@agent-wiki/mcp 0.22.4 → 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 (94) 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 +17 -0
  7. package/dist/evidence-report.d.ts.map +1 -1
  8. package/dist/evidence-report.js +46 -2
  9. package/dist/evidence-report.js.map +1 -1
  10. package/dist/evidence-search.d.ts +71 -0
  11. package/dist/evidence-search.d.ts.map +1 -1
  12. package/dist/evidence-search.js +104 -1
  13. package/dist/evidence-search.js.map +1 -1
  14. package/dist/evidence-search.test.js +58 -1
  15. package/dist/evidence-search.test.js.map +1 -1
  16. package/dist/index.d.ts +10 -0
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +5 -0
  19. package/dist/index.js.map +1 -1
  20. package/dist/okf-compat.d.ts +152 -0
  21. package/dist/okf-compat.d.ts.map +1 -0
  22. package/dist/okf-compat.js +604 -0
  23. package/dist/okf-compat.js.map +1 -0
  24. package/dist/okf-compat.test.d.ts +2 -0
  25. package/dist/okf-compat.test.d.ts.map +1 -0
  26. package/dist/okf-compat.test.js +234 -0
  27. package/dist/okf-compat.test.js.map +1 -0
  28. package/dist/okf-export.d.ts +63 -0
  29. package/dist/okf-export.d.ts.map +1 -0
  30. package/dist/okf-export.js +655 -0
  31. package/dist/okf-export.js.map +1 -0
  32. package/dist/okf-export.test.d.ts +2 -0
  33. package/dist/okf-export.test.d.ts.map +1 -0
  34. package/dist/okf-export.test.js +469 -0
  35. package/dist/okf-export.test.js.map +1 -0
  36. package/dist/okf-import.d.ts +136 -0
  37. package/dist/okf-import.d.ts.map +1 -0
  38. package/dist/okf-import.js +471 -0
  39. package/dist/okf-import.js.map +1 -0
  40. package/dist/okf-import.test.d.ts +2 -0
  41. package/dist/okf-import.test.d.ts.map +1 -0
  42. package/dist/okf-import.test.js +339 -0
  43. package/dist/okf-import.test.js.map +1 -0
  44. package/dist/okf-trust.test.d.ts +2 -0
  45. package/dist/okf-trust.test.d.ts.map +1 -0
  46. package/dist/okf-trust.test.js +223 -0
  47. package/dist/okf-trust.test.js.map +1 -0
  48. package/dist/okf.d.ts +128 -0
  49. package/dist/okf.d.ts.map +1 -0
  50. package/dist/okf.js +659 -0
  51. package/dist/okf.js.map +1 -0
  52. package/dist/search-currency.d.ts +44 -0
  53. package/dist/search-currency.d.ts.map +1 -0
  54. package/dist/search-currency.js +111 -0
  55. package/dist/search-currency.js.map +1 -0
  56. package/dist/search.d.ts +19 -0
  57. package/dist/search.d.ts.map +1 -1
  58. package/dist/search.js.map +1 -1
  59. package/dist/server.d.ts +0 -1
  60. package/dist/server.d.ts.map +1 -1
  61. package/dist/server.js +617 -21
  62. package/dist/server.js.map +1 -1
  63. package/dist/server.test.js +772 -0
  64. package/dist/server.test.js.map +1 -1
  65. package/dist/wiki-graph.d.ts +126 -0
  66. package/dist/wiki-graph.d.ts.map +1 -0
  67. package/dist/wiki-graph.js +479 -0
  68. package/dist/wiki-graph.js.map +1 -0
  69. package/dist/wiki-graph.test.d.ts +2 -0
  70. package/dist/wiki-graph.test.d.ts.map +1 -0
  71. package/dist/wiki-graph.test.js +216 -0
  72. package/dist/wiki-graph.test.js.map +1 -0
  73. package/dist/wiki.d.ts +140 -1
  74. package/dist/wiki.d.ts.map +1 -1
  75. package/dist/wiki.js +509 -23
  76. package/dist/wiki.js.map +1 -1
  77. package/dist/worklist.d.ts +43 -0
  78. package/dist/worklist.d.ts.map +1 -0
  79. package/dist/worklist.js +147 -0
  80. package/dist/worklist.js.map +1 -0
  81. package/dist/worklist.test.d.ts +2 -0
  82. package/dist/worklist.test.d.ts.map +1 -0
  83. package/dist/worklist.test.js +233 -0
  84. package/dist/worklist.test.js.map +1 -0
  85. package/docs/evidence-envelope.md +5 -0
  86. package/docs/okf-adoption-plan.md +566 -0
  87. package/docs/okf-compat-plan.md +418 -0
  88. package/docs/okf-extensions.md +245 -0
  89. package/docs/open-knowledge-format.md +280 -0
  90. package/docs/tools.md +264 -2
  91. package/package.json +1 -1
  92. package/schemas/agent-wiki-okf.schema.json +130 -0
  93. package/skills/agent-wiki/SKILL.md +7 -0
  94. package/skills/agent-wiki/references/tools-reference.md +80 -3
