// MUST be first: sets DATABASE_URL before db_client is evaluated. import "./setup_env"; import { test, expect, describe } from "bun:test"; import { explicitLinks, matchStrength, MATCH_THRESHOLD, type ConditionRowLite } from "../src/kb_outcome"; import type { KbClaim } from "../src/kb_db"; /** * 显式配对 —— 归因回环唯一的真信号。 * * 为什么要有这一套:模糊匹配在生产上判不出来。1634 次注入里 731 次 inconclusive、 * 只有 8 次给出过判定,原因是它要靠比对隔月、跨节点、各自随手写的 subject/statement * 去猜"这两行说的是不是同一件事"。agent 在记录条件的那一刻两份文本都在手上,所以 * 让它直接写编号。下面钉的是这条捷径**不能**变成后门:编号只在执行阶段成立、越界的 * 编号一律丢弃、先写者胜(否则 ingest 顺序能翻转判定)。 */ const cond = (over: Partial = {}): ConditionRowLite => ({ kind: "env", scope: "构建", subject: "远端产物", statement: "必须用 ./start.sh 拉包", payload: null, verdict: "verified", round: 1, nodeId: "n1", kbLabels: null, ...over, }); describe("explicitLinks · conditions record --kb 的解析", () => { const injected = ["c-one", "c-two", "c-three"]; test("K2 落到列表里的第二条", () => { const c = cond({ kbLabels: JSON.stringify(["K2"]) }); expect([...explicitLinks("fix", injected, [c]).keys()]).toEqual(["c-two"]); }); test("一行可以同时挂多条", () => { const c = cond({ kbLabels: JSON.stringify(["K1", "K3"]) }); expect([...explicitLinks("fix", injected, [c]).keys()]).toEqual(["c-one", "c-three"]); }); test("只认执行阶段:eval 的 K1 与 agent 看到的 K1 不是同一条知识", () => { const c = cond({ kbLabels: JSON.stringify(["K1"]) }); expect(explicitLinks("eval", injected, [c]).size).toBe(0); expect(explicitLinks("regen", injected, [c]).size).toBe(0); }); test("越界编号丢弃,不回绕也不猜", () => { expect(explicitLinks("fix", injected, [cond({ kbLabels: JSON.stringify(["K9"]) })]).size).toBe(0); expect(explicitLinks("fix", injected, [cond({ kbLabels: JSON.stringify(["K0", "notalabel"]) })]).size).toBe(0); }); test("同一编号被两行认领时,先写的那行胜出 —— 判定不能取决于 ingest 顺序", () => { const first = cond({ kbLabels: JSON.stringify(["K1"]), statement: "第一行" }); const second = cond({ kbLabels: JSON.stringify(["K1"]), statement: "第二行" }); expect(explicitLinks("fix", injected, [first, second]).get("c-one")?.statement).toBe("第一行"); }); test("损坏的 kb_labels 视为「没说」,退回模糊匹配,而不是抛错", () => { expect(explicitLinks("fix", injected, [cond({ kbLabels: "{不是JSON" })]).size).toBe(0); expect(explicitLinks("fix", injected, [cond({ kbLabels: null })]).size).toBe(0); }); }); describe("显式配对补的正是模糊匹配够不到的那一段", () => { const claim = { kind: "env", platform: "ios", scopeKey: "ios:构建", subjectKey: "maccatalyst启动参数组合", statement: "已 re-sign 的 macCatalyst 包必须用 MallocNanoZone=0 open -n 启动", } as Pick; test("同一件事、两个人各自起的名字,模糊匹配判不出来", () => { const c = cond({ kind: "env", scope: "Catalyst", subject: "Catalyst 驱动相机上滑手势与录屏冲突", statement: "起包要带 MallocNanoZone=0,否则秒退", }); expect(matchStrength(claim, c, "ios")).toBeLessThan(MATCH_THRESHOLD); // 同一行,agent 挂上编号之后就不再需要任何猜测。 const linked = explicitLinks("fix", ["k-claim"], [{ ...c, kbLabels: JSON.stringify(["K1"]) }]); expect(linked.get("k-claim")).toBeTruthy(); }); });