@agent-wiki/mcp 0.22.3 → 0.22.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +31 -0
  2. package/dist/cli.js +177 -0
  3. package/dist/cli.js.map +1 -1
  4. package/dist/evidence-migration.js +1 -1
  5. package/dist/evidence-migration.js.map +1 -1
  6. package/dist/evidence-report.d.ts +70 -1
  7. package/dist/evidence-report.d.ts.map +1 -1
  8. package/dist/evidence-report.js +228 -5
  9. package/dist/evidence-report.js.map +1 -1
  10. package/dist/evidence-report.test.js +176 -0
  11. package/dist/evidence-report.test.js.map +1 -1
  12. package/dist/evidence-search.d.ts +71 -0
  13. package/dist/evidence-search.d.ts.map +1 -1
  14. package/dist/evidence-search.js +104 -1
  15. package/dist/evidence-search.js.map +1 -1
  16. package/dist/evidence-search.test.js +58 -1
  17. package/dist/evidence-search.test.js.map +1 -1
  18. package/dist/index.d.ts +10 -0
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +5 -0
  21. package/dist/index.js.map +1 -1
  22. package/dist/okf-compat.d.ts +152 -0
  23. package/dist/okf-compat.d.ts.map +1 -0
  24. package/dist/okf-compat.js +604 -0
  25. package/dist/okf-compat.js.map +1 -0
  26. package/dist/okf-compat.test.d.ts +2 -0
  27. package/dist/okf-compat.test.d.ts.map +1 -0
  28. package/dist/okf-compat.test.js +234 -0
  29. package/dist/okf-compat.test.js.map +1 -0
  30. package/dist/okf-export.d.ts +63 -0
  31. package/dist/okf-export.d.ts.map +1 -0
  32. package/dist/okf-export.js +655 -0
  33. package/dist/okf-export.js.map +1 -0
  34. package/dist/okf-export.test.d.ts +2 -0
  35. package/dist/okf-export.test.d.ts.map +1 -0
  36. package/dist/okf-export.test.js +469 -0
  37. package/dist/okf-export.test.js.map +1 -0
  38. package/dist/okf-import.d.ts +136 -0
  39. package/dist/okf-import.d.ts.map +1 -0
  40. package/dist/okf-import.js +471 -0
  41. package/dist/okf-import.js.map +1 -0
  42. package/dist/okf-import.test.d.ts +2 -0
  43. package/dist/okf-import.test.d.ts.map +1 -0
  44. package/dist/okf-import.test.js +339 -0
  45. package/dist/okf-import.test.js.map +1 -0
  46. package/dist/okf-trust.test.d.ts +2 -0
  47. package/dist/okf-trust.test.d.ts.map +1 -0
  48. package/dist/okf-trust.test.js +223 -0
  49. package/dist/okf-trust.test.js.map +1 -0
  50. package/dist/okf.d.ts +128 -0
  51. package/dist/okf.d.ts.map +1 -0
  52. package/dist/okf.js +659 -0
  53. package/dist/okf.js.map +1 -0
  54. package/dist/search-currency.d.ts +44 -0
  55. package/dist/search-currency.d.ts.map +1 -0
  56. package/dist/search-currency.js +111 -0
  57. package/dist/search-currency.js.map +1 -0
  58. package/dist/search.d.ts +19 -0
  59. package/dist/search.d.ts.map +1 -1
  60. package/dist/search.js.map +1 -1
  61. package/dist/server.d.ts +0 -1
  62. package/dist/server.d.ts.map +1 -1
  63. package/dist/server.js +753 -49
  64. package/dist/server.js.map +1 -1
  65. package/dist/server.test.js +848 -0
  66. package/dist/server.test.js.map +1 -1
  67. package/dist/wiki-graph.d.ts +126 -0
  68. package/dist/wiki-graph.d.ts.map +1 -0
  69. package/dist/wiki-graph.js +479 -0
  70. package/dist/wiki-graph.js.map +1 -0
  71. package/dist/wiki-graph.test.d.ts +2 -0
  72. package/dist/wiki-graph.test.d.ts.map +1 -0
  73. package/dist/wiki-graph.test.js +216 -0
  74. package/dist/wiki-graph.test.js.map +1 -0
  75. package/dist/wiki.d.ts +140 -1
  76. package/dist/wiki.d.ts.map +1 -1
  77. package/dist/wiki.js +509 -23
  78. package/dist/wiki.js.map +1 -1
  79. package/dist/worklist.d.ts +43 -0
  80. package/dist/worklist.d.ts.map +1 -0
  81. package/dist/worklist.js +147 -0
  82. package/dist/worklist.js.map +1 -0
  83. package/dist/worklist.test.d.ts +2 -0
  84. package/dist/worklist.test.d.ts.map +1 -0
  85. package/dist/worklist.test.js +233 -0
  86. package/dist/worklist.test.js.map +1 -0
  87. package/docs/evidence-envelope.md +26 -1
  88. package/docs/okf-adoption-plan.md +566 -0
  89. package/docs/okf-compat-plan.md +418 -0
  90. package/docs/okf-extensions.md +245 -0
  91. package/docs/open-knowledge-format.md +280 -0
  92. package/docs/tools.md +264 -2
  93. package/package.json +1 -1
  94. package/schemas/agent-wiki-okf.schema.json +130 -0
  95. package/skills/agent-wiki/SKILL.md +7 -0
  96. package/skills/agent-wiki/references/tools-reference.md +80 -3
@@ -19,6 +19,28 @@ function cleanUp() {
19
19
  rmSync(TEST_ROOT, { recursive: true, force: true });
20
20
  }
21
21
  }
22
+ function writeValidOkfManifest(root = TEST_ROOT) {
23
+ writeFileSync(join(root, "agent-wiki.yaml"), `format: agent-wiki-okf
24
+ format_version: 0.1
25
+ name: payroll-modernization-knowledge
26
+ version: 0.1.0
27
+ license: internal-proprietary
28
+ owner: platform-team
29
+ created_at: 2026-06-20
30
+ generator:
31
+ name: agent-wiki
32
+ version: 0.22.4
33
+ source_policy:
34
+ raw_immutable: true
35
+ require_sha256: true
36
+ wiki_policy:
37
+ require_sources_for_grounded_pages: true
38
+ allow_synthesis_pages: true
39
+ evidence_policy:
40
+ allow_unsupported_pages: warn
41
+ require_abstain_signal: true
42
+ `);
43
+ }
22
44
  // We test the Wiki methods that the server handlers call,
23
45
  // since createServer() requires MCP transport setup.
24
46
  // This verifies the data layer that backs every tool.
@@ -1985,6 +2007,117 @@ describe("consolidated tool: wiki_admin", () => {
1985
2007
  expect(parsed).toHaveProperty("rawDir");
1986
2008
  expect(parsed).toHaveProperty("search");
1987
2009
  });