package/dist/server.js CHANGED
@@ -12,14 +12,22 @@ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
12
12
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
13
13
  import { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
14
14
  import { existsSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
15
- import { buildSearchEnvelope, downgradeForReadPage } from "./evidence-search.js";
15
+ import { applyTrust, buildSearchEnvelope, downgradeForContradictions, downgradeForLifecycle, downgradeForReadPage, downgradeForSourceDrift, PROVENANCE_LIMIT } from "./evidence-search.js";
16
+ import { lifecycleConcerns, okfLifecycle, okfTrust, parseOkfTimestamp } from "./okf-compat.js";
17
+ import { rankByCurrency } from "./search-currency.js";
18
+ import { buildWorklist } from "./worklist.js";
19
+ import { importOkfBundle } from "./okf-import.js";
20
+ import { exportOkfBundle } from "./okf-export.js";
16
21
  import { rotateEventLog, summarizeLastWeek } from "./evidence-write-log.js";
17
22
  import { appendSearchEvent, rotateSearchLog } from "./evidence-search-log.js";
18
23
  import { runEvidenceReport } from "./evidence-report.js";
19
24
  import { migrateExistingPagesForEvidence } from "./evidence-migration.js";
20
25
  import { absentDeterministic, strongDeterministic } from "./evidence.js";
26
+ import { buildOkfPackageReport, runOkfPackageReport } from "./okf.js";
21
27
  import { join, resolve, basename, extname } from "node:path";
22
- import { Wiki, splitSections, buildToc, findSectionByHeading, matchSimpleGlob, safePath } from "./wiki.js";
28
+ import { createHash } from "node:crypto";
29
+ import { Wiki, describeSourceDrift, isSystemPage, splitSections, buildToc, findSectionByHeading, matchSimpleGlob, safePath } from "./wiki.js";
30
+ import { computeWikiGraph, runWikiGraphQuery, WIKI_GRAPH_QUERY_TYPES } from "./wiki-graph.js";
23
31
  import { extractDocument, chunkSegments, guessMime } from "./extraction.js";
24
32
  import matter from "gray-matter";
25
33
  import { VERSION } from "./version.js";
@@ -255,6 +263,10 @@ export function createServer(wikiPath, workspace) {
255
263
  type: "string",
256
264
  description: "Provenance — why this write is happening",
257
265
  },
266
+ actor: {
267
+ type: "string",
268
+ description: "Who is writing, as an OKF actor: <producer>/<version> for an agent (e.g. my-agent/gpt-5), human:<id> for a person. Recorded in the page's generated.by when the content changes. Default: agent-wiki/<version>.",
269
+ },
258
270
  return_content: {
259
271
  type: "boolean",
260
272
  description: "If true, include the final written content in the response. Eliminates a follow-up wiki_read call. Default: false.",
@@ -294,6 +306,61 @@ export function createServer(wikiPath, workspace) {
294
306
  },
295
307
  },
296
308
  },
309
+ {
310
+ name: "wiki_graph",
311
+ description: "Query the [[wikilink]] graph between wiki pages. Select `query_type`:\n" +
312
+ "- `backlinks`: pages that link to `page`, each with the line the link sits on.\n" +
313
+ "- `neighbors`: pages within `depth` hops of `page`, following links in both directions.\n" +
314
+ "- `orphans`: pages that no other page links to.\n" +
315
+ "- `broken_links`: [[links]] whose target is no page, and bare links whose name several pages share.\n" +
316
+ "- `shortest_path`: the shortest chain of links between `from` and `to`, depth-capped.\n" +
317
+ "Read-only; the graph is rebuilt from the pages on every call. Each response carries an evidence " +
318
+ "envelope: a direct link is strong, a path or neighbourhood over 2+ hops is weak (a chain of links " +
319
+ "does not show the ends are related), and an empty result or a search that hit the depth cap abstains.",
320
+ inputSchema: {
321
+ type: "object",
322
+ properties: {
323
+ query_type: {
324
+ type: "string",
325
+ enum: [...WIKI_GRAPH_QUERY_TYPES],
326
+ description: "Query type: backlinks, neighbors, orphans, broken_links, or shortest_path",
327
+ },
328
+ page: {
329
+ type: "string",
330
+ description: "[backlinks, neighbors] Page path or slug, e.g. 'concept-gil', 'concept-gil.md' or 'topic/foo'",
331
+ },
332
+ depth: {
333
+ type: "number",
334
+ description: "[neighbors] How many hops to follow (default 1, max 3)",
335
+ },
336
+ from: {
337
+ type: "string",
338
+ description: "[shortest_path] Page path or slug to start from",
339
+ },
340
+ to: {
341
+ type: "string",
342
+ description: "[shortest_path] Page path or slug to reach",
343
+ },
344
+ max_depth: {
345
+ type: "number",
346
+ description: "[shortest_path] Longest path to look for, in hops (default 6, max 10). When the cap stops the search the response abstains.",
347
+ },
348
+ directed: {
349
+ type: "boolean",
350
+ description: "[shortest_path] true: follow links only from a page to the pages it links to. Default false: follow links both ways.",
351
+ },
352
+ include_system: {
353
+ type: "boolean",
354
+ description: "[neighbors, shortest_path] Also walk through system pages (index.md, log.md, timeline.md, */index.md). Default false: they link to almost every page and would connect everything.",
355
+ },
356
+ limit: {
357
+ type: "number",
358
+ description: "[backlinks, neighbors, orphans, broken_links] Maximum rows returned (default 100, max 500); `truncated` says when more exist",
359
+ },
360
+ },
361
+ required: ["query_type"],
362
+ },
363
+ },
297
364
  {
298
365
  name: "wiki_search",
299
366
  description: "Full-text keyword search across all wiki pages. Returns paths, scores, and snippets sorted by relevance. " +
@@ -332,6 +399,11 @@ export function createServer(wikiPath, workspace) {
332
399
  type: "number",
333
400
  description: "Max total characters of inlined content across all results (only with include_content=true). Greedy — top-scoring results get content first; lower-scoring ones fall back to snippet-only when budget is exhausted. Omit for no limit.",
334
401
  },
402
+ min_trust: {
403
+ type: "string",
404
+ enum: ["machine-confirmed", "human-reviewed"],
405
+ description: "The OKF trust tier the answer needs (default: unset, trust does not affect confidence). When the top cited page is below it, evidence.confidence drops from strong to weak and the rationale says which tier the page has. Reviews are recorded with wiki_admin action:verify.",
406
+ },
335
407
  read_top_n: {
336
408
  type: "number",
337
409
  description: "How many unique top-scoring pages to read in full (default: unset). When set, activates combined search+read mode: deduplicates search hits, reads up to N unique pages, and returns a `pages` array alongside `results`. Max: 10.",
@@ -358,20 +430,23 @@ export function createServer(wikiPath, workspace) {
358
430
  description: "Wiki administration and maintenance. Select `action` to control behavior:\n" +
359
431
  "- `init`: Initialize a new knowledge base — creates wiki/, raw/, schemas/ directories and default templates.\n" +
360
432
  "- `config`: Show current workspace configuration: directories, lint settings, search settings, entity templates.\n" +
361
- "- `rebuild`: Rebuild index.md, timeline.md, code knowledge graphs, and optionally the vector index (when search.hybrid is enabled). Set evidence_report=true to also regenerate the evidence report and persist it to wiki/evidence-report.md as part of the rebuild.\n" +
433
+ "- `format-check`: Validate the agent-wiki package manifest (`agent-wiki.yaml`), package inventory, and conformance findings against package profile v0.1. This is agent-wiki's own format, not upstream Open Knowledge Format conformance.\n" +
434
+ "- `rebuild`: Rebuild index.md, timeline.md, code knowledge graphs, and optionally the vector index (when search.hybrid is enabled). Set evidence_report=true to also regenerate the evidence report and persist it to wiki/evidence-report.md as part of the rebuild. Set okf_report=true to persist evidence/okf-report.json.\n" +
362
435
  "- `lint`: Run comprehensive health checks: contradictions, orphan pages, broken links, raw file integrity (SHA-256), synthesis page integrity. Set apply_fixes=true to auto-repair fixable issues.\n" +
363
- "- `evidence-report`: Aggregate evidence-first telemetry into a corpus-level Markdown report (source coverage, lineage diagnostics, 4-week write trend, Phase 2b readiness gates). Set write=true to also persist the report to wiki/evidence-report.md.",
436
+ "- `evidence-report`: Aggregate evidence-first telemetry into a corpus-level Markdown report (source coverage, lineage diagnostics, 4-week write trend, Phase 2b readiness gates). Set write=true to also persist the report to wiki/evidence-report.md.\n" +
437
+ "- `reconcile`: Settle a contradiction between two pages. With `page_a` and `page_b` only, returns both claims with each page's sources so you can judge. Add `winner` (one of the two pages) to write a reconciliation page that records the decision and marks the other claim superseded; search then stops flagging that claim. Nothing is decided for you, neither page is edited, and the result is always `inferred`.\n" +
438
+ "- `import`: Import an Open Knowledge Format (OKF) v0.3 bundle from `path` (a directory or a .zip) into wiki/. The bundle is checked first and refused, with the rule it breaks, when it is not conformant; nothing is converted. Refuses to replace existing files unless `overwrite` is true. Set `dry_run` to check and list what would be copied without writing.",
364
439
  inputSchema: {
365
440
  type: "object",
366
441
  properties: {
367
442
  action: {
368
443
  type: "string",
369
- enum: ["init", "config", "rebuild", "lint", "evidence-report"],
444
+ enum: ["init", "config", "format-check", "rebuild", "lint", "evidence-report", "reconcile", "import", "export", "verify", "worklist"],
370
445
  description: "Administration action to perform",
371
446
  },
372
447
  path: {
373
448
  type: "string",
374
- description: "[init] Config root — where .agent-wiki.yaml is created (default: current directory)",
449
+ description: "[init] Config root — where .agent-wiki.yaml is created (default: current directory). [import] Directory or .zip archive that holds the OKF bundle, on the machine the server runs on.",
375
450
  },
376
451
  workspace: {
377
452
  type: "string",
@@ -389,6 +464,60 @@ export function createServer(wikiPath, workspace) {
389
464
  type: "boolean",
390
465
  description: "[rebuild] If true, also regenerate the evidence report and persist it to wiki/evidence-report.md as part of the rebuild. Useful for keeping the dashboard fresh without a separate evidence-report call. Default: false.",
391
466
  },
467
+ okf_report: {
468
+ type: "boolean",
469
+ description: "[rebuild] If true, regenerate the agent-wiki package inventory/conformance report and persist it to evidence/okf-report.json. Default: false.",
470
+ },
471
+ format: {
472
+ type: "string",
473
+ enum: ["okf"],
474
+ description: "[import, export] Bundle format. Only okf (Open Knowledge Format v0.3) is supported. Default: okf.",
475
+ },
476
+ out: {
477
+ type: "string",
478
+ description: "[export] Directory on the server's machine to write the bundle to. Must be empty or not exist, unless overwrite is set.",
479
+ },
480
+ overwrite: {
481
+ type: "boolean",
482
+ description: "[import] Replace files that already exist in wiki/. [export] Replace an earlier export in the output directory. Default: false, the operation is refused instead.",
483
+ },
484
+ dry_run: {
485
+ type: "boolean",
486
+ description: "[import] Check the bundle and report what would be imported without writing anything. Default: false.",
487
+ },
488
+ kind: {
489
+ type: "string",
490
+ enum: ["rewrite", "reconcile", "review", "ingest"],
491
+ description: "[worklist] Only items of this kind. Default: all, most urgent first.",
492
+ },
493
+ limit: {
494
+ type: "number",
495
+ description: "[worklist] Max items to return. Default: 50.",
496
+ },
497
+ page: {
498
+ type: "string",
499
+ description: "[verify] The page that was reviewed, relative to wiki/",
500
+ },
501
+ by: {
502
+ type: "string",
503
+ description: "[verify] Who confirmed the page against its sources, as an OKF actor: human:<id> for a person, process:<id> for an automated check, <producer>/<version> for an agent. Only human: gives the human-reviewed tier.",
504
+ },
505
+ page_a: {
506
+ type: "string",
507
+ description: "[reconcile] First page of the contradicting pair, relative to wiki/",
508
+ },
509
+ page_b: {
510
+ type: "string",
511
+ description: "[reconcile] Second page of the contradicting pair, relative to wiki/",
512
+ },
513
+ winner: {
514
+ type: "string",
515
+ description: "[reconcile] Which of the two pages holds the claim you judge correct. Omit to only see both claims and their sources.",
516
+ },
517
+ note: {
518
+ type: "string",
519
+ description: "[reconcile] Why that page wins; recorded in the reconciliation page. Recommended whenever winner is set.",
520
+ },
392
521
  },
393
522
  required: ["action"],
394
523
  },
@@ -1380,6 +1509,29 @@ function applyDerivedArtifacts(wiki, pluginId, derived) {
1380
1509
  }
1381
1510
  return writtenArtifacts;
1382
1511
  }
1512
+ /**
1513
+ * The wiki paths rebuildDeferredGraphs would write or delete right now, without doing it.
1514
+ * An import uses this to keep bundle files off paths a plugin owns.
1515
+ */
1516
+ function pluginGeneratedWikiPaths(wiki) {
1517
+ const paths = new Set();
1518
+ for (const plugin of listPlugins()) {
1519
+ const parsedDir = join(wiki.config.rawDir, "parsed", plugin.id);
1520
+ try {
1521
+ for (const page of plugin.rebuildAggregatePages?.(parsedDir) ?? [])
1522
+ paths.add(page.path);
1523
+ for (const page of plugin.buildKnowledgeGraph?.(parsedDir)?.wikiPages ?? [])
1524
+ paths.add(page.path);
1525
+ const derived = plugin.buildDerivedArtifacts?.(parsedDir, { config: wiki.config });
1526
+ for (const page of derived?.wikiPages ?? [])
1527
+ paths.add(page.path);
1528
+ for (const stale of derived?.staleWikiPages ?? [])
1529
+ paths.add(stale);
1530
+ }
1531
+ catch { /* a plugin that cannot build now will not write on the rebuild either */ }
1532
+ }
1533
+ return paths;
1534
+ }
1383
1535
  function rebuildDeferredGraphs(wiki) {
1384
1536
  for (const plugin of listPlugins()) {
1385
1537
  const parsedDir = join(wiki.config.rawDir, "parsed", plugin.id);
@@ -1548,6 +1700,300 @@ function buildImpactResponse(graph, sourceNode, maxDepth) {
1548
1700
  diagnostics: relevantDiagnostics,
1549
1701
  };
1550
1702
  }
1703
+ /** Internal options — not exposed to MCP callers. */
1704
+ /**
1705
+ * Flag a search envelope when a page it cites is in an open contradiction, was written
1706
+ * against a raw source that has since moved on, or says of itself that it is not current.
1707
+ * The first two read an index that lint and rebuild persisted: one stat each, no
1708
+ * detection. The third reads the frontmatter of the cited pages (at most three) and also
1709
+ * puts their OKF trust tier and lifecycle on the result, where the page states any.
1710
+ */
1711
+ /** Pages whose sealed source is an earlier version of the raw file just added. */
1712
+ function pagesCitingEarlierVersion(wiki, rawPath) {
1713
+ if (!/_v\d+(\.[^./]+)?$/.test(rawPath))
1714
+ return []; // not a versioned name: nothing it could supersede
1715
+ try {
1716
+ const drift = wiki.refreshSourceDriftIndex().pages;
1717
+ return Object.entries(drift)
1718
+ .filter(([, entries]) => entries.some((e) => e.newerVersion?.replace(/^raw\//, "") === rawPath))
1719
+ .map(([page]) => page)
1720
+ .sort();
1721
+ }
1722
+ catch {
1723
+ return [];
1724
+ }
1725
+ }
1726
+ /**
1727
+ * Extra candidates fetched beyond the requested limit before ranking by currency. Without
1728
+ * them a retired page that is the best match would fill the last place and its current
1729
+ * successor, one rank below the cut, could never be brought up.
1730
+ */
1731
+ const CURRENCY_HEADROOM = 10;
1732
+ /**
1733
+ * Order search results by what is known about each page's currency (search-currency.ts):
1734
+ * the frontmatter of the pages found, and the source-drift index that lint and rebuild keep.
1735
+ */
1736
+ function rankSearchResults(wiki, results) {
1737
+ if (results.length === 0)
1738
+ return results;
1739
+ const drift = wiki.sourceDriftIndex()?.pages ?? {};
1740
+ return rankByCurrency(results, (path) => {
1741
+ const page = wiki.read(path);
1742
+ if (!page)
1743
+ return undefined;
1744
+ const lc = okfLifecycle(page.frontmatter, path);
1745
+ const generatedAt = parseOkfTimestamp(page.frontmatter.generated?.at);
1746
+ const updatedAt = page.updated ? Date.parse(page.updated) : NaN;
1747
+ return {
1748
+ deprecated: lc.status === "deprecated",
1749
+ stale: lc.staleness === "stale" || lc.staleness === "malformed",
1750
+ drifted: (drift[path]?.length ?? 0) > 0,
1751
+ changedAt: generatedAt ?? (Number.isFinite(updatedAt) ? updatedAt : undefined),
1752
+ };
1753
+ });
1754
+ }
1755
+ function readMinTrust(value) {
1756
+ if (value === undefined || value === null || value === "" || value === "unverified")
1757
+ return undefined;
1758
+ if (value === "machine-confirmed" || value === "human-reviewed")
1759
+ return value;
1760
+ throw new Error(`min_trust: unknown tier "${String(value)}". Expected: machine-confirmed | human-reviewed`);
1761
+ }
1762
+ function withIndexDowngrades(wiki, results, envelope, minTrust) {
1763
+ if (envelope.abstain || results.length === 0)
1764
+ return envelope;
1765
+ const cited = results.slice(0, PROVENANCE_LIMIT);
1766
+ let out = envelope;
1767
+ const lifecycle = [];
1768
+ const trusted = [];
1769
+ for (const r of cited) {
1770
+ const page = wiki.read(r.path);
1771
+ if (!page)
1772
+ continue;
1773
+ const lc = okfLifecycle(page.frontmatter, r.path);
1774
+ const trust = okfTrust(page.frontmatter);
1775
+ const tier = trust?.tier;
1776
+ trusted.push({ page: r.path, tier, lapsed: trust?.lapsed, beforeChange: trust?.before_change });
1777
+ if (tier || lc.status !== undefined || lc.staleness !== "unset") {
1778
+ r.okf = {
1779
+ ...(tier ? { trust_tier: tier } : {}),
1780
+ ...(trust?.lapsed ? { review_lapsed: true } : {}),
1781
+ ...(lc.status !== undefined ? { status: lc.status } : {}),
1782
+ ...(lc.supersededBy ? { superseded_by: lc.supersededBy } : {}),
1783
+ ...(lc.staleAfter !== undefined ? { stale_after: lc.staleAfter, stale: lc.staleness !== "fresh" } : {}),
1784
+ };
1785
+ }
1786
+ lifecycle.push({ page: r.path, concerns: lifecycleConcerns(lc) });
1787
+ }
1788
+ out = downgradeForLifecycle(out, lifecycle);
1789
+ out = applyTrust(out, trusted, minTrust);
1790
+ const contradictions = wiki.contradictionIndex();
1791
+ if (contradictions) {
1792
+ out = downgradeForContradictions(out, cited.map((r) => ({ page: r.path, disputes: contradictions.pages[r.path] ?? [] })));
1793
+ }
1794
+ const drift = wiki.sourceDriftIndex();
1795
+ if (drift) {
1796
+ out = downgradeForSourceDrift(out, cited.map((r) => ({
1797
+ page: r.path,
1798
+ sources: (drift.pages[r.path] ?? []).map((d) => ({ source: d.source, detail: describeSourceDrift(d) })),
1799
+ })));
1800
+ }
1801
+ return out;
1802
+ }
1803
+ function reconcileSide(page, excerpt) {
1804
+ return {
1805
+ page: page.path,
1806
+ title: page.title,
1807
+ excerpt,
1808
+ sources: page.sources,
1809
+ ...(page.updated ? { updated: page.updated } : {}),
1810
+ };
1811
+ }
1812
+ /**
1813
+ * `wiki_admin action:reconcile`. Without `winner`: show both claims and where each page
1814
+ * says its claim comes from. With `winner`: write a reconciliation page that records the
1815
+ * agent's decision. The tool never picks a side, never edits the two pages, and reports
1816
+ * the outcome as inferred so the decision stays auditable.
1817
+ */
1818
+ function reconcilePages(wiki, args) {
1819
+ const need = (name) => {
1820
+ const v = args[name];
1821
+ if (typeof v !== "string" || v.trim() === "")
1822
+ throw new Error(`wiki_admin reconcile: "${name}" is required`);
1823
+ return v.trim();
1824
+ };
1825
+ const load = (name) => {
1826
+ const page = wiki.read(need(name));
1827
+ if (!page)
1828
+ throw new Error(`wiki_admin reconcile: no such page "${args[name]}"`);
1829
+ return { ...page, path: page.path.replace(/\\/g, "/") };
1830
+ };
1831
+ const a = load("page_a");
1832
+ const b = load("page_b");
1833
+ if (a.path === b.path)
1834
+ throw new Error("wiki_admin reconcile: page_a and page_b are the same page");
1835
+ const between = (list) => list.filter((c) => (c.pageA === a.path && c.pageB === b.path) || (c.pageA === b.path && c.pageB === a.path));
1836
+ const state = wiki.contradictionState();
1837
+ const open = between(state.active);
1838
+ const settled = between(state.reconciled);
1839
+ const sideOf = (c, page) => reconcileSide(page, c.pageA === page.path ? c.excerptA : c.excerptB);
1840
+ const provenance = [a, b].flatMap((p) => [
1841
+ { wikiPage: `wiki/${p.path}` },
1842
+ ...p.sources.filter((src) => src.startsWith("raw/")).map((src) => ({ raw: src })),
1843
+ ]);
1844
+ const alreadyReconciled = settled.map((c) => ({ claim: c.claim, resolution: c.resolution }));
1845
+ if (open.length === 0) {
1846
+ return {
1847
+ written: false,
1848
+ response: {
1849
+ page_a: a.path,
1850
+ page_b: b.path,
1851
+ contradictions: [],
1852
+ already_reconciled: alreadyReconciled,
1853
+ evidence: absentDeterministic(settled.length > 0
1854
+ ? `No open contradiction between ${a.path} and ${b.path}; ${settled.length} already reconciled.`
1855
+ : `Detection finds no contradiction between ${a.path} and ${b.path}.`, [{ wikiPage: `wiki/${a.path}` }, { wikiPage: `wiki/${b.path}` }]),
1856
+ },
1857
+ };
1858
+ }
1859
+ const contradictions = open.map((c) => ({
1860
+ claim: c.claim,
1861
+ severity: c.severity,
1862
+ a: sideOf(c, a),
1863
+ b: sideOf(c, b),
1864
+ }));
1865
+ const winnerArg = args.winner;
1866
+ if (typeof winnerArg !== "string" || winnerArg.trim() === "") {
1867
+ return {
1868
+ written: false,
1869
+ response: {
1870
+ page_a: a.path,
1871
+ page_b: b.path,
1872
+ contradictions,
1873
+ already_reconciled: alreadyReconciled,
1874
+ next: "Compare the sources of both pages, then call reconcile again with `winner` set to the page whose claim holds, and a `note` saying why.",
1875
+ evidence: {
1876
+ confidence: "weak",
1877
+ basis: "inferred",
1878
+ abstain: false,
1879
+ rationale: `${open.length} open contradiction(s) between ${a.path} and ${b.path}, found by pattern matching on ` +
1880
+ `numbers and dates. Which page is right is not decided here.`,
1881
+ provenance,
1882
+ },
1883
+ },
1884
+ };
1885
+ }
1886
+ const winnerPage = wiki.read(winnerArg.trim());
1887
+ const winnerPath = winnerPage?.path.replace(/\\/g, "/");
1888
+ if (winnerPath !== a.path && winnerPath !== b.path) {
1889
+ throw new Error(`wiki_admin reconcile: winner must be page_a or page_b, got "${winnerArg}"`);
1890
+ }
1891
+ const winner = winnerPath === a.path ? a : b;
1892
+ const loser = winner === a ? b : a;
1893
+ const note = typeof args.note === "string" ? args.note.trim() : "";
1894
+ const slugOf = (p) => (typeof p === "string" ? p : p.path).replace(/\.md$/, "");
1895
+ const [first, second] = [a, b].sort((x, y) => x.path.localeCompare(y.path));
1896
+ const pair = [first.path, second.path];
1897
+ // The readable part of the name can be the same for different pairs (a/b.md and a-b.md
1898
+ // both flatten to "a-b"), so the name also carries a hash of the exact pair.
1899
+ const pairHash = createHash("sha256").update(pair.join("\u0000")).digest("hex").slice(0, 8);
1900
+ const flat = (p) => slugOf(p).replace(/\//g, "-");
1901
+ const resolutionPath = `reconciliation-${flat(first)}-vs-${flat(second)}-${pairHash}.md`;
1902
+ const earlier = wiki.read(resolutionPath);
1903
+ let earlierDecisions = [];
1904
+ if (earlier) {
1905
+ const earlierPair = Array.isArray(earlier.frontmatter.reconciles)
1906
+ ? earlier.frontmatter.reconciles.map(String)
1907
+ : [];
1908
+ if (earlierPair.length !== 2 || earlierPair[0] !== pair[0] || earlierPair[1] !== pair[1]) {
1909
+ throw new Error(`wiki_admin reconcile: ${resolutionPath} exists and does not belong to ${pair[0]} / ${pair[1]}; not overwriting it`);
1910
+ }
1911
+ if (Array.isArray(earlier.frontmatter.decisions)) {
1912
+ earlierDecisions = earlier.frontmatter.decisions
1913
+ .filter((d) => d && typeof d.claim === "string")
1914
+ .map((d) => ({
1915
+ claim: String(d.claim),
1916
+ winner: String(d.winner ?? ""),
1917
+ superseded: String(d.superseded ?? ""),
1918
+ kept_excerpt: String(d.kept_excerpt ?? ""),
1919
+ superseded_excerpt: String(d.superseded_excerpt ?? ""),
1920
+ note: String(d.note ?? ""),
1921
+ decided_at: String(d.decided_at ?? ""),
1922
+ }));
1923
+ }
1924
+ }
1925
+ const excerptOf = (c, page) => (c.pageA === page.path ? c.excerptA : c.excerptB);
1926
+ const decidedAt = new Date().toISOString();
1927
+ const newDecisions = open.map((c) => ({
1928
+ claim: c.claim,
1929
+ winner: winner.path,
1930
+ superseded: loser.path,
1931
+ kept_excerpt: excerptOf(c, winner),
1932
+ superseded_excerpt: excerptOf(c, loser),
1933
+ note,
1934
+ decided_at: decidedAt,
1935
+ }));
1936
+ const newClaims = new Set(newDecisions.map((d) => d.claim));
1937
+ const decisions = [...earlierDecisions.filter((d) => !newClaims.has(d.claim)), ...newDecisions];
1938
+ const sourcesLine = (p) => (p.sources.length > 0 ? p.sources.join(", ") : "none listed");
1939
+ const frontmatter = {
1940
+ title: `Reconciliation: ${first.title} vs ${second.title}`,
1941
+ type: "synthesis",
1942
+ synthesis: true,
1943
+ reconciles: pair,
1944
+ reconciled_claims: decisions.map((d) => d.claim),
1945
+ decisions,
1946
+ derived_from: pair,
1947
+ sources: [...new Set([...a.sources, ...b.sources])],
1948
+ tags: ["reconciliation"],
1949
+ };
1950
+ const body = [
1951
+ `# Reconciliation: ${first.title} vs ${second.title}`,
1952
+ "",
1953
+ `[[${slugOf(first)}]] and [[${slugOf(second)}]] disagree. This page records, claim by claim, which side was kept. ` +
1954
+ `Each decision is a judgement by the agent that made it, not a fact from a source: both claims and their sources are kept below so it can be checked.`,
1955
+ "",
1956
+ "## Decisions",
1957
+ "",
1958
+ ...decisions.flatMap((d) => [
1959
+ `### ${d.claim}`,
1960
+ "",
1961
+ `- Kept — [[${slugOf(d.winner)}]]: "${d.kept_excerpt}"`,
1962
+ `- Superseded — [[${slugOf(d.superseded)}]]: "${d.superseded_excerpt}"`,
1963
+ `- Reason: ${d.note || "none given"}`,
1964
+ ...(d.decided_at ? [`- Decided: ${d.decided_at.slice(0, 10)}`] : []),
1965
+ "",
1966
+ ]),
1967
+ "## Sources",
1968
+ "",
1969
+ `- [[${slugOf(first)}]]: ${sourcesLine(first)}`,
1970
+ `- [[${slugOf(second)}]]: ${sourcesLine(second)}`,
1971
+ "",
1972
+ ].join("\n");
1973
+ wiki.write(resolutionPath, matter.stringify(body, frontmatter), "reconcile");
1974
+ const index = wiki.refreshContradictionIndex();
1975
+ return {
1976
+ written: true,
1977
+ response: {
1978
+ ok: true,
1979
+ resolution_page: resolutionPath,
1980
+ winner: winner.path,
1981
+ superseded: loser.path,
1982
+ reconciled_claims: open.map((c) => c.claim),
1983
+ contradictions,
1984
+ still_disputed: Object.keys(index.pages).length,
1985
+ evidence: {
1986
+ confidence: "weak",
1987
+ basis: "inferred",
1988
+ abstain: false,
1989
+ rationale: `${winner.path} was kept over ${loser.path} by the caller's judgement` +
1990
+ (note ? ` ("${note}")` : " (no reason given)") +
1991
+ `. Neither page was edited; both claims and their sources are in ${resolutionPath}.`,
1992
+ provenance: [{ wikiPage: `wiki/${resolutionPath}` }, ...provenance],
1993
+ },
1994
+ },
1995
+ };
1996
+ }
1551
1997
  /**
1552
1998
  * Build a knowledge_gap suggestion when a search returns no results.
1553
1999
  * Derives suggested_page, suggested_title, type, and tags from the query
@@ -1681,11 +2127,24 @@ function regenerateEvidenceReport(wiki) {
1681
2127
  return { ok: false, error: err instanceof Error ? err.message : String(err) };
1682
2128
  }
1683
2129
  }
2130
+ function regenerateOkfReport(wiki) {
2131
+ try {
2132
+ const result = runOkfPackageReport(wiki, { write: true });
2133
+ if (!result.writtenTo) {
2134
+ return { ok: false, error: "runOkfPackageReport(write:true) returned no writtenTo path" };
2135
+ }
2136
+ return { ok: true, writtenTo: result.writtenTo };
2137
+ }
2138
+ catch (err) {
2139
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
2140
+ }
2141
+ }
1684
2142
  /**
1685
- * Single source of truth for the post-rebuild evidence bookkeeping that
2143
+ * Single source of truth for the post-rebuild evidence / OKF bookkeeping that
1686
2144
  * both `wiki_admin action:rebuild` (inline) and the end-of-batch rebuild
1687
2145
  * path execute: (1) one-shot migration of pre-existing pages, (2) weekly
1688
- * digest line into wiki/log.md, (3) optional opt-in evidence-report regen.
2146
+ * digest line into wiki/log.md, (3) optional opt-in evidence-report regen,
2147
+ * (4) optional OKF package report regen.
1689
2148
  *
1690
2149
  * Returns:
1691
2150
  * - `parts`: message fragments for the inline handler to append to its
@@ -1695,6 +2154,8 @@ function regenerateEvidenceReport(wiki) {
1695
2154
  * - `evidence`: the regen result when `regenerateReport` was true,
1696
2155
  * `null` otherwise. Both call sites consume this to surface failure
1697
2156
  * into their visible response shape.
2157
+ * - `okf`: the regen result when `regenerateOkfReport` was true,
2158
+ * `null` otherwise.
1698
2159
  */
1699
2160
  function runPostRebuildEvidence(wiki, opts) {
1700
2161
  const parts = [];
@@ -1725,7 +2186,8 @@ function runPostRebuildEvidence(wiki, opts) {
1725
2186
  }
1726
2187
  catch { /* never fails the rebuild */ }
1727
2188
  const evidence = opts.regenerateReport ? regenerateEvidenceReport(wiki) : null;
1728
- return { parts, evidence };
2189
+ const okf = opts.regenerateOkfReport ? regenerateOkfReport(wiki) : null;
2190
+ return { parts, evidence, okf };
1729
2191
  }
1730
2192
  export async function handleTool(wiki, name, args, opts) {
1731
2193
  switch (name) {
@@ -1744,7 +2206,19 @@ export async function handleTool(wiki, name, args, opts) {
1744
2206
  if (Array.isArray(result)) {
1745
2207
  return JSON.stringify({ ok: true, imported: result.length, documents: result }, null, 2);
1746
2208
  }
1747
- const text = JSON.stringify({ ok: true, document: result }, null, 2);
2209
+ // A new version of a file that pages already cite: say which pages now rest on the
2210
+ // older one, so the caller does not have to go looking.
2211
+ const affected = pagesCitingEarlierVersion(wiki, result.path);
2212
+ const text = JSON.stringify({
2213
+ ok: true,
2214
+ document: result,
2215
+ ...(affected.length > 0
2216
+ ? {
2217
+ affected_pages: affected,
2218
+ next: `${affected.length} page(s) cite an earlier version of this file. Check them against raw/${result.path} and rewrite; wiki_admin action:worklist lists everything that is due.`,
2219
+ }
2220
+ : {}),
2221
+ }, null, 2);
1748
2222
  // For single image files, include image content block so agent can describe it
1749
2223
  const imgBlock = tryImageBlock(join(wiki.config.rawDir, result.path), result.mimeType ?? "");
1750
2224
  return imgBlock ? [{ type: "text", text }, imgBlock] : text;
@@ -1965,7 +2439,7 @@ export async function handleTool(wiki, name, args, opts) {
1965
2439
  : { content: enrichedContent, linksAdded: 0 };
1966
2440
  // Auto-route to matching topic subdirectory
1967
2441
  const resolvedPage = wiki.resolvePagePath(args.page, linkedContent);
1968
- const writtenContent = wiki.write(resolvedPage, linkedContent, args.source);
2442
+ const writtenContent = wiki.write(resolvedPage, linkedContent, args.source, typeof args.actor === "string" && args.actor.trim() !== "" ? { actor: args.actor.trim() } : undefined);
1969
2443
  // Auto-rebuild indexes (skipped when called from batch — batch rebuilds once at end)
1970
2444
  if (!opts?.skipRebuild)
1971
2445
  wiki.rebuildIndex();
@@ -2001,18 +2475,30 @@ export async function handleTool(wiki, name, args, opts) {
2001
2475
  const pages = wiki.list(args.type, args.tag);
2002
2476
  return JSON.stringify({ pages, count: pages.length }, null, 2);
2003
2477
  }
2478
+ case "wiki_graph": {
2479
+ const pages = [];
2480
+ for (const pagePath of wiki.listAllPages()) {
2481
+ const page = wiki.read(pagePath);
2482
+ if (page)
2483
+ pages.push(page);
2484
+ }
2485
+ const graph = computeWikiGraph(pages, isSystemPage);
2486
+ return JSON.stringify(runWikiGraphQuery(graph, args), null, 2);
2487
+ }
2004
2488
  case "wiki_search": {
2005
2489
  const searchQuery = args.query;
2006
2490
  const searchLimit = args.limit ?? 10;
2007
2491
  const filterType = args.type;
2008
2492
  const filterTags = args.tags;
2009
2493
  // Fetch extra candidates so post-filter doesn't starve results
2010
- const fetchLimit = (filterType || filterTags?.length) ? searchLimit * 3 : searchLimit;
2494
+ // ... and so that ranking by currency can bring up a current page that relevance
2495
+ // alone put just below the cut (see CURRENCY_HEADROOM).
2496
+ const fetchLimit = ((filterType || filterTags?.length) ? searchLimit * 3 : searchLimit) + CURRENCY_HEADROOM;
2011
2497
  const rawResults = wiki.config.search.hybrid
2012
2498
  ? await wiki.searchHybrid(searchQuery, fetchLimit)
2013
2499
  : wiki.search(searchQuery, fetchLimit);
2014
2500
  // Apply type / tags filters (post-ranking — BM25 scores are unaffected)
2015
- const results = (filterType || filterTags?.length)
2501
+ const candidates = (filterType || filterTags?.length)
2016
2502
  ? rawResults.filter(r => {
2017
2503
  const p = wiki.read(r.path);
2018
2504
  if (!p)
@@ -2022,9 +2508,10 @@ export async function handleTool(wiki, name, args, opts) {
2022
2508
  if (filterTags?.length && !filterTags.some(t => p.tags.includes(t)))
2023
2509
  return false;
2024
2510
  return true;
2025
- }).slice(0, searchLimit)
2511
+ })
2026
2512
  : rawResults;
2027
- const envelope = buildSearchEnvelope(results, searchQuery, (e) => appendSearchEvent(wiki.config.workspace, e));
2513
+ const results = rankSearchResults(wiki, candidates).slice(0, searchLimit);
2514
+ const envelope = withIndexDowngrades(wiki, results, buildSearchEnvelope(results, searchQuery, (e) => appendSearchEvent(wiki.config.workspace, e)), readMinTrust(args.min_trust));
2028
2515
  // Knowledge gap: guide the agent when the search finds nothing
2029
2516
  if (results.length === 0) {
2030
2517
  return JSON.stringify({
@@ -2141,10 +2628,11 @@ export async function handleTool(wiki, name, args, opts) {
2141
2628
  const perPageLimit = Math.min(500, Math.max(1, Math.floor(args.perPageLimit ?? 200)));
2142
2629
  const includeToc = args.includeToc ?? false;
2143
2630
  // Step 1: Search
2144
- const results = wiki.config.search.hybrid
2145
- ? await wiki.searchHybrid(query, limit)
2146
- : wiki.search(query, limit);
2147
- const envelope = buildSearchEnvelope(results, query, (e) => appendSearchEvent(wiki.config.workspace, e));
2631
+ const candidates = wiki.config.search.hybrid
2632
+ ? await wiki.searchHybrid(query, limit + CURRENCY_HEADROOM)
2633
+ : wiki.search(query, limit + CURRENCY_HEADROOM);
2634
+ const results = rankSearchResults(wiki, candidates).slice(0, limit);
2635
+ const envelope = withIndexDowngrades(wiki, results, buildSearchEnvelope(results, query, (e) => appendSearchEvent(wiki.config.workspace, e)), readMinTrust(args.min_trust));
2148
2636
  // Knowledge gap: guide the agent when the search finds nothing
2149
2637
  if (results.length === 0) {
2150
2638
  return JSON.stringify({
@@ -2203,6 +2691,71 @@ export async function handleTool(wiki, name, args, opts) {
2203
2691
  catch { /* ignore */ }
2204
2692
  return JSON.stringify(report, null, 2);
2205
2693
  }
2694
+ case "wiki_worklist": {
2695
+ const kind = args.kind;
2696
+ if (kind !== undefined && !["rewrite", "reconcile", "review", "ingest"].includes(kind)) {
2697
+ throw new Error(`wiki_admin worklist: unknown kind "${kind}". Expected: rewrite | reconcile | review | ingest`);
2698
+ }
2699
+ const list = buildWorklist(wiki, { limit: args.limit, kind: kind });
2700
+ const s = list.summary;
2701
+ const evidence = strongDeterministic(`Worklist from the current state of wiki/ and raw/: ${s.rewrite} to rewrite, ${s.reconcile} to reconcile, ${s.review} to review, ${s.ingest} to ingest.`);
2702
+ return JSON.stringify({ ...list, evidence }, null, 2);
2703
+ }
2704
+ case "wiki_verify": {
2705
+ const page = args.page;
2706
+ const by = args.by;
2707
+ if (typeof page !== "string" || page.trim() === "")
2708
+ throw new Error('wiki_admin verify: "page" is required');
2709
+ if (typeof by !== "string" || by.trim() === "")
2710
+ throw new Error('wiki_admin verify: "by" is required, e.g. human:ana');
2711
+ const result = wiki.verify(page.trim(), by.trim());
2712
+ return JSON.stringify({ ok: true, page: result.page, verified: result.event, trust_tier: result.trust.tier }, null, 2);
2713
+ }
2714
+ case "wiki_export": {
2715
+ const format = args.format ?? "okf";
2716
+ if (format !== "okf")
2717
+ throw new Error(`wiki_admin export: unknown format "${format}". Expected: okf`);
2718
+ const out = args.out;
2719
+ if (typeof out !== "string" || out.trim() === "")
2720
+ throw new Error('wiki_admin export: "out" is required');
2721
+ const report = exportOkfBundle(wiki, out, { overwrite: args.overwrite === true });
2722
+ if (report.ok) {
2723
+ wiki.log("export", "—", `Exported OKF bundle "${report.bundle.title}": ${report.bundle.concepts} concepts, ${report.written.length} files`);
2724
+ }
2725
+ return JSON.stringify(report, null, 2);
2726
+ }
2727
+ case "wiki_import": {
2728
+ const format = args.format ?? "okf";
2729
+ if (format !== "okf")
2730
+ throw new Error(`wiki_admin import: unknown format "${format}". Expected: okf`);
2731
+ const source = args.path;
2732
+ if (typeof source !== "string" || source.trim() === "")
2733
+ throw new Error('wiki_admin import: "path" is required');
2734
+ const importOpts = { overwrite: args.overwrite === true, generatedPaths: pluginGeneratedWikiPaths(wiki) };
2735
+ let report = importOkfBundle(wiki, source, { ...importOpts, dryRun: true });
2736
+ if (report.ok && args.dry_run !== true) {
2737
+ // The one-shot legacy migration tags every page it finds without sources. Let it
2738
+ // settle the pages that are here now, so the rebuild after the import does not
2739
+ // take the imported files for legacy pages and rewrite them.
2740
+ try {
2741
+ migrateExistingPagesForEvidence(wiki, listPlugins().map((p) => p.id));
2742
+ }
2743
+ catch { /* the rebuild below reports migration problems */ }
2744
+ report = importOkfBundle(wiki, source, importOpts);
2745
+ }
2746
+ if (report.ok && !report.dryRun) {
2747
+ wiki.log("import", "—", `Imported OKF bundle${report.bundle.title ? ` "${report.bundle.title}"` : ""}: ${report.bundle.concepts} concepts, ${report.imported.length} files`);
2748
+ if (!opts?.skipRebuild)
2749
+ await handleTool(wiki, "wiki_rebuild", {}, opts);
2750
+ }
2751
+ return JSON.stringify(report, null, 2);
2752
+ }
2753
+ case "wiki_reconcile": {
2754
+ const result = reconcilePages(wiki, args);
2755
+ if (result.written && !opts?.skipRebuild)
2756
+ wiki.rebuildIndex();
2757
+ return JSON.stringify(result.response, null, 2);
2758
+ }
2206
2759
  case "wiki_evidence_report": {
2207
2760
  const write = args.write ?? false;
2208
2761
  const result = runEvidenceReport(wiki, { write });
@@ -2245,6 +2798,9 @@ export async function handleTool(wiki, name, args, opts) {
2245
2798
  schemas: schemas.map(s => s.name),
2246
2799
  }, null, 2);
2247
2800
  }
2801
+ case "wiki_format_check": {
2802
+ return JSON.stringify(buildOkfPackageReport(wiki), null, 2);
2803
+ }
2248
2804
  // wiki_schemas removed — merged into wiki_config
2249
2805
  case "wiki_rebuild": {
2250
2806
  // Rebuild code knowledge graphs for all registered plugins FIRST,
@@ -2288,6 +2844,11 @@ export async function handleTool(wiki, name, args, opts) {
2288
2844
  // Yield event loop so MCP transport can respond to client pings.
2289
2845
  await new Promise((r) => setImmediate(r));
2290
2846
  wiki.rebuildTimeline(pageCache);
2847
+ // Refresh the page → counter-pages index that search reads to flag disputed hits.
2848
+ if (wiki.config.lint.checkContradictions)
2849
+ wiki.refreshContradictionIndex(pageCache);
2850
+ // Likewise the page → drifted-sources index.
2851
+ wiki.refreshSourceDriftIndex(pageCache);
2291
2852
  // Rebuild vector index if hybrid search is enabled
2292
2853
  let vectorStats;
2293
2854
  if (wiki.config.search.hybrid) {
@@ -2303,13 +2864,19 @@ export async function handleTool(wiki, name, args, opts) {
2303
2864
  // Single source of truth for post-rebuild evidence bookkeeping;
2304
2865
  // batch's end-of-batch path invokes the same helper for parity.
2305
2866
  const regenerateReport = args.evidence_report ?? false;
2306
- const bookkeeping = runPostRebuildEvidence(wiki, { regenerateReport });
2867
+ const regenerateOkf = args.okf_report ?? false;
2868
+ const bookkeeping = runPostRebuildEvidence(wiki, { regenerateReport, regenerateOkfReport: regenerateOkf });
2307
2869
  parts.push(...bookkeeping.parts);
2308
2870
  if (bookkeeping.evidence) {
2309
2871
  parts.push(bookkeeping.evidence.ok
2310
2872
  ? `Evidence report written to ${bookkeeping.evidence.writtenTo}`
2311
2873
  : `Evidence report regeneration failed: ${bookkeeping.evidence.error}`);
2312
2874
  }
2875
+ if (bookkeeping.okf) {
2876
+ parts.push(bookkeeping.okf.ok
2877
+ ? `OKF report written to ${bookkeeping.okf.writtenTo}`
2878
+ : `OKF report regeneration failed: ${bookkeeping.okf.error}`);
2879
+ }
2313
2880
  // On regen failure, surface a structured field alongside ok:true so
2314
2881
  // programmatic callers can detect partial-success without sniffing
2315
2882
  // the message string. Matches the batch handler's deferred-entry
@@ -2324,6 +2891,12 @@ export async function handleTool(wiki, name, args, opts) {
2324
2891
  error: bookkeeping.evidence.error,
2325
2892
  };
2326
2893
  }
2894
+ if (bookkeeping.okf && !bookkeeping.okf.ok) {
2895
+ response.okfReport = {
2896
+ ok: false,
2897
+ error: bookkeeping.okf.error,
2898
+ };
2899
+ }
2327
2900
  return JSON.stringify(response);
2328
2901
  }
2329
2902
  // wiki_classify removed — wiki_write auto-classifies
@@ -2864,11 +3437,13 @@ export async function handleTool(wiki, name, args, opts) {
2864
3437
  // op from this batch — the end-of-batch rebuild block below regenerates
2865
3438
  // the report once so the opt-in flag survives dedup.
2866
3439
  let needsEvidenceReport = false;
3440
+ let needsOkfReport = false;
2867
3441
  // Deferred entries from rebuild ops that asked for evidence_report:true.
2868
3442
  // Held by reference so we can mutate them in place on regen failure —
2869
3443
  // keeps the 1-op→1-result invariant and the established `{ tool, result }`
2870
3444
  // shape rather than introducing a sibling entry on failure.
2871
3445
  const rebuildEntriesAwaitingEvidence = [];
3446
+ const rebuildEntriesAwaitingOkf = [];
2872
3447
  const results = [];
2873
3448
  for (const op of ops) {
2874
3449
  if (op.tool === "batch") {
@@ -2894,6 +3469,11 @@ export async function handleTool(wiki, name, args, opts) {
2894
3469
  needsEvidenceReport = true;
2895
3470
  rebuildEntriesAwaitingEvidence.push(entry);
2896
3471
  }
3472
+ const opOkfReport = op.args?.okf_report ?? false;
3473
+ if (opOkfReport) {
3474
+ needsOkfReport = true;
3475
+ rebuildEntriesAwaitingOkf.push(entry);
3476
+ }
2897
3477
  continue;
2898
3478
  }
2899
3479
  try {
@@ -2959,6 +3539,7 @@ export async function handleTool(wiki, name, args, opts) {
2959
3539
  // produce equivalent side effects (log.md, .agent-wiki/ marker).
2960
3540
  const bookkeeping = runPostRebuildEvidence(wiki, {
2961
3541
  regenerateReport: needsEvidenceReport,
3542
+ regenerateOkfReport: needsOkfReport,
2962
3543
  });
2963
3544
  if (bookkeeping.evidence && !bookkeeping.evidence.ok) {
2964
3545
  // Surface failure in-place on the deferred entry so the caller
@@ -2972,6 +3553,15 @@ export async function handleTool(wiki, name, args, opts) {
2972
3553
  };
2973
3554
  }
2974
3555
  }
3556
+ if (bookkeeping.okf && !bookkeeping.okf.ok) {
3557
+ for (const entry of rebuildEntriesAwaitingOkf) {
3558
+ const prior = entry.result;
3559
+ entry.result = {
3560
+ ...prior,
3561
+ okfReport: { ok: false, error: bookkeeping.okf.error },
3562
+ };
3563
+ }
3564
+ }
2975
3565
  }
2976
3566
  return JSON.stringify({ results, count: results.length }, null, 2);
2977
3567
  }
@@ -2991,10 +3581,16 @@ export async function handleTool(wiki, name, args, opts) {
2991
3581
  switch (action) {
2992
3582
  case "init": return handleTool(wiki, "wiki_init", args, opts);
2993
3583
  case "config": return handleTool(wiki, "wiki_config", args, opts);
3584
+ case "format-check": return handleTool(wiki, "wiki_format_check", args, opts);
2994
3585
  case "rebuild": return handleTool(wiki, "wiki_rebuild", args, opts);
2995
3586
  case "lint": return handleTool(wiki, "wiki_lint", args, opts);
2996
3587
  case "evidence-report": return handleTool(wiki, "wiki_evidence_report", args, opts);
2997
- default: throw new Error(`Unknown wiki_admin action: "${action}". Expected: init | config | rebuild | lint | evidence-report`);
3588
+ case "reconcile": return handleTool(wiki, "wiki_reconcile", args, opts);
3589
+ case "import": return handleTool(wiki, "wiki_import", args, opts);
3590
+ case "export": return handleTool(wiki, "wiki_export", args, opts);
3591
+ case "verify": return handleTool(wiki, "wiki_verify", args, opts);
3592
+ case "worklist": return handleTool(wiki, "wiki_worklist", args, opts);
3593
+ default: throw new Error(`Unknown wiki_admin action: "${action}". Expected: init | config | format-check | rebuild | lint | evidence-report | reconcile | import`);
2998
3594
  }
2999
3595
  }
3000
3596
  case "code_query": {