@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/wiki.js CHANGED
@@ -22,14 +22,76 @@
22
22
  import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync, unlinkSync, rmdirSync, statSync, copyFileSync, createWriteStream, appendFileSync } from "node:fs";
23
23
  import { pipeline } from "node:stream/promises";
24
24
  import { Readable } from "node:stream";
25
- import { join, relative, resolve, basename, extname, dirname } from "node:path";
25
+ import { join, relative, resolve, basename, extname, dirname, posix } from "node:path";
26
26
  import { createHash } from "node:crypto";
27
27
  import matter from "gray-matter";
28
+ import { moveToNativeKeys, withNativeKeys, extractLinks, isExactLink, isOkfReservedFile, readSources, readTags, isOkfActor, okfTrust, parseOkfTimestamp, readVerified, sameContent } from "./okf-compat.js";
28
29
  import yaml from "js-yaml";
29
30
  import { VERSION } from "./version.js";
30
31
  import { SearchEngine, DEFAULT_SEARCH_CONFIG } from "./search.js";
31
32
  import { extractText, extractDocument, guessMime } from "./extraction.js";
32
33
  import { appendUnsupportedWriteEvent, appendWriteEvent } from "./evidence-write-log.js";
34
+ export const CONTRADICTION_INDEX_FILE = ".contradiction-index.json";
35
+ export const SOURCE_DRIFT_INDEX_FILE = ".source-drift-index.json";
36
+ /** What happened to a cited source, as the end of a sentence that starts with its name. */
37
+ export function describeSourceDrift(d) {
38
+ if (d.reason === "missing")
39
+ return "no longer exists";
40
+ if (d.reason === "superseded") {
41
+ // An index written by hand or by an older build may lack the path, or carry it with
42
+ // the raw/ prefix already.
43
+ const newer = d.newerVersion ? ` (raw/${d.newerVersion.replace(/^raw\//, "")})` : "";
44
+ return `has a newer version${newer} added after this page was written`;
45
+ }
46
+ return "has changed since this page was written";
47
+ }
48
+ /** A `sources` entry as a path under raw/, or null for a URL. */
49
+ export function rawPathOfSource(source) {
50
+ const t = source.trim();
51
+ if (t === "" || /^[a-z][a-z0-9+.-]*:\/\//i.test(t))
52
+ return null;
53
+ // Collapse "./" and "x/../" so that a citation written as raw/./report.md or
54
+ // raw/sub/../report.md names the same file the raw/ scan lists as report.md.
55
+ const rel = posix.normalize(t.replace(/\\/g, "/").replace(/^\.\//, "").replace(/^raw\//, ""));
56
+ if (rel === "." || rel === ".." || rel.startsWith("../") || rel.startsWith("/"))
57
+ return null;
58
+ return rel;
59
+ }
60
+ /** Extension key under which an OKF export records source drift on the concept. */
61
+ export const CARRIED_SOURCE_DRIFT_KEY = "x-agent-wiki-source-drift";
62
+ /** Source drift that an exporting workspace wrote onto a page (see okf-export.ts). */
63
+ function carriedSourceDrift(fm) {
64
+ const value = fm[CARRIED_SOURCE_DRIFT_KEY];
65
+ if (!Array.isArray(value))
66
+ return [];
67
+ const out = [];
68
+ for (const item of value) {
69
+ if (!item || typeof item !== "object" || Array.isArray(item))
70
+ continue;
71
+ const { resource, reason } = item;
72
+ if (typeof resource !== "string" || resource.trim() === "")
73
+ continue;
74
+ if (reason !== "changed" && reason !== "missing" && reason !== "superseded")
75
+ continue;
76
+ out.push({ source: resource, reason, sealedSha: "" });
77
+ }
78
+ return out;
79
+ }
80
+ /** Split "dir/report_v3.xlsx" into its version chain ("dir/report" + ".xlsx") and number. */
81
+ function rawVersionOf(rawPath) {
82
+ const ext = extname(rawPath);
83
+ const base = rawPath.slice(0, rawPath.length - ext.length);
84
+ const m = base.match(/^(.+?)_v(\d+)$/);
85
+ return m ? { chain: m[1] + ext, version: parseInt(m[2], 10) } : { chain: base + ext, version: 1 };
86
+ }
87
+ /** True for a page written by `wiki_admin` `reconcile`: it quotes both sides of a
88
+ * contradiction and must not be read as a third claim. */
89
+ export function isReconciliationPage(page) {
90
+ return Array.isArray(page.frontmatter.reconciles);
91
+ }
92
+ function contradictionPairKey(a, b) {
93
+ return [a, b].sort().join("\u0000");
94
+ }
33
95
  // System pages that lint should treat specially. `evidence-report.md` is
34
96
  // the auto-regenerated output of wiki_admin --action evidence-report; it
35
97
  // lives here (not in the lint/orphan tally, not in the source-coverage
@@ -270,9 +332,9 @@ _Chronological view of all knowledge in this wiki._
270
332
  // default schemas
271
333
  writeDefaultSchemas(schemasDir);
272
334
  // .gitignore in workspace (if separate, also add one there)
273
- writeFileSync(join(configRoot, ".gitignore"), "node_modules/\ndist/\n.env\n.lint-cache.json\n");
335
+ writeFileSync(join(configRoot, ".gitignore"), "node_modules/\ndist/\n.env\n.lint-cache.json\n.contradiction-index.json\n.source-drift-index.json\n");
274
336
  if (workspace && wsRoot !== configRoot) {
275
- writeFileSync(join(wsRoot, ".gitignore"), "# Agent Wiki workspace data\n.lint-cache.json\n");
337
+ writeFileSync(join(wsRoot, ".gitignore"), "# Agent Wiki workspace data\n.lint-cache.json\n.contradiction-index.json\n.source-drift-index.json\n");
276
338
  }
277
339
  return new Wiki(configRoot, workspace);
278
340
  }
@@ -1109,6 +1171,9 @@ _Chronological view of all knowledge in this wiki._
1109
1171
  /** Write (create or update) a wiki page. Content must include frontmatter.
1110
1172
  * Automatically injects/updates created and updated timestamps. */
1111
1173
  write(pagePath, content, source, opts) {
1174
+ if (opts?.actor !== undefined && !isOkfActor(opts.actor)) {
1175
+ throw new Error(`wiki_write: actor "${opts.actor}" is not an OKF actor. Use <producer>/<version> for an agent or tool, or <scheme>:<id> such as human:ana.`);
1176
+ }
1112
1177
  // Guard: nested */index.md paths are reserved for auto-generated directory indexes
1113
1178
  if (isSystemPage(pagePath) && !SYSTEM_PAGES.has(pagePath)) {
1114
1179
  throw new Error(`Cannot write to reserved path: ${pagePath}. Nested */index.md is auto-generated by wiki_rebuild.`);
@@ -1119,15 +1184,20 @@ _Chronological view of all knowledge in this wiki._
1119
1184
  const now = new Date().toISOString();
1120
1185
  // Parse incoming content to inject timestamps
1121
1186
  const parsed = matter(content);
1187
+ // Content that came from an OKF export may carry agent-wiki's keys as x-agent-wiki-*.
1188
+ moveToNativeKeys(parsed.data);
1122
1189
  // Read existing on-disk frontmatter once — used for created-timestamp
1123
1190
  // preservation and for evidence-first classification (telemetry dedupe
1124
1191
  // and legacy-flag preservation across edits). Resilient to a corrupted
1125
1192
  // existing file: treat as if there's no prior frontmatter; the write
1126
1193
  // proceeds and overwrites the corruption rather than crashing.
1127
1194
  let existingFrontmatter = null;
1195
+ let existingBody = null;
1128
1196
  if (existsSync(fullPath)) {
1129
1197
  try {
1130
- existingFrontmatter = matter(readFileSync(fullPath, "utf-8")).data;
1198
+ const onDisk = matter(readFileSync(fullPath, "utf-8"));
1199
+ existingFrontmatter = withNativeKeys(onDisk.data, pagePath);
1200
+ existingBody = onDisk.content;
1131
1201
  }
1132
1202
  catch {
1133
1203
  existingFrontmatter = null;
@@ -1143,8 +1213,7 @@ _Chronological view of all knowledge in this wiki._
1143
1213
  // (auto-generated index.md / log.md / timeline.md) are excluded — they're
1144
1214
  // synthesis by construction, not user/agent assertions.
1145
1215
  if (!isSystemPage(pagePath) && !opts?._bypassEvidenceClassification) {
1146
- const sourcesField = parsed.data.sources;
1147
- const sourcesCount = Array.isArray(sourcesField) ? sourcesField.length : 0;
1216
+ const sourcesCount = readSources(parsed.data.sources).length;
1148
1217
  // Both `synthesis: true` (new flag) and `type: synthesis` (pre-existing
1149
1218
  // convention used by compiler-generated pages and user-authored
1150
1219
  // synthesis pages) count as legitimate synthesis.
@@ -1225,6 +1294,57 @@ _Chronological view of all knowledge in this wiki._
1225
1294
  appendWriteEvent(this.config.workspace, synthesisFlag ? "synthesis" : "grounded", now);
1226
1295
  }
1227
1296
  }
1297
+ // Seal the raw sources this page cites: record each one's SHA-256 as of this write,
1298
+ // so lint can later tell when the ground has shifted. The map is rebuilt on every
1299
+ // write, which is what re-seals a page when it is edited. Skipped for internal
1300
+ // state-restoring writes, which must not count as the author re-reading the sources.
1301
+ if (!isSystemPage(pagePath) && !opts?._bypassEvidenceClassification) {
1302
+ const sealed = {};
1303
+ for (const src of readSources(parsed.data.sources)) {
1304
+ const rawPath = rawPathOfSource(src);
1305
+ const sha = rawPath === null ? undefined : this.rawSha(rawPath);
1306
+ if (sha)
1307
+ sealed[src] = sha;
1308
+ }
1309
+ if (Object.keys(sealed).length > 0)
1310
+ parsed.data.sources_sha = sealed;
1311
+ else
1312
+ delete parsed.data.sources_sha;
1313
+ // Writing the page is the author's re-check: drift carried in from an export is settled.
1314
+ delete parsed.data[CARRIED_SOURCE_DRIFT_KEY];
1315
+ // Trust (OKF §5.2). `generated` says who made the current content and when; it moves
1316
+ // only when the content changes, so that a review recorded after it stays current
1317
+ // across a trivial edit and stops counting once the text is rewritten (§5.3). Both
1318
+ // fields are kept by the server: what the submitted frontmatter says about them is
1319
+ // not taken over, and a review is recorded with `wiki_admin` `verify`, not here.
1320
+ const prior = existingFrontmatter?.generated;
1321
+ const unchanged = existingBody !== null && sameContent(existingBody, parsed.content);
1322
+ if (unchanged) {
1323
+ if (prior !== undefined)
1324
+ parsed.data.generated = prior;
1325
+ else
1326
+ delete parsed.data.generated; // how this text was made is not known
1327
+ }
1328
+ else {
1329
+ // Strictly later than every review on file and than the generation it replaces,
1330
+ // whatever the clock says (an imported page may carry a future date): the
1331
+ // reviews were of the earlier text and must stop counting.
1332
+ let at = Date.parse(now);
1333
+ const earlier = [parseOkfTimestamp(prior?.at)];
1334
+ for (const e of readVerified(existingFrontmatter?.verified)) {
1335
+ if (e && typeof e === "object")
1336
+ earlier.push(parseOkfTimestamp(e.at));
1337
+ }
1338
+ for (const t of earlier)
1339
+ if (t !== null && t >= at)
1340
+ at = t + 1;
1341
+ parsed.data.generated = { by: opts?.actor ?? `agent-wiki/${VERSION}`, at: new Date(at).toISOString() };
1342
+ }
1343
+ if (existingFrontmatter?.verified !== undefined)
1344
+ parsed.data.verified = existingFrontmatter.verified;
1345
+ else
1346
+ delete parsed.data.verified;
1347
+ }
1228
1348
  // Reconstruct content with updated frontmatter
1229
1349
  const finalContent = matter.stringify(parsed.content, parsed.data);
1230
1350
  writeFileSync(fullPath, finalContent.trimEnd() + "\n");
@@ -1490,19 +1610,29 @@ _Chronological view of all knowledge in this wiki._
1490
1610
  }
1491
1611
  // Reverse link index: slug → set of pages that link TO this slug
1492
1612
  const incomingLinks = new Map();
1613
+ // Markdown links name one file by its full path; they never match by basename.
1614
+ const exactIncoming = new Map();
1493
1615
  for (const [sourcePath, page] of pageMap) {
1494
1616
  for (const link of page.links) {
1495
- let targets = incomingLinks.get(link);
1617
+ const exact = isExactLink(link);
1618
+ const map = exact ? exactIncoming : incomingLinks;
1619
+ const key = exact ? link.slice(1) : link;
1620
+ let targets = map.get(key);
1496
1621
  if (!targets) {
1497
1622
  targets = new Set();
1498
- incomingLinks.set(link, targets);
1623
+ map.set(key, targets);
1499
1624
  }
1500
1625
  targets.add(sourcePath);
1501
1626
  }
1502
1627
  }
1503
1628
  for (const [pagePath, page] of pageMap) {
1504
1629
  // ── Missing frontmatter ──
1505
- if (Object.keys(page.frontmatter).length === 0) {
1630
+ // index.md and log.md are exempt at every level: in an OKF bundle they are reserved
1631
+ // names (§3.1) with no frontmatter below the root (§8, §9), and adding one would
1632
+ // break that. A nested log.md stays an ordinary page everywhere else, so a wiki
1633
+ // that already has one keeps it.
1634
+ const reserved = isSystemPage(pagePath) || isOkfReservedFile(pagePath);
1635
+ if (!reserved && Object.keys(page.frontmatter).length === 0) {
1506
1636
  if (applyFixes) {
1507
1637
  // Auto-fix: derive title from filename, auto-classify type + tags
1508
1638
  const titleFromFilename = basename(pagePath, ".md")
@@ -1526,7 +1656,7 @@ _Chronological view of all knowledge in this wiki._
1526
1656
  }
1527
1657
  }
1528
1658
  // ── Missing title ──
1529
- if (!page.title || page.title === basename(pagePath, extname(pagePath))) {
1659
+ if (!reserved && (!page.title || page.title === basename(pagePath, extname(pagePath)))) {
1530
1660
  report.issues.push({
1531
1661
  severity: "warning",
1532
1662
  page: pagePath,
@@ -1537,15 +1667,17 @@ _Chronological view of all knowledge in this wiki._
1537
1667
  });
1538
1668
  }
1539
1669
  // ── Orphan pages ──
1540
- if (this.config.lint.checkOrphans && !isSystemPage(pagePath)) {
1670
+ if (this.config.lint.checkOrphans && !reserved) {
1541
1671
  const slug = basename(pagePath, extname(pagePath));
1542
1672
  // Full relative slug: "topic/page-name" (without .md)
1543
1673
  const fullSlug = pagePath.endsWith(".md") ? pagePath.slice(0, -3) : pagePath;
1544
1674
  const slugIncoming = incomingLinks.get(slug);
1545
1675
  const fullSlugIncoming = incomingLinks.get(fullSlug);
1676
+ const exactPathIncoming = exactIncoming.get(fullSlug);
1546
1677
  // Check that at least one *other* page links here (exclude self-links)
1547
1678
  const hasIncoming = (slugIncoming !== undefined && (slugIncoming.size > 1 || !slugIncoming.has(pagePath))) ||
1548
- (fullSlugIncoming !== undefined && (fullSlugIncoming.size > 1 || !fullSlugIncoming.has(pagePath)));
1679
+ (fullSlugIncoming !== undefined && (fullSlugIncoming.size > 1 || !fullSlugIncoming.has(pagePath))) ||
1680
+ (exactPathIncoming !== undefined && (exactPathIncoming.size > 1 || !exactPathIncoming.has(pagePath)));
1549
1681
  if (!hasIncoming) {
1550
1682
  report.issues.push({
1551
1683
  severity: "warning",
@@ -1559,6 +1691,20 @@ _Chronological view of all knowledge in this wiki._
1559
1691
  }
1560
1692
  // ── Broken links ──
1561
1693
  for (const link of page.links) {
1694
+ if (isExactLink(link)) {
1695
+ // A Markdown link names exactly one file: no basename fallback, no guessing.
1696
+ if (pageSet.has(link.slice(1) + ".md"))
1697
+ continue;
1698
+ report.issues.push({
1699
+ severity: "error",
1700
+ page: pagePath,
1701
+ message: `Broken link: ${link}.md`,
1702
+ suggestion: `Create ${link.slice(1)}.md or fix the link`,
1703
+ autoFixable: false,
1704
+ category: "broken-link",
1705
+ });
1706
+ continue;
1707
+ }
1562
1708
  const linkPath = link.endsWith(".md") ? link : link + ".md";
1563
1709
  // O(1) direct-path check
1564
1710
  if (pageSet.has(linkPath) || pageSet.has(link))
@@ -1640,8 +1786,13 @@ _Chronological view of all knowledge in this wiki._
1640
1786
  }
1641
1787
  // ── Cross-page contradiction detection ──
1642
1788
  if (this.config.lint.checkContradictions) {
1643
- const contradictions = this.detectContradictions(pageMap);
1789
+ // Contradictions a reconciliation page already settles are not reported again.
1790
+ const state = this.contradictionState(pageMap);
1791
+ const contradictions = state.active;
1644
1792
  report.contradictions = contradictions;
1793
+ if (state.reconciled.length > 0)
1794
+ report.reconciledContradictions = state.reconciled.length;
1795
+ this.saveContradictionIndex(state);
1645
1796
  for (const c of contradictions) {
1646
1797
  report.issues.push({
1647
1798
  severity: c.severity,
@@ -1653,6 +1804,20 @@ _Chronological view of all knowledge in this wiki._
1653
1804
  });
1654
1805
  }
1655
1806
  }
1807
+ // ── Source drift: cited raw sources that changed since the page was written ──
1808
+ const drift = this.saveSourceDriftIndex(this.sourceDriftState(pageMap));
1809
+ for (const [pagePath, entries] of Object.entries(drift.pages)) {
1810
+ for (const d of entries) {
1811
+ report.issues.push({
1812
+ severity: "warning",
1813
+ page: pagePath,
1814
+ message: `Cited source ${d.source} ${describeSourceDrift(d)}`,
1815
+ suggestion: "Check the page against the current source, then write it again to re-seal",
1816
+ autoFixable: false,
1817
+ category: "source-drift",
1818
+ });
1819
+ }
1820
+ }
1656
1821
  // ── Raw file integrity (incremental — cached by mtime+size) ──
1657
1822
  if (this.config.lint.checkIntegrity) {
1658
1823
  const lintCache = this.loadLintCache() ?? { version: 1, entries: {} };
@@ -1729,6 +1894,9 @@ _Chronological view of all knowledge in this wiki._
1729
1894
  for (const [pagePath, page] of pageMap) {
1730
1895
  if (isSystemPage(pagePath))
1731
1896
  continue;
1897
+ // A reconciliation page quotes both sides; it is not a third claim.
1898
+ if (isReconciliationPage(page))
1899
+ continue;
1732
1900
  // Extract date claims: "published in 2021", "released March 2021", "born 2021-03-15"
1733
1901
  const datePatterns = page.content.matchAll(/(?:published|released|founded|created|introduced|launched|announced|born|died)\s+(?:in\s+|on\s+)?(?:(?:january|february|march|april|may|june|july|august|september|october|november|december)\s+)?(\d{4}(?:-\d{2}-\d{2})?)/gi);
1734
1902
  for (const m of datePatterns) {
@@ -1788,8 +1956,10 @@ _Chronological view of all knowledge in this wiki._
1788
1956
  const sharedTag = pA.tags.some(t => pB.tags.includes(t));
1789
1957
  const slugB = basename(b.page, ".md");
1790
1958
  const slugA = basename(a.page, ".md");
1791
- const linkedAtoB = pA.links.includes(slugB) || pA.links.includes(b.page.replace(/\.md$/, ""));
1792
- const linkedBtoA = pB.links.includes(slugA) || pB.links.includes(a.page.replace(/\.md$/, ""));
1959
+ const pathA = a.page.replace(/\.md$/, "");
1960
+ const pathB = b.page.replace(/\.md$/, "");
1961
+ const linkedAtoB = pA.links.includes(slugB) || pA.links.includes(pathB) || pA.links.includes("/" + pathB);
1962
+ const linkedBtoA = pB.links.includes(slugA) || pB.links.includes(pathA) || pB.links.includes("/" + pathA);
1793
1963
  if (!sharedTag && !linkedAtoB && !linkedBtoA)
1794
1964
  continue;
1795
1965
  contradictions.push({
@@ -1805,6 +1975,285 @@ _Chronological view of all knowledge in this wiki._
1805
1975
  }
1806
1976
  return contradictions;
1807
1977
  }
1978
+ /**
1979
+ * Bundle metadata on the root index.md that a rebuild must not lose. OKF §8.1 puts
1980
+ * `okf_version`, `title`, `description` and `license` there and requires a producer that
1981
+ * regenerates index.md to keep that frontmatter; extension keys are kept too. Returns
1982
+ * the title to write and the other kept keys as YAML lines.
1983
+ */
1984
+ rootIndexMetadata() {
1985
+ const fm = this.read("index.md")?.frontmatter ?? {};
1986
+ const own = new Set(["title", "type", "created", "updated"]);
1987
+ const keep = {};
1988
+ for (const [key, value] of Object.entries(fm)) {
1989
+ if (!own.has(key))
1990
+ keep[key] = value;
1991
+ }
1992
+ const isBundleRoot = fm.okf_version !== undefined && typeof fm.title === "string" && fm.title.trim() !== "";
1993
+ const title = isBundleRoot ? yaml.dump(fm.title, { lineWidth: -1 }).trim() : "Knowledge Base Index";
1994
+ const kept = Object.keys(keep).length > 0 ? yaml.dump(keep, { lineWidth: -1 }).trimEnd().split("\n") : [];
1995
+ return { title, kept };
1996
+ }
1997
+ // ── Contradiction index + reconciliation ──────────────────────
1998
+ /**
1999
+ * Run detection and split the result by whether a reconciliation page settles it.
2000
+ * A reconciliation page names its two pages in `reconciles` and the claims it covers in
2001
+ * `reconciled_claims`; a contradiction is settled only when both match, so a new
2002
+ * disagreement between the same two pages is still reported.
2003
+ */
2004
+ contradictionState(pageMap) {
2005
+ const pages = pageMap ?? this.buildPageCache();
2006
+ const settled = new Map(); // pair -> claim -> resolution page
2007
+ for (const [pagePath, page] of pages) {
2008
+ if (!isReconciliationPage(page))
2009
+ continue;
2010
+ const pair = page.frontmatter.reconciles.map(String);
2011
+ const claims = page.frontmatter.reconciled_claims;
2012
+ if (pair.length !== 2 || !Array.isArray(claims))
2013
+ continue;
2014
+ const key = contradictionPairKey(pair[0], pair[1]);
2015
+ const byClaim = settled.get(key) ?? new Map();
2016
+ for (const c of claims)
2017
+ byClaim.set(String(c), pagePath);
2018
+ settled.set(key, byClaim);
2019
+ }
2020
+ const active = [];
2021
+ const reconciled = [];
2022
+ for (const c of this.detectContradictions(pages)) {
2023
+ const resolution = settled.get(contradictionPairKey(c.pageA, c.pageB))?.get(c.claim);
2024
+ if (resolution)
2025
+ reconciled.push({ ...c, resolution });
2026
+ else
2027
+ active.push(c);
2028
+ }
2029
+ return { active, reconciled };
2030
+ }
2031
+ contradictionIndexCache = null;
2032
+ saveContradictionIndex(state) {
2033
+ const pages = {};
2034
+ const add = (page, entry) => {
2035
+ (pages[page] ??= []).push(entry);
2036
+ };
2037
+ for (const c of state.active) {
2038
+ add(c.pageA, { page: c.pageB, claim: c.claim, excerpt: c.excerptA, counterExcerpt: c.excerptB, severity: c.severity });
2039
+ add(c.pageB, { page: c.pageA, claim: c.claim, excerpt: c.excerptB, counterExcerpt: c.excerptA, severity: c.severity });
2040
+ }
2041
+ const index = {
2042
+ version: 1,
2043
+ builtAt: new Date().toISOString(),
2044
+ pages,
2045
+ reconciled: state.reconciled.length,
2046
+ };
2047
+ const file = join(this.config.workspace, CONTRADICTION_INDEX_FILE);
2048
+ writeFileSync(file, JSON.stringify(index));
2049
+ this.contradictionIndexCache = { mtimeMs: statSync(file).mtimeMs, index };
2050
+ return index;
2051
+ }
2052
+ /** Detect contradictions and persist the page → counter-pages index. Called by lint,
2053
+ * rebuild and reconcile. */
2054
+ refreshContradictionIndex(pageMap) {
2055
+ return this.saveContradictionIndex(this.contradictionState(pageMap));
2056
+ }
2057
+ /**
2058
+ * The persisted index, or null when lint or rebuild has not written one. Costs one stat
2059
+ * per call and re-reads the file only when it changed; it never runs detection and
2060
+ * never reads a page.
2061
+ */
2062
+ contradictionIndex() {
2063
+ const file = join(this.config.workspace, CONTRADICTION_INDEX_FILE);
2064
+ let mtimeMs;
2065
+ try {
2066
+ mtimeMs = statSync(file).mtimeMs;
2067
+ }
2068
+ catch {
2069
+ this.contradictionIndexCache = null;
2070
+ return null;
2071
+ }
2072
+ if (this.contradictionIndexCache?.mtimeMs === mtimeMs)
2073
+ return this.contradictionIndexCache.index;
2074
+ try {
2075
+ const raw = JSON.parse(readFileSync(file, "utf-8"));
2076
+ if (raw?.version !== 1 || typeof raw.pages !== "object" || raw.pages === null)
2077
+ return null;
2078
+ this.contradictionIndexCache = { mtimeMs, index: raw };
2079
+ return this.contradictionIndexCache.index;
2080
+ }
2081
+ catch {
2082
+ return null;
2083
+ }
2084
+ }
2085
+ /** Open contradictions recorded for `pagePath`, from the persisted index. */
2086
+ disputesFor(pagePath) {
2087
+ return this.contradictionIndex()?.pages[pagePath.replace(/\\/g, "/")] ?? [];
2088
+ }
2089
+ // ── Source drift ──────────────────────────────────────────────
2090
+ /** SHA-256 and add time of a file under raw/, from its sidecar when there is one;
2091
+ * otherwise the file is hashed and its mtime used. Undefined when there is no such file. */
2092
+ rawState(rawPath) {
2093
+ let full;
2094
+ try {
2095
+ full = safePath(this.config.rawDir, rawPath);
2096
+ }
2097
+ catch {
2098
+ return undefined;
2099
+ }
2100
+ if (!existsSync(full))
2101
+ return undefined;
2102
+ const stat = statSync(full);
2103
+ if (!stat.isFile())
2104
+ return undefined;
2105
+ let sha256;
2106
+ let downloadedAt;
2107
+ const metaPath = full + ".meta.yaml";
2108
+ if (existsSync(metaPath)) {
2109
+ try {
2110
+ const meta = yaml.load(readFileSync(metaPath, "utf-8"));
2111
+ if (typeof meta?.sha256 === "string" && meta.sha256.length > 0)
2112
+ sha256 = meta.sha256;
2113
+ const at = meta?.downloadedAt;
2114
+ downloadedAt = at instanceof Date ? at.toISOString() : typeof at === "string" ? at : undefined;
2115
+ }
2116
+ catch { /* fall through to the file itself */ }
2117
+ }
2118
+ return {
2119
+ sha256: sha256 ?? createHash("sha256").update(readFileSync(full)).digest("hex"),
2120
+ downloadedAt: downloadedAt ?? stat.mtime.toISOString(),
2121
+ };
2122
+ }
2123
+ rawSha(rawPath) {
2124
+ return this.rawState(rawPath)?.sha256;
2125
+ }
2126
+ /**
2127
+ * Compare every sealed page with the raw layer as it is now. A cited source has drifted
2128
+ * when its content changed, when it is gone, or when a newer version of it was added
2129
+ * after the page was last written. Pages without `sources_sha` predate sealing: their
2130
+ * baseline is unknown and they are counted, never flagged.
2131
+ */
2132
+ sourceDriftState(pageMap) {
2133
+ const pages = pageMap ?? this.buildPageCache();
2134
+ // One pass over raw/: current SHA and add time per file, grouped by version chain.
2135
+ const current = new Map();
2136
+ const chains = new Map();
2137
+ if (existsSync(this.config.rawDir)) {
2138
+ for (const file of listAllFiles(this.config.rawDir, this.config.rawDir)) {
2139
+ if (file.endsWith(".meta.yaml"))
2140
+ continue;
2141
+ const state = this.rawState(file);
2142
+ if (!state)
2143
+ continue;
2144
+ const { chain, version } = rawVersionOf(file);
2145
+ current.set(file, { ...state, version });
2146
+ const list = chains.get(chain);
2147
+ if (list)
2148
+ list.push(file);
2149
+ else
2150
+ chains.set(chain, [file]);
2151
+ }
2152
+ }
2153
+ const out = {};
2154
+ let sealedPages = 0;
2155
+ let unsealedPages = 0;
2156
+ for (const [pagePath, page] of pages) {
2157
+ if (isSystemPage(pagePath))
2158
+ continue;
2159
+ const sealed = page.frontmatter.sources_sha;
2160
+ if (!sealed || typeof sealed !== "object" || Array.isArray(sealed)) {
2161
+ // A page that came in through an OKF import has no seal to check here, but the
2162
+ // workspace that exported it may have recorded that its evidence had moved on.
2163
+ // That finding stays in force until the page is written again.
2164
+ const carried = carriedSourceDrift(page.frontmatter);
2165
+ if (carried.length > 0)
2166
+ out[pagePath] = carried;
2167
+ else if (page.sources.some((src) => rawPathOfSource(src) !== null))
2168
+ unsealedPages++;
2169
+ continue;
2170
+ }
2171
+ sealedPages++;
2172
+ const writtenAt = page.updated ? Date.parse(page.updated) : NaN;
2173
+ const entries = [];
2174
+ for (const [source, sealedShaRaw] of Object.entries(sealed)) {
2175
+ const sealedSha = String(sealedShaRaw);
2176
+ const rawPath = rawPathOfSource(source);
2177
+ if (rawPath === null)
2178
+ continue;
2179
+ // The cited file itself is looked up the way sealing found it, so a file the
2180
+ // scan does not list (a dot-prefixed path, say) is still seen; the scan is only
2181
+ // what version chains are built from.
2182
+ let now = current.get(rawPath);
2183
+ if (!now) {
2184
+ const direct = this.rawState(rawPath);
2185
+ if (direct) {
2186
+ now = { ...direct, version: rawVersionOf(rawPath).version };
2187
+ current.set(rawPath, now);
2188
+ }
2189
+ }
2190
+ if (!now) {
2191
+ entries.push({ source, reason: "missing", sealedSha });
2192
+ continue;
2193
+ }
2194
+ if (now.sha256 !== sealedSha) {
2195
+ entries.push({ source, reason: "changed", sealedSha, currentSha: now.sha256 });
2196
+ continue;
2197
+ }
2198
+ // Same content, but has a newer version arrived since the page was written?
2199
+ if (!Number.isFinite(writtenAt))
2200
+ continue;
2201
+ let newer = null;
2202
+ for (const other of chains.get(rawVersionOf(rawPath).chain) ?? []) {
2203
+ const o = current.get(other);
2204
+ if (o.version <= now.version || Date.parse(o.downloadedAt) <= writtenAt)
2205
+ continue;
2206
+ if (!newer || o.version > newer.version)
2207
+ newer = { path: other, version: o.version };
2208
+ }
2209
+ if (newer) {
2210
+ entries.push({ source, reason: "superseded", sealedSha, currentSha: now.sha256, newerVersion: newer.path });
2211
+ }
2212
+ }
2213
+ if (entries.length > 0)
2214
+ out[pagePath] = entries;
2215
+ }
2216
+ return { pages: out, sealedPages, unsealedPages };
2217
+ }
2218
+ sourceDriftIndexCache = null;
2219
+ saveSourceDriftIndex(state) {
2220
+ const index = { version: 1, builtAt: new Date().toISOString(), ...state };
2221
+ const file = join(this.config.workspace, SOURCE_DRIFT_INDEX_FILE);
2222
+ writeFileSync(file, JSON.stringify(index));
2223
+ this.sourceDriftIndexCache = { mtimeMs: statSync(file).mtimeMs, index };
2224
+ return index;
2225
+ }
2226
+ /** Check sealed pages against raw/ and persist the result. Called by lint and rebuild. */
2227
+ refreshSourceDriftIndex(pageMap) {
2228
+ return this.saveSourceDriftIndex(this.sourceDriftState(pageMap));
2229
+ }
2230
+ /**
2231
+ * The persisted drift index, or null when lint or rebuild has not written one. One stat
2232
+ * per call, re-read only when the file changed; never reads a page or a raw file.
2233
+ */
2234
+ sourceDriftIndex() {
2235
+ const file = join(this.config.workspace, SOURCE_DRIFT_INDEX_FILE);
2236
+ let mtimeMs;
2237
+ try {
2238
+ mtimeMs = statSync(file).mtimeMs;
2239
+ }
2240
+ catch {
2241
+ this.sourceDriftIndexCache = null;
2242
+ return null;
2243
+ }
2244
+ if (this.sourceDriftIndexCache?.mtimeMs === mtimeMs)
2245
+ return this.sourceDriftIndexCache.index;
2246
+ try {
2247
+ const raw = JSON.parse(readFileSync(file, "utf-8"));
2248
+ if (raw?.version !== 1 || typeof raw.pages !== "object" || raw.pages === null)
2249
+ return null;
2250
+ this.sourceDriftIndexCache = { mtimeMs, index: raw };
2251
+ return this.sourceDriftIndexCache.index;
2252
+ }
2253
+ catch {
2254
+ return null;
2255
+ }
2256
+ }
1808
2257
  // ── Synthesis — Knowledge distillation ────────────────────────
1809
2258
  /** Get context for synthesis: reads multiple pages and returns
1810
2259
  * their content for the agent to distill into a new page. */
@@ -2215,6 +2664,7 @@ _Chronological view of all knowledge in this wiki._
2215
2664
  }
2216
2665
  const hasTopics = Object.keys(topicPages).length > 0;
2217
2666
  const now = new Date().toISOString();
2667
+ const rootMeta = this.rootIndexMetadata();
2218
2668
  if (hasTopics) {
2219
2669
  // ── Build per-topic sub-indexes ──
2220
2670
  for (const [topic, tPages] of Object.entries(topicPages)) {
@@ -2224,10 +2674,11 @@ _Chronological view of all knowledge in this wiki._
2224
2674
  const topicCount = Object.keys(topicPages).length;
2225
2675
  let lines = [
2226
2676
  "---",
2227
- "title: Knowledge Base Index",
2677
+ `title: ${rootMeta.title}`,
2228
2678
  "type: index",
2229
2679
  `created: "${this.read("index.md")?.created ?? now}"`,
2230
2680
  `updated: "${now}"`,
2681
+ ...rootMeta.kept,
2231
2682
  "---",
2232
2683
  "",
2233
2684
  "# Knowledge Base Index",
@@ -2286,10 +2737,11 @@ _Chronological view of all knowledge in this wiki._
2286
2737
  }
2287
2738
  let lines = [
2288
2739
  "---",
2289
- "title: Knowledge Base Index",
2740
+ `title: ${rootMeta.title}`,
2290
2741
  "type: index",
2291
2742
  `created: "${this.read("index.md")?.created ?? now}"`,
2292
2743
  `updated: "${now}"`,
2744
+ ...rootMeta.kept,
2293
2745
  "---",
2294
2746
  "",
2295
2747
  "# Knowledge Base Index",
@@ -2446,19 +2898,53 @@ _Chronological view of all knowledge in this wiki._
2446
2898
  return [];
2447
2899
  return listMdFiles(dir, dir);
2448
2900
  }
2901
+ /**
2902
+ * Record that `by` confirmed a page against its sources: append a `verified` event
2903
+ * (OKF §5.2). Nothing else in the file changes: not the text, not `generated`, not
2904
+ * `updated`, not the sealed source hashes. Earlier events stay as history.
2905
+ */
2906
+ verify(pagePath, by, at = new Date()) {
2907
+ if (!isOkfActor(by)) {
2908
+ throw new Error(`verify: "${by}" is not an OKF actor. Use human:<id> for a person, process:<id> for an automated check, or <producer>/<version> for an agent.`);
2909
+ }
2910
+ const withMd = pagePath.endsWith(".md") ? pagePath : `${pagePath}.md`;
2911
+ if (isSystemPage(withMd) || isOkfReservedFile(withMd)) {
2912
+ throw new Error(`verify: ${withMd} is a generated page; there is nothing to review in it.`);
2913
+ }
2914
+ const fullPath = safePath(this.config.wikiDir, withMd);
2915
+ if (!existsSync(fullPath))
2916
+ throw new Error(`verify: page not found: ${withMd}`);
2917
+ const parsed = matter(readFileSync(fullPath, "utf-8"));
2918
+ if (Object.keys(parsed.data).length === 0) {
2919
+ throw new Error(`verify: ${withMd} has no frontmatter to record a review in.`);
2920
+ }
2921
+ // gray-matter hands out one cached object per input text: work on a copy.
2922
+ const data = { ...parsed.data };
2923
+ // Never earlier than the content it confirms, whatever the clocks say.
2924
+ const generatedAt = parseOkfTimestamp(data.generated?.at);
2925
+ const moment = generatedAt !== null && at.getTime() < generatedAt ? new Date(generatedAt) : at;
2926
+ const event = { by, at: moment.toISOString() };
2927
+ data.verified = [...readVerified(data.verified), event];
2928
+ writeFileSync(fullPath, matter.stringify(parsed.content, data).trimEnd() + "\n");
2929
+ this.searchEngine.invalidate();
2930
+ this.log("verify", withMd, `Verified by ${by}`);
2931
+ return { page: withMd, event, trust: okfTrust(data) };
2932
+ }
2449
2933
  parsePage(pagePath, raw) {
2450
2934
  const parsed = matter(raw);
2451
- const fm = parsed.data;
2935
+ // Keys an OKF export wrote as x-agent-wiki-* are read back under their native names.
2936
+ const fm = withNativeKeys(parsed.data, pagePath);
2452
2937
  const body = parsed.content.trim();
2453
- const linkMatches = body.matchAll(/\[\[([^\]]+)\]\]/g);
2454
- // Support [[slug|display text]] format — extract slug part only
2455
- const links = [...linkMatches].map((m) => m[1].split("|")[0].trim());
2938
+ // [[slug]] / [[slug|display text]] wikilinks, plus standard Markdown links to other
2939
+ // pages (the only link syntax OKF recognises).
2940
+ const links = extractLinks(body, pagePath);
2456
2941
  return {
2457
2942
  path: pagePath,
2458
2943
  title: fm.title ?? basename(pagePath, extname(pagePath)),
2459
2944
  type: fm.type,
2460
- tags: Array.isArray(fm.tags) ? fm.tags.map(String) : [],
2461
- sources: Array.isArray(fm.sources) ? fm.sources.map(String) : [],
2945
+ tags: readTags(fm.tags),
2946
+ // Strings (agent-wiki) or mappings with a `resource` (OKF §5.1).
2947
+ sources: readSources(fm.sources),
2462
2948
  content: body,
2463
2949
  frontmatter: fm,
2464
2950
  links,