2010
+ it("action:format-check reports a missing OKF manifest", async () => {
2011
+ const wiki = freshWiki();
2012
+ const result = await handleTool(wiki, "wiki_admin", { action: "format-check" });
2013
+ const parsed = JSON.parse(result);
2014
+ expect(parsed.ok).toBe(false);
2015
+ expect(parsed.format).toBe("agent-wiki-okf");
2016
+ expect(parsed.expectedFormatVersion).toBe("0.1");
2017
+ expect(parsed.checked.manifest).toBe(false);
2018
+ expect(parsed.issues.some((issue) => issue.message.includes("Missing agent-wiki.yaml"))).toBe(true);
2019
+ });
2020
+ it("action:format-check accepts a valid OKF v0.1 manifest", async () => {
2021
+ const wiki = freshWiki();
2022
+ writeValidOkfManifest();
2023
+ const result = await handleTool(wiki, "wiki_admin", { action: "format-check" });
2024
+ const parsed = JSON.parse(result);
2025
+ expect(parsed.ok).toBe(true);
2026
+ expect(parsed.manifest.name).toBe("payroll-modernization-knowledge");
2027
+ expect(parsed.manifest.format_version).toBe("0.1");
2028
+ expect(parsed.checked.rawDir).toBe(true);
2029
+ expect(parsed.checked.wikiDir).toBe(true);
2030
+ expect(parsed.checked.schemasDir).toBe(true);
2031
+ expect(parsed.inventory.raw.total).toBe(0);
2032
+ expect(parsed.inventory.wiki.classes.system).toBeGreaterThanOrEqual(3);
2033
+ expect(parsed.conformance.status).toBe("pass");
2034
+ });
2035
+ it("action:format-check reports OKF package inventory and conformance warnings", async () => {
2036
+ const wiki = freshWiki();
2037
+ writeValidOkfManifest();
2038
+ wiki.rawAdd("uncompiled.txt", { content: "source not yet compiled" });
2039
+ wiki.write("unsupported-note.md", "---\ntitle: Unsupported Note\n---\nNo source yet.");
2040
+ const result = await handleTool(wiki, "wiki_admin", { action: "format-check" });
2041
+ const parsed = JSON.parse(result);
2042
+ expect(parsed.ok).toBe(true);
2043
+ expect(parsed.inventory.raw.total).toBe(1);
2044
+ expect(parsed.inventory.raw.coverage.uncoveredRaw).toBe(1);
2045
+ expect(parsed.inventory.wiki.classes.unsupported).toBe(1);
2046
+ expect(parsed.conformance.warningCount).toBeGreaterThanOrEqual(2);
2047
+ expect(parsed.issues).toEqual(expect.arrayContaining([
2048
+ expect.objectContaining({
2049
+ path: "raw/",
2050
+ message: expect.stringContaining("not referenced"),
2051
+ }),
2052
+ expect.objectContaining({
2053
+ path: "wiki/",
2054
+ message: expect.stringContaining("marked unsupported"),
2055
+ }),
2056
+ ]));
2057
+ });
2058
+ it("action:format-check rejects unknown manifest fields", async () => {
2059
+ const wiki = freshWiki();
2060
+ writeFileSync(join(TEST_ROOT, "agent-wiki.yaml"), `format: agent-wiki-okf
2061
+ format_version: 0.1
2062
+ name: typo-check
2063
+ version: 0.1.0
2064
+ license: MIT
2065
+ onwer: typo-team
2066
+ owner: platform-team
2067
+ created_at: 2026-06-20
2068
+ source_policy:
2069
+ raw_immutable: true
2070
+ require_sha256: true
2071
+ wiki_policy:
2072
+ require_sources_for_grounded_pages: true
2073
+ allow_synthesis_pages: true
2074
+ evidence_policy:
2075
+ allow_unsupported_pages: warn
2076
+ require_abstain_signal: true
2077
+ `);
2078
+ const result = await handleTool(wiki, "wiki_admin", { action: "format-check" });
2079
+ const parsed = JSON.parse(result);
2080
+ expect(parsed.ok).toBe(false);
2081
+ expect(parsed.issues).toEqual(expect.arrayContaining([
2082
+ expect.objectContaining({
2083
+ path: "agent-wiki.yaml.onwer",
2084
+ message: expect.stringContaining("Unknown manifest field"),
2085
+ }),
2086
+ ]));
2087
+ });
2088
+ it("action:format-check rejects incompatible source policy", async () => {
2089
+ const wiki = freshWiki();
2090
+ writeFileSync(join(TEST_ROOT, "agent-wiki.yaml"), `format: agent-wiki-okf
2091
+ format_version: 0.1
2092
+ name: policy-check
2093
+ version: 0.1.0
2094
+ license: MIT
2095
+ owner: platform-team
2096
+ created_at: 2026-06-20
2097
+ source_policy:
2098
+ raw_immutable: false
2099
+ require_sha256: false
2100
+ wiki_policy:
2101
+ require_sources_for_grounded_pages: true
2102
+ allow_synthesis_pages: true
2103
+ evidence_policy:
2104
+ allow_unsupported_pages: warn
2105
+ require_abstain_signal: true
2106
+ `);
2107
+ const result = await handleTool(wiki, "wiki_admin", { action: "format-check" });
2108
+ const parsed = JSON.parse(result);
2109
+ expect(parsed.ok).toBe(false);
2110
+ expect(parsed.issues).toEqual(expect.arrayContaining([
2111
+ expect.objectContaining({
2112
+ path: "agent-wiki.yaml:source_policy.raw_immutable",
2113
+ message: expect.stringContaining("must be true"),
2114
+ }),
2115
+ expect.objectContaining({
2116
+ path: "agent-wiki.yaml:source_policy.require_sha256",
2117
+ message: expect.stringContaining("must be true"),
2118
+ }),
2119
+ ]));
2120
+ });
1988
2121
  it("action:rebuild runs without error", async () => {
1989
2122
  const wiki = freshWiki();
1990
2123
  const result = await handleTool(wiki, "wiki_admin", { action: "rebuild" });
@@ -2037,6 +2170,651 @@ describe("consolidated tool: wiki_admin", () => {
2037
2170
  expect(parsed.writtenTo).toBeDefined();
2038
2171
  expect(existsSync(join(wiki.config.wikiDir, "evidence-report.md"))).toBe(true);
2039
2172
  });
2173
+ it("action:rebuild with evidence_report:true also writes the evidence report", async () => {
2174
+ const wiki = freshWiki();
2175
+ const reportPath = join(wiki.config.wikiDir, "evidence-report.md");
2176
+ expect(existsSync(reportPath)).toBe(false);
2177
+ const result = await handleTool(wiki, "wiki_admin", {
2178
+ action: "rebuild",
2179
+ evidence_report: true,
2180
+ });
2181
+ const parsed = JSON.parse(result);
2182
+ expect(parsed.ok).toBe(true);
2183
+ expect(parsed.message).toMatch(/Evidence report written/);
2184
+ expect(existsSync(reportPath)).toBe(true);
2185
+ // The Phase 2b readiness section should appear in the persisted report.
2186
+ const content = readFileSync(reportPath, "utf-8");
2187
+ expect(content).toContain("## Phase 2b readiness");
2188
+ // On success, no structured failure field is emitted — the field
2189
+ // exists only when regen failed (parity with the batch path's
2190
+ // deferred-entry mutation shape).
2191
+ expect(parsed.evidenceReport).toBeUndefined();
2192
+ });
2193
+ it("action:rebuild with okf_report:true writes the OKF package report", async () => {
2194
+ const wiki = freshWiki();
2195
+ writeValidOkfManifest();
2196
+ const reportPath = join(wiki.config.workspace, "evidence", "okf-report.json");
2197
+ expect(existsSync(reportPath)).toBe(false);
2198
+ const result = await handleTool(wiki, "wiki_admin", {
2199
+ action: "rebuild",
2200
+ okf_report: true,
2201
+ });
2202
+ const parsed = JSON.parse(result);
2203
+ expect(parsed.ok).toBe(true);
2204
+ expect(parsed.message).toMatch(/OKF report written/);
2205
+ expect(parsed.okfReport).toBeUndefined();
2206
+ expect(existsSync(reportPath)).toBe(true);
2207
+ const report = JSON.parse(readFileSync(reportPath, "utf-8"));
2208
+ expect(report.manifest.name).toBe("payroll-modernization-knowledge");
2209
+ expect(report.inventory).toHaveProperty("raw");
2210
+ expect(report.inventory).toHaveProperty("wiki");
2211
+ expect(report.inventory.evidence.okfReport).toBe(true);
2212
+ expect(report.conformance.status).toBe("pass");
2213
+ });
2214
+ it("action:rebuild without evidence_report leaves the report file untouched", async () => {
2215
+ const wiki = freshWiki();
2216
+ const reportPath = join(wiki.config.wikiDir, "evidence-report.md");
2217
+ expect(existsSync(reportPath)).toBe(false);
2218
+ await handleTool(wiki, "wiki_admin", { action: "rebuild" });
2219
+ expect(existsSync(reportPath)).toBe(false);
2220
+ });
2221
+ });
2222
+ describe("contradictions: search envelope + wiki_admin reconcile", () => {
2223
+ beforeEach(cleanUp);
2224
+ afterEach(() => { vi.restoreAllMocks(); cleanUp(); });
2225
+ // "zebrafish" appears on one page only, so the search envelope starts out strong.
2226
+ function seed() {
2227
+ const wiki = freshWiki();
2228
+ wiki.write("yolo-origin.md", "---\ntitle: YOLO Origin\ntype: concept\ntags: [yolo]\nsources: [raw/redmon.pdf]\n---\nZebrafish notes. YOLO was released in 2015.");
2229
+ wiki.write("yolo-history.md", "---\ntitle: YOLO History\ntype: concept\ntags: [yolo]\nsources: [raw/blog.md]\n---\nA timeline. YOLO was released in 2018.");
2230
+ for (let i = 0; i < 6; i++) {
2231
+ wiki.write(`filler-${i}.md`, `---\ntitle: Filler ${i}\ntype: note\ntags: [misc]\nsources: [raw/x.md]\n---\nUnrelated text number ${i} about gardening.`);
2232
+ }
2233
+ return wiki;
2234
+ }
2235
+ const search = async (wiki, extra = {}) => JSON.parse(await handleTool(wiki, "wiki_search", { query: "zebrafish", ...extra }));
2236
+ const admin = async (wiki, args) => JSON.parse(await handleTool(wiki, "wiki_admin", args));
2237
+ it("without an index, search runs no detection and the envelope is untouched", async () => {
2238
+ const wiki = seed();
2239
+ const detect = vi.spyOn(Wiki.prototype, "detectContradictions");
2240
+ expect(existsSync(join(TEST_ROOT, ".contradiction-index.json"))).toBe(false);
2241
+ const r = await search(wiki);
2242
+ expect(r.evidence.confidence).toBe("strong");
2243
+ expect(r.evidence.rationale).not.toMatch(/Disputed/);
2244
+ expect(detect).not.toHaveBeenCalled();
2245
+ });
2246
+ it("after lint, a disputed top hit is weak and names the counter-claim page", async () => {
2247
+ const wiki = seed();
2248
+ const lint = await admin(wiki, { action: "lint" });
2249
+ expect(lint.contradictions).toHaveLength(1);
2250
+ const index = JSON.parse(readFileSync(join(TEST_ROOT, ".contradiction-index.json"), "utf-8"));
2251
+ expect(Object.keys(index.pages).sort()).toEqual(["yolo-history.md", "yolo-origin.md"]);
2252
+ const detect = vi.spyOn(Wiki.prototype, "detectContradictions");
2253
+ const r = await search(wiki);
2254
+ expect(r.evidence).toMatchObject({ confidence: "weak", abstain: false });
2255
+ expect(r.evidence.rationale).toMatch(/wiki\/yolo-origin\.md conflicts with wiki\/yolo-history\.md/);
2256
+ expect(r.evidence.provenance).toContainEqual({ wikiPage: "wiki/yolo-history.md" });
2257
+ expect(detect).not.toHaveBeenCalled(); // the lookup reads the index, it does not re-detect
2258
+ const read = await search(wiki, { read_top_n: 1 });
2259
+ expect(read.evidence.rationale).toMatch(/Disputed/);
2260
+ const legacy = JSON.parse(await handleTool(wiki, "wiki_search_read", { query: "zebrafish" }));
2261
+ expect(legacy.evidence.rationale).toMatch(/Disputed/);
2262
+ });
2263
+ it("rebuild writes the index too, and an undisputed hit stays strong", async () => {
2264
+ const wiki = seed();
2265
+ await admin(wiki, { action: "rebuild" });
2266
+ expect((await search(wiki)).evidence.confidence).toBe("weak");
2267
+ const other = JSON.parse(await handleTool(wiki, "wiki_search", { query: "gardening number 3" }));
2268
+ expect(other.evidence.rationale).not.toMatch(/Disputed/);
2269
+ });
2270
+ it("reconcile without a winner shows both claims with their sources and decides nothing", async () => {
2271
+ const wiki = seed();
2272
+ const r = await admin(wiki, { action: "reconcile", page_a: "yolo-origin.md", page_b: "yolo-history" });
2273
+ expect(r.contradictions).toHaveLength(1);
2274
+ expect(r.contradictions[0].a).toMatchObject({ page: "yolo-origin.md", excerpt: "released in 2015", sources: ["raw/redmon.pdf"] });
2275
+ expect(r.contradictions[0].b).toMatchObject({ page: "yolo-history.md", excerpt: "released in 2018", sources: ["raw/blog.md"] });
2276
+ expect(r.evidence).toMatchObject({ confidence: "weak", basis: "inferred", abstain: false });
2277
+ expect(r.evidence.provenance).toContainEqual({ raw: "raw/redmon.pdf" });
2278
+ expect(wiki.list().some((p) => p.startsWith("reconciliation-"))).toBe(false);
2279
+ });
2280
+ it("reconcile with a winner writes the resolution page, stays inferred, and search stops downgrading", async () => {
2281
+ const wiki = seed();
2282
+ await admin(wiki, { action: "lint" });
2283
+ const before = wiki.read("yolo-history.md").content;
2284
+ const r = await admin(wiki, {
2285
+ action: "reconcile", page_a: "yolo-origin.md", page_b: "yolo-history.md",
2286
+ winner: "yolo-origin", note: "The original paper is dated 2015.",
2287
+ });
2288
+ expect(r).toMatchObject({ ok: true, winner: "yolo-origin.md", superseded: "yolo-history.md", still_disputed: 0 });
2289
+ expect(r.evidence.basis).toBe("inferred");
2290
+ expect(r.evidence.confidence).not.toBe("strong");
2291
+ const page = wiki.read(r.resolution_page);
2292
+ expect(page.frontmatter).toMatchObject({
2293
+ type: "synthesis",
2294
+ reconciles: ["yolo-history.md", "yolo-origin.md"],
2295
+ reconciled_claims: ["released in year"],
2296
+ decisions: [{
2297
+ claim: "released in year",
2298
+ winner: "yolo-origin.md",
2299
+ superseded: "yolo-history.md",
2300
+ kept_excerpt: "released in 2015",
2301
+ superseded_excerpt: "released in 2018",
2302
+ note: "The original paper is dated 2015.",
2303
+ }],
2304
+ sources: ["raw/redmon.pdf", "raw/blog.md"],
2305
+ });
2306
+ expect(r.resolution_page).toMatch(/^reconciliation-yolo-history-vs-yolo-origin-[0-9a-f]{8}\.md$/);
2307
+ expect(page.content).toContain("released in 2015");
2308
+ expect(page.content).toContain("released in 2018");
2309
+ expect(page.content).toContain("The original paper is dated 2015.");
2310
+ expect(wiki.read("yolo-history.md").content).toBe(before); // the losing page is not edited
2311
+ const s = await search(wiki);
2312
+ expect(s.evidence.confidence).toBe("strong");
2313
+ expect(s.evidence.rationale).not.toMatch(/Disputed/);
2314
+ const lint = await admin(wiki, { action: "lint" });
2315
+ expect(lint.contradictions).toHaveLength(0); // settled, and the resolution page is not a third claim
2316
+ expect(lint.reconciledContradictions).toBe(1);
2317
+ const again = await admin(wiki, { action: "reconcile", page_a: "yolo-origin.md", page_b: "yolo-history.md" });
2318
+ expect(again.contradictions).toEqual([]);
2319
+ expect(again.already_reconciled).toEqual([{ claim: "released in year", resolution: r.resolution_page }]);
2320
+ expect(again.evidence.abstain).toBe(true);
2321
+ });
2322
+ it("a new disagreement between an already reconciled pair is reported again", async () => {
2323
+ const wiki = seed();
2324
+ await admin(wiki, { action: "reconcile", page_a: "yolo-origin.md", page_b: "yolo-history.md", winner: "yolo-origin.md" });
2325
+ wiki.write("yolo-origin.md", "---\ntitle: YOLO Origin\ntype: concept\ntags: [yolo]\nsources: [raw/redmon.pdf]\n---\nZebrafish notes. YOLO was released in 2015. It was announced in 2014.");
2326
+ wiki.write("yolo-history.md", "---\ntitle: YOLO History\ntype: concept\ntags: [yolo]\nsources: [raw/blog.md]\n---\nA timeline. YOLO was released in 2018. It was announced in 2016.");
2327
+ const lint = await admin(wiki, { action: "lint" });
2328
+ expect(lint.contradictions.map((c) => c.claim)).toEqual(["announced in year"]);
2329
+ expect(lint.reconciledContradictions).toBe(1);
2330
+ });
2331
+ it("a second reconciliation of the pair keeps the first decision, its evidence and its reason", async () => {
2332
+ const wiki = seed();
2333
+ const first = await admin(wiki, {
2334
+ action: "reconcile", page_a: "yolo-origin.md", page_b: "yolo-history.md",
2335
+ winner: "yolo-origin.md", note: "The original paper is dated 2015.",
2336
+ });
2337
+ wiki.write("yolo-origin.md", "---\ntitle: YOLO Origin\ntype: concept\ntags: [yolo]\nsources: [raw/redmon.pdf]\n---\nZebrafish notes. YOLO was released in 2015. It was announced in 2014.");
2338
+ wiki.write("yolo-history.md", "---\ntitle: YOLO History\ntype: concept\ntags: [yolo]\nsources: [raw/blog.md]\n---\nA timeline. YOLO was released in 2018. It was announced in 2016.");
2339
+ // the second claim goes the other way
2340
+ const second = await admin(wiki, {
2341
+ action: "reconcile", page_a: "yolo-origin.md", page_b: "yolo-history.md",
2342
+ winner: "yolo-history.md", note: "The blog cites the announcement talk.",
2343
+ });
2344
+ expect(second.resolution_page).toBe(first.resolution_page);
2345
+ expect(second.reconciled_claims).toEqual(["announced in year"]);
2346
+ const page = wiki.read(second.resolution_page);
2347
+ expect(page.frontmatter.reconciled_claims).toEqual(["released in year", "announced in year"]);
2348
+ expect(page.frontmatter.decisions).toMatchObject([
2349
+ { claim: "released in year", winner: "yolo-origin.md", superseded: "yolo-history.md", note: "The original paper is dated 2015.", kept_excerpt: "released in 2015" },
2350
+ { claim: "announced in year", winner: "yolo-history.md", superseded: "yolo-origin.md", note: "The blog cites the announcement talk.", kept_excerpt: "announced in 2016" },
2351
+ ]);
2352
+ expect(page.content).toContain("The original paper is dated 2015.");
2353
+ expect(page.content).toContain('Kept — [[yolo-origin]]: "released in 2015"');
2354
+ expect(page.content).toContain('Kept — [[yolo-history]]: "announced in 2016"');
2355
+ const lint = await admin(wiki, { action: "lint" });
2356
+ expect(lint.contradictions).toHaveLength(0);
2357
+ expect(lint.reconciledContradictions).toBe(2);
2358
+ });
2359
+ it("pairs whose names flatten alike get different pages, and a foreign page is never overwritten", async () => {
2360
+ const wiki = freshWiki();
2361
+ const fm = (title) => `---\ntitle: ${title}\ntype: concept\ntags: [yolo]\nsources: [raw/x.md]\n---\n`;
2362
+ wiki.write("a/b.md", fm("Nested") + "YOLO was released in 2015.");
2363
+ wiki.write("a-b.md", fm("Flat") + "YOLO was released in 2016.");
2364
+ wiki.write("c.md", fm("Other") + "YOLO was released in 2018.");
2365
+ const nested = await admin(wiki, { action: "reconcile", page_a: "a/b.md", page_b: "c.md", winner: "c.md", note: "nested" });
2366
+ const flat = await admin(wiki, { action: "reconcile", page_a: "a-b.md", page_b: "c.md", winner: "a-b.md", note: "flat" });
2367
+ expect(nested.resolution_page).not.toBe(flat.resolution_page);
2368
+ expect(wiki.read(nested.resolution_page).frontmatter).toMatchObject({ reconciles: ["a/b.md", "c.md"], decisions: [{ winner: "c.md", note: "nested" }] });
2369
+ expect(wiki.read(flat.resolution_page).frontmatter).toMatchObject({ reconciles: ["a-b.md", "c.md"], decisions: [{ winner: "a-b.md", note: "flat" }] });
2370
+ // a page that sits at the destination but belongs to another pair is left alone
2371
+ wiki.write("d.md", fm("Dee") + "YOLO was released in 2019.");
2372
+ const probe = await admin(wiki, { action: "reconcile", page_a: "c.md", page_b: "d.md", winner: "d.md" });
2373
+ const squatter = "---\ntitle: Squatter\ntype: synthesis\nreconciles: [x.md, y.md]\nreconciled_claims: []\n---\nNot yours.";
2374
+ wiki.write(probe.resolution_page, squatter);
2375
+ wiki.write("d.md", fm("Dee") + "YOLO was released in 2019. It was announced in 2012.");
2376
+ wiki.write("c.md", fm("Other") + "YOLO was released in 2018. It was announced in 2013.");
2377
+ await expect(admin(wiki, { action: "reconcile", page_a: "c.md", page_b: "d.md", winner: "d.md" }))
2378
+ .rejects.toThrow(/does not belong to c\.md \/ d\.md/);
2379
+ expect(wiki.read(probe.resolution_page).content).toContain("Not yours.");
2380
+ });
2381
+ it("reconcile rejects bad input and abstains when the pair does not conflict", async () => {
2382
+ const wiki = seed();
2383
+ await expect(admin(wiki, { action: "reconcile", page_a: "yolo-origin.md" })).rejects.toThrow(/"page_b" is required/);
2384
+ await expect(admin(wiki, { action: "reconcile", page_a: "yolo-origin.md", page_b: "nope.md" })).rejects.toThrow(/no such page/);
2385
+ await expect(admin(wiki, { action: "reconcile", page_a: "yolo-origin.md", page_b: "yolo-origin" })).rejects.toThrow(/same page/);
2386
+ await expect(admin(wiki, {
2387
+ action: "reconcile", page_a: "yolo-origin.md", page_b: "yolo-history.md", winner: "filler-0.md",
2388
+ })).rejects.toThrow(/winner must be page_a or page_b/);
2389
+ const none = await admin(wiki, { action: "reconcile", page_a: "yolo-origin.md", page_b: "filler-0.md" });
2390
+ expect(none.evidence).toMatchObject({ confidence: "absent", abstain: true });
2391
+ });
2392
+ });
2393
+ describe("source drift: sources_sha sealing + search envelope", () => {
2394
+ beforeEach(cleanUp);
2395
+ afterEach(() => { vi.restoreAllMocks(); cleanUp(); });
2396
+ const PAGE = (extra = "") => `---\ntitle: Quarterly Numbers\ntype: concept\ntags: [finance]\nsources: [raw/report.md, "https://example.com/q3"]\n---\nZebrafish revenue summary.${extra}`;
2397
+ function seed() {
2398
+ const wiki = freshWiki();
2399
+ wiki.rawAdd("report.md", { content: "Q3 revenue: 10" });
2400
+ wiki.rawAdd("other.md", { content: "unrelated" });
2401
+ wiki.write("quarterly-numbers.md", PAGE());
2402
+ for (let i = 0; i < 6; i++) {
2403
+ wiki.write(`filler-${i}.md`, `---\ntitle: Filler ${i}\ntype: note\ntags: [misc]\nsources: [raw/other.md]\n---\nUnrelated text number ${i} about gardening.`);
2404
+ }
2405
+ return wiki;
2406
+ }
2407
+ const search = async (wiki, tool = "wiki_search", extra = {}) => JSON.parse(await handleTool(wiki, tool, { query: "zebrafish", ...extra }));
2408
+ const admin = async (wiki, args) => JSON.parse(await handleTool(wiki, "wiki_admin", args));
2409
+ const shaOf = (wiki, path) => wiki.rawList().find((r) => r.path === path).sha256;
2410
+ // Raw files are immutable through the API; a changed source is simulated the way it
2411
+ // happens in practice: the file and its sidecar are replaced on disk.
2412
+ function replaceRaw(wiki, path, content) {
2413
+ rmSync(join(wiki.config.rawDir, path));
2414
+ rmSync(join(wiki.config.rawDir, path + ".meta.yaml"));
2415
+ wiki.rawAdd(path, { content });
2416
+ }
2417
+ it("wiki_write records the SHA of each cited raw file, and only of those", () => {
2418
+ const wiki = seed();
2419
+ const fm = wiki.read("quarterly-numbers.md").frontmatter;
2420
+ expect(fm.sources_sha).toEqual({ "raw/report.md": shaOf(wiki, "report.md") });
2421
+ expect(fm.sources).toEqual(["raw/report.md", "https://example.com/q3"]);
2422
+ });
2423
+ it("drops sources_sha when no cited source is a raw file, and ignores a hand-written one", () => {
2424
+ const wiki = seed();
2425
+ wiki.write("web-only.md", "---\ntitle: Web Only\ntype: concept\nsources: [\"https://example.com/x\", raw/does-not-exist.md]\nsources_sha:\n raw/report.md: deadbeef\n---\nBody.");
2426
+ expect(wiki.read("web-only.md").frontmatter.sources_sha).toBeUndefined();
2427
+ });
2428
+ it("an unchanged source keeps the envelope strong, and lint reports nothing", async () => {
2429
+ const wiki = seed();
2430
+ const lint = await admin(wiki, { action: "lint" });
2431
+ expect(lint.issues.filter((i) => i.category === "source-drift")).toEqual([]);
2432
+ const index = JSON.parse(readFileSync(join(TEST_ROOT, ".source-drift-index.json"), "utf-8"));
2433
+ expect(index.pages).toEqual({});
2434
+ expect(index.sealedPages).toBe(7);
2435
+ expect((await search(wiki)).evidence.confidence).toBe("strong");
2436
+ });
2437
+ it("a changed source: lint flags it, search drops to weak, and frontmatter is not rewritten", async () => {
2438
+ const wiki = seed();
2439
+ const before = readFileSync(join(wiki.config.wikiDir, "quarterly-numbers.md"), "utf-8");
2440
+ replaceRaw(wiki, "report.md", "Q3 revenue: 12 (restated)");
2441
+ expect((await search(wiki)).evidence.confidence).toBe("strong"); // no index yet: nothing extra happens
2442
+ const lint = await admin(wiki, { action: "lint" });
2443
+ const issue = lint.issues.find((i) => i.category === "source-drift");
2444
+ expect(issue).toMatchObject({ page: "quarterly-numbers.md", severity: "warning" });
2445
+ expect(issue.message).toBe("Cited source raw/report.md has changed since this page was written");
2446
+ expect(readFileSync(join(wiki.config.wikiDir, "quarterly-numbers.md"), "utf-8")).toBe(before);
2447
+ for (const [tool, extra] of [["wiki_search", {}], ["wiki_search", { read_top_n: 1 }], ["wiki_search_read", {}]]) {
2448
+ const r = await search(wiki, tool, extra);
2449
+ expect(r.evidence).toMatchObject({ confidence: "weak", abstain: false });
2450
+ expect(r.evidence.rationale).toContain("cited raw source has changed since this page was written");
2451
+ expect(r.evidence.rationale).toContain("wiki/quarterly-numbers.md: raw/report.md has changed");
2452
+ }
2453
+ });
2454
+ it("writing the page again re-seals it and the envelope is strong again", async () => {
2455
+ const wiki = seed();
2456
+ replaceRaw(wiki, "report.md", "Q3 revenue: 12 (restated)");
2457
+ await admin(wiki, { action: "rebuild" });
2458
+ expect((await search(wiki)).evidence.confidence).toBe("weak");
2459
+ wiki.write("quarterly-numbers.md", PAGE(" Restated to 12."));
2460
+ expect(wiki.read("quarterly-numbers.md").frontmatter.sources_sha).toEqual({ "raw/report.md": shaOf(wiki, "report.md") });
2461
+ await admin(wiki, { action: "rebuild" });
2462
+ const r = await search(wiki);
2463
+ expect(r.evidence.confidence).toBe("strong");
2464
+ expect(r.evidence.rationale).not.toMatch(/Source drift/);
2465
+ });
2466
+ it("a newer version added after the page was written counts as drift; one that predates it does not", async () => {
2467
+ const wiki = seed();
2468
+ await new Promise((res) => setTimeout(res, 15));
2469
+ wiki.rawAdd("report.md", { content: "Q3 revenue: 12", autoVersion: true }); // -> report_v2.md
2470
+ const lint = await admin(wiki, { action: "lint" });
2471
+ const issue = lint.issues.find((i) => i.category === "source-drift");
2472
+ expect(issue.message).toBe("Cited source raw/report.md has a newer version (raw/report_v2.md) added after this page was written");
2473
+ expect((await search(wiki)).evidence.rationale).toContain("raw/report.md has a newer version (raw/report_v2.md)");
2474
+ // Written after v2 exists and still citing v1: a choice the author made with v2 in view.
2475
+ await new Promise((res) => setTimeout(res, 15));
2476
+ wiki.write("quarterly-numbers.md", PAGE(" Still the original figures on purpose."));
2477
+ const again = await admin(wiki, { action: "lint" });
2478
+ expect(again.issues.filter((i) => i.category === "source-drift")).toEqual([]);
2479
+ });
2480
+ it("a citation written with ./ or ../ names the same file and is not reported as missing", async () => {
2481
+ const wiki = seed();
2482
+ wiki.rawAdd("sub/deep.md", { content: "deep" });
2483
+ wiki.write("odd-paths.md", "---\ntitle: Odd Paths\ntype: concept\nsources: [raw/./report.md, raw/sub/../report.md, ./raw/sub/deep.md, \"raw/../../outside.md\"]\n---\nBody.");
2484
+ const sha = shaOf(wiki, "report.md");
2485
+ expect(wiki.read("odd-paths.md").frontmatter.sources_sha).toEqual({
2486
+ "raw/./report.md": sha,
2487
+ "raw/sub/../report.md": sha,
2488
+ "./raw/sub/deep.md": shaOf(wiki, "sub/deep.md"),
2489
+ });
2490
+ const clean = await admin(wiki, { action: "lint" });
2491
+ expect(clean.issues.filter((i) => i.category === "source-drift")).toEqual([]);
2492
+ // and when that file really does get a newer version, both spellings see it
2493
+ await new Promise((res) => setTimeout(res, 15));
2494
+ wiki.rawAdd("report.md", { content: "v2", autoVersion: true });
2495
+ const lint = await admin(wiki, { action: "lint" });
2496
+ const drift = lint.issues.filter((i) => i.category === "source-drift" && i.page === "odd-paths.md");
2497
+ expect(drift.map((i) => i.message).sort()).toEqual([
2498
+ "Cited source raw/./report.md has a newer version (raw/report_v2.md) added after this page was written",
2499
+ "Cited source raw/sub/../report.md has a newer version (raw/report_v2.md) added after this page was written",
2500
+ ]);
2501
+ });
2502
+ it("a cited file the raw scan does not list (dot-prefixed path) is not reported as missing", async () => {
2503
+ const wiki = seed();
2504
+ mkdirSync(join(wiki.config.rawDir, ".config"), { recursive: true });
2505
+ writeFileSync(join(wiki.config.rawDir, ".config", "report.md"), "hidden but real");
2506
+ wiki.write("hidden-source.md", "---\ntitle: Hidden Source\ntype: concept\nsources: [raw/.config/report.md]\n---\nBody.");
2507
+ expect(Object.keys(wiki.read("hidden-source.md").frontmatter.sources_sha)).toEqual(["raw/.config/report.md"]);
2508
+ const clean = await admin(wiki, { action: "lint" });
2509
+ expect(clean.issues.filter((i) => i.category === "source-drift")).toEqual([]);
2510
+ writeFileSync(join(wiki.config.rawDir, ".config", "report.md"), "hidden and changed");
2511
+ const lint = await admin(wiki, { action: "lint" });
2512
+ expect(lint.issues.find((i) => i.category === "source-drift").message)
2513
+ .toBe("Cited source raw/.config/report.md has changed since this page was written");
2514
+ });
2515
+ it("a superseded entry without a usable newerVersion still reads as a sentence", async () => {
2516
+ const { describeSourceDrift } = await import("./wiki.js");
2517
+ expect(describeSourceDrift({ reason: "superseded" })).toBe("has a newer version added after this page was written");
2518
+ expect(describeSourceDrift({ reason: "superseded", newerVersion: "raw/report_v2.md" }))
2519
+ .toBe("has a newer version (raw/report_v2.md) added after this page was written");
2520
+ });
2521
+ it("a cited source that is gone is reported as missing", async () => {
2522
+ const wiki = seed();
2523
+ rmSync(join(wiki.config.rawDir, "report.md"));
2524
+ rmSync(join(wiki.config.rawDir, "report.md.meta.yaml"));
2525
+ const lint = await admin(wiki, { action: "lint" });
2526
+ const issue = lint.issues.find((i) => i.category === "source-drift");
2527
+ expect(issue.message).toBe("Cited source raw/report.md no longer exists");
2528
+ });
2529
+ it("pages written before sealing existed are counted, never downgraded", async () => {
2530
+ const wiki = seed();
2531
+ // An old page: grounded, but with no sources_sha on disk.
2532
+ writeFileSync(join(wiki.config.wikiDir, "quarterly-numbers.md"), "---\ntitle: Quarterly Numbers\ntype: concept\ntags: [finance]\nsources:\n - raw/report.md\nupdated: 2026-01-01T00:00:00.000Z\n---\nZebrafish revenue summary.\n");
2533
+ replaceRaw(wiki, "report.md", "Q3 revenue: 12 (restated)");
2534
+ const lint = await admin(wiki, { action: "lint" });
2535
+ expect(lint.issues.filter((i) => i.category === "source-drift")).toEqual([]);
2536
+ const index = JSON.parse(readFileSync(join(TEST_ROOT, ".source-drift-index.json"), "utf-8"));
2537
+ expect(index.unsealedPages).toBe(1);
2538
+ expect((await search(wiki)).evidence.rationale).not.toMatch(/Source drift/);
2539
+ });
2540
+ it("the search hot path reads the index only: no page or raw scan", async () => {
2541
+ const wiki = seed();
2542
+ replaceRaw(wiki, "report.md", "changed");
2543
+ await admin(wiki, { action: "lint" });
2544
+ const scan = vi.spyOn(wiki, "sourceDriftState");
2545
+ expect((await search(wiki)).evidence.confidence).toBe("weak");
2546
+ expect(scan).not.toHaveBeenCalled();
2547
+ });
2548
+ it("the evidence report lists drifted pages", async () => {
2549
+ const wiki = seed();
2550
+ replaceRaw(wiki, "report.md", "changed");
2551
+ const r = await admin(wiki, { action: "evidence-report" });
2552
+ expect(r.report.sourceDrift).toMatchObject({
2553
+ sealedPages: 7,
2554
+ unsealedPages: 0,
2555
+ driftedPages: 1,
2556
+ pages: [{ page: "quarterly-numbers.md", sources: [{ source: "raw/report.md", detail: "has changed since this page was written" }] }],
2557
+ });
2558
+ expect(r.markdown).toContain("## Source drift");
2559
+ expect(r.markdown).toContain("- 7 pages sealed");
2560
+ expect(r.markdown).toContain("- 1 drifted");
2561
+ expect(r.markdown).toContain("`quarterly-numbers.md` — `raw/report.md` has changed since this page was written");
2562
+ });
2563
+ });
2564
+ describe("reading an OKF v0.3 bundle placed in wiki/", () => {
2565
+ beforeEach(cleanUp);
2566
+ afterEach(cleanUp);
2567
+ // A small hand-written bundle in upstream OKF v0.3 shape: Markdown links, sources as
2568
+ // mappings, trust and lifecycle fields, index.md and log.md as §8 and §9 define them.
2569
+ const FILES = {
2570
+ "index.md": [
2571
+ "---",
2572
+ 'okf_version: "0.3"',
2573
+ "title: Zebra Retail",
2574
+ "description: Tables and metrics for Zebra Retail. Use it for margin questions.",
2575
+ "license: CC-BY-4.0",
2576
+ "x-zebra-owner: team:finance",
2577
+ "---",
2578
+ "",
2579
+ "# Subdirectories",
2580
+ "",
2581
+ "* [tables](tables/index.md) - Warehouse tables.",
2582
+ "* [metrics](metrics/index.md) - Headline numbers.",
2583
+ "",
2584
+ ].join("\n"),
2585
+ "log.md": "# Directory Update Log\n\n## 2026-11-20\n* **Creation**: Added [Gross margin](metrics/gross-margin.md).\n",
2586
+ "tables/index.md": "# Tables\n\n* [Orders](orders.md) - One row per order.\n",
2587
+ "metrics/index.md": "# Metrics\n\n* [Gross margin](gross-margin.md) - Revenue minus cost of goods.\n",
2588
+ "metrics/log.md": "# Metrics Log\n\n## 2026-11-20\n* **Creation**: Added [Gross margin](gross-margin.md).\n",
2589
+ "tables/orders.md": [
2590
+ "---",
2591
+ "type: BigQuery Table",
2592
+ "title: Orders",
2593
+ "description: One row per order.",
2594
+ "resource: bigquery://zebra.sales.orders",
2595
+ "tags: warehouse",
2596
+ "sources:",
2597
+ " - id: dbt-model",
2598
+ " resource: https://example.com/dbt/orders",
2599
+ " author: team:data-eng",
2600
+ " usage_count: 1200",
2601
+ 'generated: { by: reference_agent/gemini-2.5-pro, at: "2026-11-01T00:00:00Z" }',
2602
+ "---",
2603
+ "The orders table. Margin is defined in [gross margin](../metrics/gross-margin.md).",
2604
+ "",
2605
+ ].join("\n"),
2606
+ "metrics/gross-margin.md": [
2607
+ "---",
2608
+ "type: Metric",
2609
+ "title: Gross margin",
2610
+ "sources:",
2611
+ " - { resource: /tables/orders.md }",
2612
+ " - { resource: https://example.com/finance/policy, x-zebra-reviewed: true }",
2613
+ 'generated: { by: reference_agent/gemini-2.5-pro, at: "2026-11-01T00:00:00Z" }',
2614
+ "verified:",
2615
+ ' - { by: "human:ana", at: "2026-11-10T09:00:00Z" }',
2616
+ "status: stable",
2617
+ 'stale_after: "2099-01-01T00:00:00Z"',
2618
+ "x-zebra-owner: human:ana",
2619
+ "---",
2620
+ "Zebrafish gross margin is revenue minus cost of goods, from the [orders table](/tables/orders.md).",
2621
+ "",
2622
+ ].join("\n"),
2623
+ "metrics/gross-margin-legacy.md": [
2624
+ "---",
2625
+ "type: Metric",
2626
+ "title: Gross margin (legacy)",
2627
+ "status: deprecated",
2628
+ "superseded_by: /metrics/gross-margin.md",
2629
+ "verified: { by: \"process:nightly\", at: \"2026-01-05T02:00:00Z\" }",
2630
+ "---",
2631
+ "Quokka margin, the old definition that left out returns.",
2632
+ "",
2633
+ ].join("\n"),
2634
+ "metrics/weekly-revenue.md": [
2635
+ "---",
2636
+ "type: Metric",
2637
+ "title: Weekly revenue",
2638
+ 'stale_after: "2026-01-01"',
2639
+ "---",
2640
+ "Wombat weekly revenue from [orders](../tables/orders.md).",
2641
+ "",
2642
+ ].join("\n"),
2643
+ "README.md": "# About this bundle\n\nNot a concept: no frontmatter.\n",
2644
+ };
2645
+ function seed() {
2646
+ const wiki = freshWiki();
2647
+ for (const [rel, content] of Object.entries(FILES)) {
2648
+ const full = join(wiki.config.wikiDir, rel);
2649
+ mkdirSync(join(full, ".."), { recursive: true });
2650
+ writeFileSync(full, content);
2651
+ }
2652
+ return wiki;
2653
+ }
2654
+ const call = async (wiki, tool, args) => JSON.parse(await handleTool(wiki, tool, args));
2655
+ it("reads sources given as mappings and a scalar tag", () => {
2656
+ const wiki = seed();
2657
+ const orders = wiki.read("tables/orders.md");
2658
+ expect(orders.sources).toEqual(["https://example.com/dbt/orders"]);
2659
+ expect(orders.tags).toEqual(["warehouse"]);
2660
+ expect(wiki.read("metrics/gross-margin.md").sources).toEqual(["/tables/orders.md", "https://example.com/finance/policy"]);
2661
+ });
2662
+ it("builds the graph from Markdown links, in both path forms", async () => {
2663
+ const wiki = seed();
2664
+ const back = await call(wiki, "wiki_graph", { query_type: "backlinks", page: "tables/orders" });
2665
+ expect(back.backlinks.map((b) => b.page).sort()).toEqual([
2666
+ "metrics/gross-margin.md", "metrics/weekly-revenue.md", "tables/index.md",
2667
+ ]);
2668
+ const path = await call(wiki, "wiki_graph", { query_type: "shortest_path", from: "metrics/weekly-revenue", to: "metrics/gross-margin" });
2669
+ expect(path.path.map((p) => p.page)).toEqual(["metrics/weekly-revenue.md", "tables/orders.md", "metrics/gross-margin.md"]);
2670
+ const broken = await call(wiki, "wiki_graph", { query_type: "broken_links" });
2671
+ expect(broken.count).toBe(0);
2672
+ });
2673
+ it("a Markdown link names one file: no basename fallback to a page elsewhere", async () => {
2674
+ const wiki = seed();
2675
+ // /orders.md does not exist; tables/orders.md does and has the same basename.
2676
+ writeFileSync(join(wiki.config.wikiDir, "metrics", "returns.md"), "---\ntype: Metric\ntitle: Returns\n---\nSee [orders](/orders.md), not the table.\n");
2677
+ const back = await call(wiki, "wiki_graph", { query_type: "backlinks", page: "tables/orders" });
2678
+ expect(back.backlinks.map((b) => b.page)).not.toContain("metrics/returns.md");
2679
+ const broken = await call(wiki, "wiki_graph", { query_type: "broken_links" });
2680
+ expect(broken.broken_links).toEqual([
2681
+ { page: "metrics/returns.md", link: "/orders", snippet: "See [orders](/orders.md), not the table." },
2682
+ ]);
2683
+ const lint = await call(wiki, "wiki_admin", { action: "lint" });
2684
+ const issue = lint.issues.find((i) => i.category === "broken-link");
2685
+ expect(issue).toMatchObject({ page: "metrics/returns.md", message: "Broken link: /orders.md" });
2686
+ // a wikilink with the same name still resolves by basename, as it always has
2687
+ writeFileSync(join(wiki.config.wikiDir, "metrics", "returns.md"), "---\ntype: Metric\ntitle: Returns\n---\nSee [[orders]].\n");
2688
+ const again = await call(wiki, "wiki_graph", { query_type: "backlinks", page: "tables/orders" });
2689
+ expect(again.backlinks.map((b) => b.page)).toContain("metrics/returns.md");
2690
+ });
2691
+ it("backlinks through a Markdown link carry the line the link is on", async () => {
2692
+ const wiki = seed();
2693
+ const back = await call(wiki, "wiki_graph", { query_type: "backlinks", page: "metrics/gross-margin" });
2694
+ const fromOrders = back.backlinks.find((b) => b.page === "tables/orders.md");
2695
+ expect(fromOrders.snippet).toBe("The orders table. Margin is defined in [gross margin](../metrics/gross-margin.md).");
2696
+ });
2697
+ it("a nested log.md is an ordinary page outside lint: rebuild completes and the page stays writable", async () => {
2698
+ const wiki = seed();
2699
+ const r = await call(wiki, "wiki_admin", { action: "rebuild" });
2700
+ // the migration reports its counts only when it ran to the end without throwing
2701
+ expect(JSON.stringify(r)).toMatch(/Evidence migration: \d+ pages/);
2702
+ // a wiki that keeps a real page called log.md in a folder can still write it
2703
+ wiki.write("projects/log.md", "---\ntitle: Project Log\ntype: note\nsources: [\"https://example.com/p\"]\n---\nKept as a page.");
2704
+ expect(wiki.read("projects/log.md").title).toBe("Project Log");
2705
+ });
2706
+ it("lint accepts index.md and log.md without frontmatter and reports no broken links", async () => {
2707
+ const wiki = seed();
2708
+ const lint = await call(wiki, "wiki_admin", { action: "lint" });
2709
+ const reserved = lint.issues.filter((i) => /(^|\/)(index|log)\.md$/.test(i.page));
2710
+ expect(reserved).toEqual([]);
2711
+ expect(lint.issues.filter((i) => i.category === "broken-link")).toEqual([]);
2712
+ });
2713
+ it("search puts trust tier and lifecycle on the top results", async () => {
2714
+ const wiki = seed();
2715
+ const r = await call(wiki, "wiki_search", { query: "zebrafish" });
2716
+ expect(r.results[0].path).toBe("metrics/gross-margin.md");
2717
+ expect(r.results[0].okf).toEqual({
2718
+ trust_tier: "human-reviewed", status: "stable", stale_after: "2099-01-01T00:00:00Z", stale: false,
2719
+ });
2720
+ expect(r.evidence.rationale).not.toMatch(/Lifecycle/);
2721
+ });
2722
+ it("a deprecated hit lowers the envelope and names its replacement", async () => {
2723
+ const wiki = seed();
2724
+ const r = await call(wiki, "wiki_search", { query: "quokka" });
2725
+ expect(r.results[0].okf).toEqual({ trust_tier: "machine-confirmed", status: "deprecated", superseded_by: "metrics/gross-margin.md" });
2726
+ expect(r.evidence.confidence).not.toBe("strong");
2727
+ expect(r.evidence.rationale).toContain("wiki/metrics/gross-margin-legacy.md is deprecated, superseded by wiki/metrics/gross-margin.md");
2728
+ });
2729
+ it("a hit past its stale_after lowers the envelope", async () => {
2730
+ const wiki = seed();
2731
+ const r = await call(wiki, "wiki_search", { query: "wombat" });
2732
+ expect(r.results[0].okf).toEqual({ stale_after: "2026-01-01", stale: true });
2733
+ expect(r.evidence.confidence).not.toBe("strong");
2734
+ expect(r.evidence.rationale).toContain("is past its stale_after (2026-01-01)");
2735
+ });
2736
+ it("writing a concept back keeps unknown and nested keys", () => {
2737
+ const wiki = seed();
2738
+ wiki.write("metrics/gross-margin.md", FILES["metrics/gross-margin.md"].replace("revenue minus", "net revenue minus"));
2739
+ const fm = wiki.read("metrics/gross-margin.md").frontmatter;
2740
+ expect(fm["x-zebra-owner"]).toBe("human:ana");
2741
+ expect(fm.sources).toEqual([
2742
+ { resource: "/tables/orders.md" },
2743
+ { resource: "https://example.com/finance/policy", "x-zebra-reviewed": true },
2744
+ ]);
2745
+ // the text changed, so this write is a new generation; the earlier review stays as history
2746
+ expect(fm.generated).toMatchObject({ by: expect.stringMatching(/^agent-wiki\//) });
2747
+ expect(Date.parse(fm.generated.at)).toBeGreaterThan(Date.parse("2026-11-10T09:00:00Z"));
2748
+ expect(fm.verified).toEqual([{ by: "human:ana", at: "2026-11-10T09:00:00Z" }]);
2749
+ expect(fm.status).toBe("stable");
2750
+ expect(fm.unsupported).toBeUndefined(); // mapping sources count as grounded
2751
+ });
2752
+ it("a rebuild keeps the bundle metadata of the root index.md", async () => {
2753
+ const wiki = seed();
2754
+ await call(wiki, "wiki_admin", { action: "rebuild" });
2755
+ const fm = wiki.read("index.md").frontmatter;
2756
+ expect(fm).toMatchObject({
2757
+ okf_version: "0.3",
2758
+ title: "Zebra Retail",
2759
+ description: "Tables and metrics for Zebra Retail. Use it for margin questions.",
2760
+ license: "CC-BY-4.0",
2761
+ "x-zebra-owner": "team:finance",
2762
+ });
2763
+ });
2764
+ it("a native page is unaffected: no okf block, wikilinks still links", async () => {
2765
+ const wiki = freshWiki();
2766
+ wiki.write("alpha-note.md", "---\ntitle: Alpha Note\ntype: concept\nsources: [\"https://example.com/a\"]\n---\nPangolin facts, see [[beta-note]].");
2767
+ wiki.write("beta-note.md", "---\ntitle: Beta Note\ntype: concept\nsources: [\"https://example.com/b\"]\n---\nEnd.");
2768
+ expect(wiki.read("alpha-note.md").links).toEqual(["beta-note"]);
2769
+ const r = await call(wiki, "wiki_search", { query: "pangolin" });
2770
+ // a page written here records who generated it, so it states a trust tier: nobody reviewed it yet
2771
+ expect(r.results[0].okf).toEqual({ trust_tier: "unverified" });
2772
+ expect(r.evidence.rationale).not.toMatch(/Lifecycle|Trust/);
2773
+ });
2774
+ });
2775
+ describe("server tool: wiki_graph", () => {
2776
+ beforeEach(cleanUp);
2777
+ afterEach(cleanUp);
2778
+ function seed() {
2779
+ const wiki = freshWiki();
2780
+ wiki.write("alpha-note.md", "---\ntitle: Alpha Note\ntype: concept\n---\nStarts here, then [[beta-note]].");
2781
+ wiki.write("beta-note.md", "---\ntitle: Beta Note\ntype: concept\n---\nContinues to [[gamma-note]] and [[no-such-page]].");
2782
+ wiki.write("gamma-note.md", "---\ntitle: Gamma Note\ntype: concept\n---\nThe end.");
2783
+ return wiki;
2784
+ }
2785
+ it("backlinks returns the linking page, its snippet and a strong envelope", async () => {
2786
+ const wiki = seed();
2787
+ const r = JSON.parse(await handleTool(wiki, "wiki_graph", { query_type: "backlinks", page: "gamma-note" }));
2788
+ const fromBeta = r.backlinks.find((b) => b.page === "beta-note.md");
2789
+ expect(fromBeta).toMatchObject({ link: "gamma-note", snippet: expect.stringContaining("[[gamma-note]]") });
2790
+ expect(r.evidence).toMatchObject({ confidence: "strong", basis: "deterministic", abstain: false });
2791
+ });
2792
+ it("shortest_path skips the generated index and marks a 2-hop path weak", async () => {
2793
+ const wiki = seed();
2794
+ const r = JSON.parse(await handleTool(wiki, "wiki_graph", {
2795
+ query_type: "shortest_path", from: "alpha-note", to: "gamma-note.md",
2796
+ }));
2797
+ expect(r.path.map((p) => p.page)).toEqual(["alpha-note.md", "beta-note.md", "gamma-note.md"]);
2798
+ expect(r.evidence).toMatchObject({ confidence: "weak", basis: "inferred" });
2799
+ });
2800
+ it("broken_links reports a dangling target and abstains", async () => {
2801
+ const wiki = seed();
2802
+ const r = JSON.parse(await handleTool(wiki, "wiki_graph", { query_type: "broken_links" }));
2803
+ expect(r.broken_links).toContainEqual(expect.objectContaining({ page: "beta-note.md", link: "no-such-page" }));
2804
+ expect(r.evidence).toMatchObject({ confidence: "absent", basis: "unsupported", abstain: true });
2805
+ });
2806
+ it("neighbors and orphans answer from the live pages", async () => {
2807
+ const wiki = seed();
2808
+ const n = JSON.parse(await handleTool(wiki, "wiki_graph", { query_type: "neighbors", page: "beta-note" }));
2809
+ expect(n.neighbors.map((x) => x.page).sort()).toEqual(["alpha-note.md", "gamma-note.md"]);
2810
+ const o = JSON.parse(await handleTool(wiki, "wiki_graph", { query_type: "orphans" }));
2811
+ expect(o.query_type).toBe("orphans");
2812
+ expect(Array.isArray(o.orphans)).toBe(true);
2813
+ });
2814
+ it("rejects an unknown query_type", async () => {
2815
+ const wiki = freshWiki();
2816
+ await expect(handleTool(wiki, "wiki_graph", { query_type: "nope" })).rejects.toThrow(/Unknown wiki_graph query_type/);
2817
+ });
2040
2818
  });
2041
2819
  describe("consolidated tool: code_query", () => {
2042
2820
  beforeEach(cleanUp);
@@ -2625,5 +3403,75 @@ Extra content.` } },
2625
3403
  const rebuildResult = parsed.results.find((r) => r.tool === "wiki_admin");
2626
3404
  expect(rebuildResult?.result?.deferred).toMatch(/rebuild/);
2627
3405
  });
3406
+ it("batch preserves evidence_report:true on deduped wiki_admin rebuild", async () => {
3407
+ // Regression: dedup originally stripped the flag and the end-of-batch
3408
+ // path only ran rebuildIndex+rebuildTimeline, so wiki/evidence-report.md
3409
+ // never appeared even though the standalone call did write it.
3410
+ const wiki = freshWiki();
3411
+ const reportPath = join(wiki.config.wikiDir, "evidence-report.md");
3412
+ expect(existsSync(reportPath)).toBe(false);
3413
+ const result = await handleTool(wiki, "batch", {
3414
+ operations: [
3415
+ { tool: "wiki_admin", args: { action: "rebuild", evidence_report: true } },
3416
+ ],
3417
+ });
3418
+ expect(existsSync(reportPath)).toBe(true);
3419
+ expect(readFileSync(reportPath, "utf-8")).toContain("## Phase 2b readiness");
3420
+ // Invariant: 1 op → 1 result entry. The evidence-report regen lives
3421
+ // inside the deferred rebuild's entry, never as a sibling that would
3422
+ // inflate `count` and break op→result alignment for callers.
3423
+ const parsed = JSON.parse(result);
3424
+ expect(parsed.count).toBe(1);
3425
+ expect(parsed.results).toHaveLength(1);
3426
+ expect(parsed.results[0].tool).toBe("wiki_admin");
3427
+ expect(parsed.results[0].result?.deferred).toMatch(/rebuild/);
3428
+ });
3429
+ it("batch preserves okf_report:true on deduped wiki_admin rebuild", async () => {
3430
+ const wiki = freshWiki();
3431
+ writeValidOkfManifest();
3432
+ const reportPath = join(wiki.config.workspace, "evidence", "okf-report.json");
3433
+ expect(existsSync(reportPath)).toBe(false);
3434
+ const result = await handleTool(wiki, "batch", {
3435
+ operations: [
3436
+ { tool: "wiki_admin", args: { action: "rebuild", okf_report: true } },
3437
+ ],
3438
+ });
3439
+ expect(existsSync(reportPath)).toBe(true);
3440
+ const report = JSON.parse(readFileSync(reportPath, "utf-8"));
3441
+ expect(report.manifest.name).toBe("payroll-modernization-knowledge");
3442
+ expect(report.inventory).toHaveProperty("raw");
3443
+ expect(report.inventory.evidence.okfReport).toBe(true);
3444
+ const parsed = JSON.parse(result);
3445
+ expect(parsed.count).toBe(1);
3446
+ expect(parsed.results).toHaveLength(1);
3447
+ expect(parsed.results[0].tool).toBe("wiki_admin");
3448
+ expect(parsed.results[0].result?.deferred).toMatch(/rebuild/);
3449
+ });
3450
+ it("batch leaves report untouched when evidence_report flag is absent on rebuild", async () => {
3451
+ const wiki = freshWiki();
3452
+ const reportPath = join(wiki.config.wikiDir, "evidence-report.md");
3453
+ await handleTool(wiki, "batch", {
3454
+ operations: [
3455
+ { tool: "wiki_admin", args: { action: "rebuild" } },
3456
+ ],
3457
+ });
3458
+ expect(existsSync(reportPath)).toBe(false);
3459
+ });
3460
+ it("batch rebuild runs evidence migration so legacy pages classify equivalently to inline rebuild", async () => {
3461
+ // Without batch-side migration, the report's Source coverage would
3462
+ // bucket pre-migration legacy pages as `other` instead of
3463
+ // `legacyUnsupported` — divergence from the inline rebuild path.
3464
+ // Marker file presence under .agent-wiki/ is the canonical signal that
3465
+ // migration ran.
3466
+ const wiki = freshWiki();
3467
+ const marker = join(wiki.config.workspace, ".agent-wiki", "evidence-migrated");
3468
+ expect(existsSync(marker)).toBe(false);
3469
+ await handleTool(wiki, "batch", {
3470
+ operations: [
3471
+ { tool: "wiki_admin", args: { action: "rebuild", evidence_report: true } },
3472
+ ],
3473
+ });
3474
+ expect(existsSync(marker)).toBe(true);
3475
+ });
2628
3476
  });
2629
3477
  //# sourceMappingURL=server.test.js.map