@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
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).\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). 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",
@@ -385,6 +460,64 @@ export function createServer(wikiPath, workspace) {
385
460
  type: "boolean",
386
461
  description: "[evidence-report] If true, persist the report to wiki/evidence-report.md in addition to returning it. Default: false.",
387
462
  },
463
+ evidence_report: {
464
+ type: "boolean",
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.",
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
+ },
388
521
  },
389
522
  required: ["action"],
390
523
  },
@@ -1376,6 +1509,29 @@ function applyDerivedArtifacts(wiki, pluginId, derived) {
1376
1509
  }
1377
1510
  return writtenArtifacts;
1378
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
+ }
1379
1535
  function rebuildDeferredGraphs(wiki) {
1380
1536
  for (const plugin of listPlugins()) {
1381
1537
  const parsedDir = join(wiki.config.rawDir, "parsed", plugin.id);
@@ -1544,6 +1700,300 @@ function buildImpactResponse(graph, sourceNode, maxDepth) {
1544
1700
  diagnostics: relevantDiagnostics,
1545
1701
  };
1546
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
+ }
1547
1997
  /**
1548
1998
  * Build a knowledge_gap suggestion when a search returns no results.
1549
1999
  * Derives suggested_page, suggested_title, type, and tags from the query
@@ -1654,6 +2104,91 @@ function readPagesContent(wiki, paths, sectionFilter, perPageLimit, includeToc)
1654
2104
  }
1655
2105
  return pages;
1656
2106
  }
2107
+ /**
2108
+ * Best-effort regeneration of `wiki/evidence-report.md`. Called from
2109
+ * `runPostRebuildEvidence` below, which both the inline and batched
2110
+ * rebuild paths invoke. The rebuild never fails on evidence
2111
+ * bookkeeping, but the flag is operator-requested — both callers
2112
+ * surface success or failure into their visible response so `ok:true`
2113
+ * never implies the regen happened when it didn't.
2114
+ */
2115
+ function regenerateEvidenceReport(wiki) {
2116
+ try {
2117
+ const er = runEvidenceReport(wiki, { write: true });
2118
+ // `write: true` always sets `writtenTo`; the null-check is here only
2119
+ // because the public signature keeps `writtenTo?: string` rather than
2120
+ // paying for overloads to narrow it for a single caller.
2121
+ if (!er.writtenTo) {
2122
+ return { ok: false, error: "runEvidenceReport(write:true) returned no writtenTo path" };
2123
+ }
2124
+ return { ok: true, writtenTo: er.writtenTo };
2125
+ }
2126
+ catch (err) {
2127
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
2128
+ }
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
+ }
2142
+ /**
2143
+ * Single source of truth for the post-rebuild evidence / OKF bookkeeping that
2144
+ * both `wiki_admin action:rebuild` (inline) and the end-of-batch rebuild
2145
+ * path execute: (1) one-shot migration of pre-existing pages, (2) weekly
2146
+ * digest line into wiki/log.md, (3) optional opt-in evidence-report regen,
2147
+ * (4) optional OKF package report regen.
2148
+ *
2149
+ * Returns:
2150
+ * - `parts`: message fragments for the inline handler to append to its
2151
+ * ok-message. The batch handler does not surface these and may
2152
+ * discard them — current behavior is to omit migration / digest
2153
+ * messages from batch responses (they remain in log.md).
2154
+ * - `evidence`: the regen result when `regenerateReport` was true,
2155
+ * `null` otherwise. Both call sites consume this to surface failure
2156
+ * into their visible response shape.
2157
+ * - `okf`: the regen result when `regenerateOkfReport` was true,
2158
+ * `null` otherwise.
2159
+ */
2160
+ function runPostRebuildEvidence(wiki, opts) {
2161
+ const parts = [];
2162
+ let migration = null;
2163
+ try {
2164
+ const pluginIds = listPlugins().map((p) => p.id);
2165
+ migration = migrateExistingPagesForEvidence(wiki, pluginIds);
2166
+ }
2167
+ catch { /* never fails the rebuild */ }
2168
+ if (migration && !migration.alreadyMigrated && migration.totalPages > 0) {
2169
+ parts.push(`Evidence migration: ${migration.totalPages} pages — ` +
2170
+ `${migration.grounded} grounded, ` +
2171
+ `${migration.syntheses + migration.preExistingSynthesis} synthesis, ` +
2172
+ `${migration.legacy} legacy-unsupported`);
2173
+ }
2174
+ try {
2175
+ const week = summarizeLastWeek(wiki.config.workspace);
2176
+ if (week.totalWrites > 0 || week.unsupportedTransitions > 0) {
2177
+ const ratioStr = week.wouldRejectRatio === null
2178
+ ? ""
2179
+ : ` — ${(week.wouldRejectRatio * 100).toFixed(1)}% blocked-or-would-block under Phase 2b`;
2180
+ wiki.log("evidence", "log.md", `Last 7 days: ${week.unsupportedWrites} unsupported `
2181
+ + `+ ${week.rejectedWrites} rejected `
2182
+ + `/ ${week.totalWrites} wiki_write(s) `
2183
+ + `(${week.unsupportedTransitions} new unsupported pages)`
2184
+ + `${ratioStr}.`);
2185
+ }
2186
+ }
2187
+ catch { /* never fails the rebuild */ }
2188
+ const evidence = opts.regenerateReport ? regenerateEvidenceReport(wiki) : null;
2189
+ const okf = opts.regenerateOkfReport ? regenerateOkfReport(wiki) : null;
2190
+ return { parts, evidence, okf };
2191
+ }
1657
2192
  export async function handleTool(wiki, name, args, opts) {
1658
2193
  switch (name) {
1659
2194
  // ═══ RAW LAYER ═══
@@ -1671,7 +2206,19 @@ export async function handleTool(wiki, name, args, opts) {
1671
2206
  if (Array.isArray(result)) {
1672
2207
  return JSON.stringify({ ok: true, imported: result.length, documents: result }, null, 2);
1673
2208
  }
1674
- 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);
1675
2222
  // For single image files, include image content block so agent can describe it
1676
2223
  const imgBlock = tryImageBlock(join(wiki.config.rawDir, result.path), result.mimeType ?? "");
1677
2224
  return imgBlock ? [{ type: "text", text }, imgBlock] : text;
@@ -1892,7 +2439,7 @@ export async function handleTool(wiki, name, args, opts) {
1892
2439
  : { content: enrichedContent, linksAdded: 0 };
1893
2440
  // Auto-route to matching topic subdirectory
1894
2441
  const resolvedPage = wiki.resolvePagePath(args.page, linkedContent);
1895
- 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);
1896
2443
  // Auto-rebuild indexes (skipped when called from batch — batch rebuilds once at end)
1897
2444
  if (!opts?.skipRebuild)
1898
2445
  wiki.rebuildIndex();
@@ -1928,18 +2475,30 @@ export async function handleTool(wiki, name, args, opts) {
1928
2475
  const pages = wiki.list(args.type, args.tag);
1929
2476
  return JSON.stringify({ pages, count: pages.length }, null, 2);
1930
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
+ }
1931
2488
  case "wiki_search": {
1932
2489
  const searchQuery = args.query;
1933
2490
  const searchLimit = args.limit ?? 10;
1934
2491
  const filterType = args.type;
1935
2492
  const filterTags = args.tags;
1936
2493
  // Fetch extra candidates so post-filter doesn't starve results
1937
- 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;
1938
2497
  const rawResults = wiki.config.search.hybrid
1939
2498
  ? await wiki.searchHybrid(searchQuery, fetchLimit)
1940
2499
  : wiki.search(searchQuery, fetchLimit);
1941
2500
  // Apply type / tags filters (post-ranking — BM25 scores are unaffected)
1942
- const results = (filterType || filterTags?.length)
2501
+ const candidates = (filterType || filterTags?.length)
1943
2502
  ? rawResults.filter(r => {
1944
2503
  const p = wiki.read(r.path);
1945
2504
  if (!p)
@@ -1949,9 +2508,10 @@ export async function handleTool(wiki, name, args, opts) {
1949
2508
  if (filterTags?.length && !filterTags.some(t => p.tags.includes(t)))
1950
2509
  return false;
1951
2510
  return true;
1952
- }).slice(0, searchLimit)
2511
+ })
1953
2512
  : rawResults;
1954
- 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));
1955
2515
  // Knowledge gap: guide the agent when the search finds nothing
1956
2516
  if (results.length === 0) {
1957
2517
  return JSON.stringify({
@@ -2068,10 +2628,11 @@ export async function handleTool(wiki, name, args, opts) {
2068
2628
  const perPageLimit = Math.min(500, Math.max(1, Math.floor(args.perPageLimit ?? 200)));
2069
2629
  const includeToc = args.includeToc ?? false;
2070
2630
  // Step 1: Search
2071
- const results = wiki.config.search.hybrid
2072
- ? await wiki.searchHybrid(query, limit)
2073
- : wiki.search(query, limit);
2074
- 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));
2075
2636
  // Knowledge gap: guide the agent when the search finds nothing
2076
2637
  if (results.length === 0) {
2077
2638
  return JSON.stringify({
@@ -2130,6 +2691,71 @@ export async function handleTool(wiki, name, args, opts) {
2130
2691
  catch { /* ignore */ }
2131
2692
  return JSON.stringify(report, null, 2);
2132
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
+ }
2133
2759
  case "wiki_evidence_report": {
2134
2760
  const write = args.write ?? false;
2135
2761
  const result = runEvidenceReport(wiki, { write });
@@ -2172,6 +2798,9 @@ export async function handleTool(wiki, name, args, opts) {
2172
2798
  schemas: schemas.map(s => s.name),
2173
2799
  }, null, 2);
2174
2800
  }
2801
+ case "wiki_format_check": {
2802
+ return JSON.stringify(buildOkfPackageReport(wiki), null, 2);
2803
+ }
2175
2804
  // wiki_schemas removed — merged into wiki_config
2176
2805
  case "wiki_rebuild": {
2177
2806
  // Rebuild code knowledge graphs for all registered plugins FIRST,
@@ -2215,23 +2844,16 @@ export async function handleTool(wiki, name, args, opts) {
2215
2844
  // Yield event loop so MCP transport can respond to client pings.
2216
2845
  await new Promise((r) => setImmediate(r));
2217
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);
2218
2852
  // Rebuild vector index if hybrid search is enabled
2219
2853
  let vectorStats;
2220
2854
  if (wiki.config.search.hybrid) {
2221
2855
  vectorStats = await wiki.rebuildVectorIndex().catch(() => undefined);
2222
2856
  }
2223
- // Evidence-first phase 2a: one-shot migration of pre-existing pages
2224
- // (gated by marker file under .agent-wiki/) so existing compiler
2225
- // artifacts and user pages don't all flag as "unsupported" the day
2226
- // phase 2a ships. Also emit a one-line weekly count of unsupported
2227
- // writes into wiki/log.md so the maintainer has a running signal
2228
- // ahead of the phase 4 dashboard.
2229
- let migration = null;
2230
- try {
2231
- const pluginIds = listPlugins().map((p) => p.id);
2232
- migration = migrateExistingPagesForEvidence(wiki, pluginIds);
2233
- }
2234
- catch { /* ignore — evidence bookkeeping never fails a rebuild */ }
2235
2857
  const parts = ["Index and timeline rebuilt"];
2236
2858
  if (graphStats) {
2237
2859
  parts.push(`Knowledge graph: ${graphStats.nodes} nodes, ${graphStats.edges} edges`);
@@ -2239,27 +2861,43 @@ export async function handleTool(wiki, name, args, opts) {
2239
2861
  if (vectorStats) {
2240
2862
  parts.push(`Vector index: ${vectorStats.pagesProcessed} pages embedded${vectorStats.errors > 0 ? `, ${vectorStats.errors} errors` : ""}`);
2241
2863
  }
2242
- if (migration && !migration.alreadyMigrated && migration.totalPages > 0) {
2243
- parts.push(`Evidence migration: ${migration.totalPages} pages — ` +
2244
- `${migration.grounded} grounded, ` +
2245
- `${migration.syntheses + migration.preExistingSynthesis} synthesis, ` +
2246
- `${migration.legacy} legacy-unsupported`);
2864
+ // Single source of truth for post-rebuild evidence bookkeeping;
2865
+ // batch's end-of-batch path invokes the same helper for parity.
2866
+ const regenerateReport = args.evidence_report ?? false;
2867
+ const regenerateOkf = args.okf_report ?? false;
2868
+ const bookkeeping = runPostRebuildEvidence(wiki, { regenerateReport, regenerateOkfReport: regenerateOkf });
2869
+ parts.push(...bookkeeping.parts);
2870
+ if (bookkeeping.evidence) {
2871
+ parts.push(bookkeeping.evidence.ok
2872
+ ? `Evidence report written to ${bookkeeping.evidence.writtenTo}`
2873
+ : `Evidence report regeneration failed: ${bookkeeping.evidence.error}`);
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
+ }
2880
+ // On regen failure, surface a structured field alongside ok:true so
2881
+ // programmatic callers can detect partial-success without sniffing
2882
+ // the message string. Matches the batch handler's deferred-entry
2883
+ // shape (`evidenceReport: { ok: false, error }`).
2884
+ const response = {
2885
+ ok: true,
2886
+ message: parts.join(". ") + ".",
2887
+ };
2888
+ if (bookkeeping.evidence && !bookkeeping.evidence.ok) {
2889
+ response.evidenceReport = {
2890
+ ok: false,
2891
+ error: bookkeeping.evidence.error,
2892
+ };
2247
2893
  }
2248
- try {
2249
- const week = summarizeLastWeek(wiki.config.workspace);
2250
- if (week.totalWrites > 0 || week.unsupportedTransitions > 0) {
2251
- const ratioStr = week.wouldRejectRatio === null
2252
- ? ""
2253
- : ` — ${(week.wouldRejectRatio * 100).toFixed(1)}% blocked-or-would-block under Phase 2b`;
2254
- wiki.log("evidence", "log.md", `Last 7 days: ${week.unsupportedWrites} unsupported `
2255
- + `+ ${week.rejectedWrites} rejected `
2256
- + `/ ${week.totalWrites} wiki_write(s) `
2257
- + `(${week.unsupportedTransitions} new unsupported pages)`
2258
- + `${ratioStr}.`);
2259
- }
2894
+ if (bookkeeping.okf && !bookkeeping.okf.ok) {
2895
+ response.okfReport = {
2896
+ ok: false,
2897
+ error: bookkeeping.okf.error,
2898
+ };
2260
2899
  }
2261
- catch { /* ignore */ }
2262
- return JSON.stringify({ ok: true, message: parts.join(". ") + "." });
2900
+ return JSON.stringify(response);
2263
2901
  }
2264
2902
  // wiki_classify removed — wiki_write auto-classifies
2265
2903
  // wiki_synthesize removed — agent can wiki_read multiple pages
@@ -2795,6 +3433,17 @@ export async function handleTool(wiki, name, args, opts) {
2795
3433
  let needsRebuild = false;
2796
3434
  let needsTimeline = false;
2797
3435
  let needsGraphRebuild = false;
3436
+ // Carries through any `wiki_admin action:rebuild evidence_report:true`
3437
+ // op from this batch — the end-of-batch rebuild block below regenerates
3438
+ // the report once so the opt-in flag survives dedup.
3439
+ let needsEvidenceReport = false;
3440
+ let needsOkfReport = false;
3441
+ // Deferred entries from rebuild ops that asked for evidence_report:true.
3442
+ // Held by reference so we can mutate them in place on regen failure —
3443
+ // keeps the 1-op→1-result invariant and the established `{ tool, result }`
3444
+ // shape rather than introducing a sibling entry on failure.
3445
+ const rebuildEntriesAwaitingEvidence = [];
3446
+ const rebuildEntriesAwaitingOkf = [];
2798
3447
  const results = [];
2799
3448
  for (const op of ops) {
2800
3449
  if (op.tool === "batch") {
@@ -2807,7 +3456,24 @@ export async function handleTool(wiki, name, args, opts) {
2807
3456
  if (isRebuild) {
2808
3457
  needsRebuild = true;
2809
3458
  needsTimeline = true;
2810
- results.push({ tool: op.tool, result: { ok: true, deferred: "merged into end-of-batch rebuild" } });
3459
+ const entry = {
3460
+ tool: op.tool,
3461
+ result: { ok: true, deferred: "merged into end-of-batch rebuild" },
3462
+ };
3463
+ results.push(entry);
3464
+ // Match the in-handler `(args.X as boolean) ?? false` convention
3465
+ // (e.g. wiki_lint's apply_fixes) so the same input shape produces
3466
+ // the same behavior across every wiki_admin entry point.
3467
+ const opEvidenceReport = op.args?.evidence_report ?? false;
3468
+ if (opEvidenceReport) {
3469
+ needsEvidenceReport = true;
3470
+ rebuildEntriesAwaitingEvidence.push(entry);
3471
+ }
3472
+ const opOkfReport = op.args?.okf_report ?? false;
3473
+ if (opOkfReport) {
3474
+ needsOkfReport = true;
3475
+ rebuildEntriesAwaitingOkf.push(entry);
3476
+ }
2811
3477
  continue;
2812
3478
  }
2813
3479
  try {
@@ -2862,8 +3528,40 @@ export async function handleTool(wiki, name, args, opts) {
2862
3528
  if (needsRebuild) {
2863
3529
  const pageCache = wiki.buildPageCache();
2864
3530
  wiki.rebuildIndex(pageCache);
3531
+ // Yield to the event loop so the MCP transport can answer client
3532
+ // pings between the two rebuilds. Mirrors the inline rebuild path
3533
+ // (relevant on slow filesystems like OneDrive-synced workspaces).
3534
+ await new Promise((r) => setImmediate(r));
2865
3535
  if (needsTimeline)
2866
3536
  wiki.rebuildTimeline(pageCache);
3537
+ // Single source of truth for migration + weekly log + optional
3538
+ // regen — same helper the inline rebuild path uses, so the two
3539
+ // produce equivalent side effects (log.md, .agent-wiki/ marker).
3540
+ const bookkeeping = runPostRebuildEvidence(wiki, {
3541
+ regenerateReport: needsEvidenceReport,
3542
+ regenerateOkfReport: needsOkfReport,
3543
+ });
3544
+ if (bookkeeping.evidence && !bookkeeping.evidence.ok) {
3545
+ // Surface failure in-place on the deferred entry so the caller
3546
+ // gets one result per op, keeping `count: results.length` honest
3547
+ // and the shape uniform with the rest of this handler.
3548
+ for (const entry of rebuildEntriesAwaitingEvidence) {
3549
+ const prior = entry.result;
3550
+ entry.result = {
3551
+ ...prior,
3552
+ evidenceReport: { ok: false, error: bookkeeping.evidence.error },
3553
+ };
3554
+ }
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
+ }
2867
3565
  }
2868
3566
  return JSON.stringify({ results, count: results.length }, null, 2);
2869
3567
  }
@@ -2883,10 +3581,16 @@ export async function handleTool(wiki, name, args, opts) {
2883
3581
  switch (action) {
2884
3582
  case "init": return handleTool(wiki, "wiki_init", args, opts);
2885
3583
  case "config": return handleTool(wiki, "wiki_config", args, opts);
3584
+ case "format-check": return handleTool(wiki, "wiki_format_check", args, opts);
2886
3585
  case "rebuild": return handleTool(wiki, "wiki_rebuild", args, opts);
2887
3586
  case "lint": return handleTool(wiki, "wiki_lint", args, opts);
2888
3587
  case "evidence-report": return handleTool(wiki, "wiki_evidence_report", args, opts);
2889
- 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`);
2890
3594
  }
2891
3595
  }
2892
3596
  case "code_query": {