@saasontools/strauss-kb 0.1.17 → 0.1.18

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.
package/dist/mcp-main.cjs CHANGED
@@ -79,6 +79,14 @@ var kbAnchorSchema = import_zod.z.object({
79
79
  hash: import_zod.z.string().regex(/^sha256:[0-9a-f]{64}$/, {
80
80
  message: "hash must be sha256:<64 hex chars>"
81
81
  }).optional(),
82
+ /**
83
+ * What `hash` was taken over: the span's raw text, or the normalised token
84
+ * stream a parser sees (`ast`). Absent means `raw`, which is what every
85
+ * anchor stamped before this field carries, so old hashes keep comparing
86
+ * the way they were written. An `ast` hash is blind to whitespace and
87
+ * comments, so reformatting the anchored code is not drift.
88
+ */
89
+ hash_kind: import_zod.z.enum(["raw", "ast"]).optional(),
82
90
  /** ISO 8601 timestamp of the last successful resolution. */
83
91
  resolved_at: import_zod.z.string().min(1).optional(),
84
92
  /** Line count of the text the hash was taken over. */
@@ -469,9 +477,9 @@ async function mapLimit(items, limit, fn) {
469
477
  { length: Math.min(limit, items.length) },
470
478
  async () => {
471
479
  while (!failed && next < items.length) {
472
- const at = next++;
480
+ const at2 = next++;
473
481
  try {
474
- out[at] = await fn(items[at], at);
482
+ out[at2] = await fn(items[at2], at2);
475
483
  } catch (error) {
476
484
  failed = true;
477
485
  throw error;
@@ -587,8 +595,8 @@ function safeSegment(value) {
587
595
  function revRef(rev) {
588
596
  const safe = rev.replace(/[^A-Za-z0-9_-]/g, "-").slice(0, 64);
589
597
  let hash = 5381;
590
- for (let at = 0; at < rev.length; at++) {
591
- hash = (hash * 33 ^ rev.charCodeAt(at)) >>> 0;
598
+ for (let at2 = 0; at2 < rev.length; at2++) {
599
+ hash = (hash * 33 ^ rev.charCodeAt(at2)) >>> 0;
592
600
  }
593
601
  return `refs/strauss/${safe}-${hash.toString(16)}`;
594
602
  }
@@ -697,8 +705,8 @@ function repoUrlIsSafe(repo) {
697
705
  if (!scheme?.[1]) return false;
698
706
  if (!allowed.includes(scheme[1].toLowerCase())) return false;
699
707
  const authority = url.slice(scheme[0].length).split("/")[0] ?? "";
700
- const at = authority.lastIndexOf("@");
701
- return at < 0 || !authority.slice(0, at).includes(":");
708
+ const at2 = authority.lastIndexOf("@");
709
+ return at2 < 0 || !authority.slice(0, at2).includes(":");
702
710
  }
703
711
  function protocolArgs() {
704
712
  const allowed = allowedProtocols();
@@ -789,7 +797,7 @@ async function readOneRepo(repo, url, declared, context) {
789
797
  return new Map([
790
798
  ...rejected2,
791
799
  ...wants.map(
792
- (want, at) => [wantKey(repo, want.ref, want.file), reads[at]]
800
+ (want, at2) => [wantKey(repo, want.ref, want.file), reads[at2]]
793
801
  )
794
802
  ]);
795
803
  }
@@ -1000,7 +1008,7 @@ async function readAnchorFiles(files, read, concurrency = DEFAULT_IO_CONCURRENCY
1000
1008
  return { ok: false, reason: "file-unreadable" };
1001
1009
  }
1002
1010
  });
1003
- return new Map(wanted.map((file, at) => [file, results[at]]));
1011
+ return new Map(wanted.map((file, at2) => [file, results[at2]]));
1004
1012
  }
1005
1013
 
1006
1014
  // src/anchor-resolver/resolver.ts
@@ -1190,8 +1198,8 @@ async function ensureGrammar(language, options = {}) {
1190
1198
  return miss(language, `grammar tree-sitter-${language}`, grammar);
1191
1199
  const parts = [];
1192
1200
  const total = pack2.tags.length;
1193
- for (const [at, part] of pack2.tags.entries()) {
1194
- const name = `${language} tags${total > 1 ? ` part ${at + 1}/${total}` : ""}`;
1201
+ for (const [at2, part] of pack2.tags.entries()) {
1202
+ const name = `${language} tags${total > 1 ? ` part ${at2 + 1}/${total}` : ""}`;
1195
1203
  const path = grammarCachePath(root, language, part.sha256, "scm");
1196
1204
  const held = await ensurePart(path, name, part, options);
1197
1205
  if (held !== true) return miss(language, name, held);
@@ -1336,8 +1344,8 @@ function typeNameIn(receiver) {
1336
1344
  while (stack.length) {
1337
1345
  const node = stack.pop();
1338
1346
  if (node.type === "type_identifier") return node.text;
1339
- for (let at = 0; at < node.childCount; at++) {
1340
- const child = node.child(at);
1347
+ for (let at2 = 0; at2 < node.childCount; at2++) {
1348
+ const child = node.child(at2);
1341
1349
  if (child) stack.push(child);
1342
1350
  }
1343
1351
  }
@@ -1346,7 +1354,7 @@ function typeNameIn(receiver) {
1346
1354
  function endsWith(chain, wanted) {
1347
1355
  if (wanted.length > chain.length) return false;
1348
1356
  const offset = chain.length - wanted.length;
1349
- return wanted.every((segment, at) => chain[offset + at] === segment);
1357
+ return wanted.every((segment, at2) => chain[offset + at2] === segment);
1350
1358
  }
1351
1359
  function width(node) {
1352
1360
  return node.endIndex - node.startIndex;
@@ -1372,6 +1380,26 @@ function spanOf(definition, source) {
1372
1380
  };
1373
1381
  }
1374
1382
 
1383
+ // src/tree-sitter-resolver/tokens.ts
1384
+ function tokens(root) {
1385
+ const out = [];
1386
+ const stack = [root];
1387
+ while (stack.length) {
1388
+ const node = stack.pop();
1389
+ if (node.type.includes("comment")) continue;
1390
+ if (node.childCount === 0) {
1391
+ const text = node.text.trim();
1392
+ if (text) out.push(text);
1393
+ continue;
1394
+ }
1395
+ for (let at2 = node.childCount - 1; at2 >= 0; at2--) {
1396
+ const child = node.child(at2);
1397
+ if (child) stack.push(child);
1398
+ }
1399
+ }
1400
+ return out;
1401
+ }
1402
+
1375
1403
  // src/tree-sitter-resolver/resolver.ts
1376
1404
  var TREE_CACHE_LIMIT = 32;
1377
1405
  var TreeSitterResolver = class {
@@ -1417,7 +1445,7 @@ var TreeSitterResolver = class {
1417
1445
  (language) => this.load(language)
1418
1446
  );
1419
1447
  languages.forEach(
1420
- (language, at) => this.loaded.set(language, loaded[at] ?? null)
1448
+ (language, at2) => this.loaded.set(language, loaded[at2] ?? null)
1421
1449
  );
1422
1450
  }
1423
1451
  /**
@@ -1505,6 +1533,60 @@ var TreeSitterResolver = class {
1505
1533
  this.trees.set(key, parsed);
1506
1534
  return parsed;
1507
1535
  }
1536
+ /**
1537
+ * Every definition this file declares, as dotted symbol and span.
1538
+ *
1539
+ * The inverse of `attempt`: that asks "where is this name", this asks "what
1540
+ * names are here". `moved` needs the second — the stored hash has to be
1541
+ * looked for at every definition in the repository, and there is no name to
1542
+ * ask about, since the whole question is which name now carries that code.
1543
+ */
1544
+ spans(source, file) {
1545
+ const language = languageForFile(file);
1546
+ if (!language) return [];
1547
+ const loaded = this.loaded.get(language);
1548
+ if (!loaded) return [];
1549
+ const parsed = this.parse(language, loaded, source);
1550
+ if (!parsed) return [];
1551
+ return parsed.definitions.filter((definition) => definition.target).map((definition) => ({
1552
+ symbol: chainOf(definition, parsed.byNodeId).join("."),
1553
+ span: spanOf(definition, source)
1554
+ }));
1555
+ }
1556
+ /**
1557
+ * The token stream of a span: every leaf the parser sees, comments dropped,
1558
+ * joined by single spaces.
1559
+ *
1560
+ * This is what makes a reformat not be drift. Hashing it rather than the raw
1561
+ * text means indentation, line breaks, trailing commas the formatter moved,
1562
+ * and every comment above or inside the definition are outside the hash —
1563
+ * and a renamed identifier or a changed literal is still inside it, because
1564
+ * those are leaves.
1565
+ *
1566
+ * `null` when the file has no grammar, the grammar would not load, or the
1567
+ * text will not parse: no normalisation is better than a guessed one.
1568
+ */
1569
+ normalize(text, file) {
1570
+ const language = file ? languageForFile(file) : void 0;
1571
+ if (!language) return null;
1572
+ const loaded = this.loaded.get(language);
1573
+ if (!loaded) return null;
1574
+ const parser = this.parser;
1575
+ if (!parser) return null;
1576
+ let tree;
1577
+ try {
1578
+ parser.setLanguage(loaded.language);
1579
+ tree = parser.parse(text);
1580
+ } catch {
1581
+ return null;
1582
+ }
1583
+ if (!tree) return null;
1584
+ try {
1585
+ return tokens(tree.rootNode).join(" ");
1586
+ } finally {
1587
+ tree.delete();
1588
+ }
1589
+ }
1508
1590
  /** Drops cached trees. Grammars stay loaded — they are immutable. */
1509
1591
  reset() {
1510
1592
  for (const parsed of this.trees.values()) parsed.tree.delete();
@@ -1658,7 +1740,7 @@ var regexResolver = {
1658
1740
  );
1659
1741
  const nearest = Math.min(...distances);
1660
1742
  if (Number.isFinite(nearest)) {
1661
- candidates = candidates.filter((_, at) => distances[at] === nearest);
1743
+ candidates = candidates.filter((_, at2) => distances[at2] === nearest);
1662
1744
  }
1663
1745
  }
1664
1746
  if (candidates.length !== 1) return null;
@@ -1673,8 +1755,8 @@ function escapeRegExp(value) {
1673
1755
  }
1674
1756
  function distanceToParent(lines, index2, parent) {
1675
1757
  const floor = Math.max(0, index2 - PARENT_SCOPE_LINES);
1676
- for (let at = index2; at >= floor; at--) {
1677
- if (parent.test(lines[at] ?? "")) return index2 - at;
1758
+ for (let at2 = index2; at2 >= floor; at2--) {
1759
+ if (parent.test(lines[at2] ?? "")) return index2 - at2;
1678
1760
  }
1679
1761
  return Number.POSITIVE_INFINITY;
1680
1762
  }
@@ -1702,10 +1784,12 @@ function resolveAnchorSpan(source, anchor, resolvers = [regexResolver]) {
1702
1784
  if (attempt.reason === "symbol-not-found") continue;
1703
1785
  return { ok: false, reason: attempt.reason };
1704
1786
  }
1787
+ const tokens2 = resolver.normalize?.(attempt.span.text, anchor.file);
1705
1788
  return {
1706
1789
  ok: true,
1707
1790
  span: attempt.span,
1708
- ...isResolverName(resolver.name) ? { resolver: resolver.name } : {}
1791
+ ...isResolverName(resolver.name) ? { resolver: resolver.name } : {},
1792
+ ...tokens2 ? { normalized: tokens2 } : {}
1709
1793
  };
1710
1794
  }
1711
1795
  return { ok: false, reason: "symbol-not-found" };
@@ -1733,6 +1817,11 @@ function resolverChanged(source, anchor, produced) {
1733
1817
  );
1734
1818
  return before !== null && hashAnchorText(before.text) === anchor.hash;
1735
1819
  }
1820
+ function anchorHashOf(anchor, outcome) {
1821
+ const stored = anchor.hash ? anchor.hash_kind ?? "raw" : void 0;
1822
+ const wanted = stored ?? (outcome.normalized ? "ast" : "raw");
1823
+ return wanted === "ast" && outcome.normalized ? { hash: hashAnchorText(outcome.normalized), kind: "ast" } : { hash: hashAnchorText(outcome.span.text), kind: "raw" };
1824
+ }
1736
1825
 
1737
1826
  // src/anchor-resolver/drift.ts
1738
1827
  async function detectAnchorDrift(records, options = {}) {
@@ -1812,16 +1901,29 @@ function unresolved(anchor, reason, repo) {
1812
1901
  state: "unresolved",
1813
1902
  diffSize: null,
1814
1903
  ...reason ? { reason } : {},
1815
- ...repo ? { repo } : {}
1904
+ ...repo ? { repo } : {},
1905
+ ...classOf(reason)
1816
1906
  };
1817
1907
  }
1908
+ function provisionalDriftClass(entry) {
1909
+ if (entry.state === "unresolved") {
1910
+ return entry.reason === "file-missing" || entry.reason === "symbol-not-found" ? "gone" : void 0;
1911
+ }
1912
+ return entry.state === "drifted" ? "changed" : void 0;
1913
+ }
1914
+ function classOf(reason) {
1915
+ const settled = provisionalDriftClass({ state: "unresolved", reason });
1916
+ return settled ? { class: settled } : {};
1917
+ }
1818
1918
  function hashIn(source, anchor, resolvers) {
1819
1919
  const outcome = resolveAnchorSpan(source, anchor, resolvers);
1820
1920
  if (!outcome.ok) return { ok: false, reason: outcome.reason };
1921
+ const { hash, kind } = anchorHashOf(anchor, outcome);
1821
1922
  return {
1822
1923
  ok: true,
1823
1924
  current: {
1824
- hash: hashAnchorText(outcome.span.text),
1925
+ hash,
1926
+ kind,
1825
1927
  lines: outcome.span.endLine - outcome.span.startLine + 1,
1826
1928
  ...outcome.resolver ? { resolver: outcome.resolver } : {}
1827
1929
  }
@@ -1834,11 +1936,14 @@ function resolverExtras(source, anchor, current) {
1834
1936
  };
1835
1937
  }
1836
1938
  function compared(anchor, current, extra = {}) {
1939
+ const matched = current.hash === anchor.hash;
1837
1940
  return {
1838
1941
  ...base(anchor),
1839
- state: current.hash === anchor.hash ? "match" : "drifted",
1942
+ state: matched ? "match" : "drifted",
1840
1943
  currentHash: current.hash,
1944
+ hashKind: current.kind,
1841
1945
  diffSize: anchor.lines === void 0 ? null : Math.abs(current.lines - anchor.lines),
1946
+ ...matched ? {} : { class: "changed" },
1842
1947
  ...extra
1843
1948
  };
1844
1949
  }
@@ -2280,7 +2385,7 @@ async function listPins(store, workspaceDir) {
2280
2385
  }
2281
2386
 
2282
2387
  // src/kb-pins/pin.ts
2283
- async function pinBase(store, workspaceDir, bundlePath2, at, options = {}) {
2388
+ async function pinBase(store, workspaceDir, bundlePath2, at2, options = {}) {
2284
2389
  const layer = options.layer ?? "project";
2285
2390
  const root = layerRoot(workspaceDir, layer);
2286
2391
  const manifest = await readPinsLayer(workspaceDir, layer);
@@ -2308,7 +2413,7 @@ async function pinBase(store, workspaceDir, bundlePath2, at, options = {}) {
2308
2413
  return {
2309
2414
  path: existing.path,
2310
2415
  layer,
2311
- pinnedAt: existing.pinnedAt ?? at,
2416
+ pinnedAt: existing.pinnedAt ?? at2,
2312
2417
  alreadyPinned: true,
2313
2418
  ...updated.mode ? { mode: updated.mode } : {},
2314
2419
  ...updated.profiles ? { profiles: updated.profiles } : {},
@@ -2318,7 +2423,7 @@ async function pinBase(store, workspaceDir, bundlePath2, at, options = {}) {
2318
2423
  }
2319
2424
  const entry = {
2320
2425
  path: storablePath(root, bundlePath2),
2321
- pinnedAt: at,
2426
+ pinnedAt: at2,
2322
2427
  ...fields
2323
2428
  };
2324
2429
  await writePinsLayer(workspaceDir, layer, {
@@ -2328,7 +2433,7 @@ async function pinBase(store, workspaceDir, bundlePath2, at, options = {}) {
2328
2433
  return {
2329
2434
  path: entry.path,
2330
2435
  layer,
2331
- pinnedAt: at,
2436
+ pinnedAt: at2,
2332
2437
  alreadyPinned: false,
2333
2438
  ...fields,
2334
2439
  ...warning ? { warning } : {}
@@ -2380,9 +2485,9 @@ function argvFlag(argv, name) {
2380
2485
  if (!value2) throw new KbMissingFlagValueError(name);
2381
2486
  return value2;
2382
2487
  }
2383
- const at = argv.indexOf(name);
2384
- if (at === -1) return void 0;
2385
- const value = argv[at + 1];
2488
+ const at2 = argv.indexOf(name);
2489
+ if (at2 === -1) return void 0;
2490
+ const value = argv[at2 + 1];
2386
2491
  if (value === void 0 || value.startsWith("--")) {
2387
2492
  throw new KbMissingFlagValueError(name);
2388
2493
  }
@@ -2475,11 +2580,14 @@ var anchorResolveCommand = define({
2475
2580
  }
2476
2581
  const resolved = outcome.span;
2477
2582
  const producedBy = outcome.resolver;
2478
- const currentHash = hashAnchorText(resolved.text);
2583
+ const { hash: currentHash, kind } = anchorHashOf(anchor, outcome);
2479
2584
  const currentLines = resolved.endLine - resolved.startLine + 1;
2585
+ const stampedKind = outcome.normalized ? "ast" : "raw";
2586
+ const stampedHash = outcome.normalized ? anchorHashOf({ ...anchor, hash: void 0 }, outcome).hash : currentHash;
2480
2587
  const stamped = {
2481
2588
  ...anchor,
2482
- hash: currentHash,
2589
+ hash: stampedHash,
2590
+ hash_kind: stampedKind,
2483
2591
  lines: currentLines,
2484
2592
  resolved_at: now(),
2485
2593
  ...producedBy ? { resolver: producedBy } : {}
@@ -2489,7 +2597,8 @@ var anchorResolveCommand = define({
2489
2597
  results.push({
2490
2598
  ...base2,
2491
2599
  state: "stamped",
2492
- currentHash,
2600
+ currentHash: stampedHash,
2601
+ hashKind: stampedKind,
2493
2602
  ...producedBy ? { resolver: producedBy } : {}
2494
2603
  });
2495
2604
  updated.push(stamped);
@@ -2501,6 +2610,7 @@ var anchorResolveCommand = define({
2501
2610
  ...base2,
2502
2611
  state: "drifted",
2503
2612
  currentHash,
2613
+ hashKind: kind,
2504
2614
  diffSize: lineDelta(anchor, currentLines),
2505
2615
  ...producedBy ? { resolver: producedBy } : {},
2506
2616
  // A regex-stamped anchor re-read by tree-sitter drifts because the
@@ -2529,6 +2639,7 @@ var anchorResolveCommand = define({
2529
2639
  ...base2,
2530
2640
  state: "match",
2531
2641
  currentHash,
2642
+ hashKind: kind,
2532
2643
  ...producedBy ? { resolver: producedBy } : {},
2533
2644
  ...pinned ? { remoteState: "matches-ref" } : {}
2534
2645
  });
@@ -2761,7 +2872,8 @@ function warningAnchor(entry) {
2761
2872
  diffSize,
2762
2873
  ...reason !== void 0 ? { reason } : {},
2763
2874
  ...repo !== void 0 ? { repo } : {},
2764
- ...remoteState !== void 0 ? { remoteState } : {}
2875
+ ...remoteState !== void 0 ? { remoteState } : {},
2876
+ ...entry.class !== void 0 ? { class: entry.class } : {}
2765
2877
  };
2766
2878
  }
2767
2879
  function resolveHeads(from, byId) {
@@ -3237,7 +3349,406 @@ var contextCommand = define({
3237
3349
  });
3238
3350
 
3239
3351
  // src/commands/doctor.ts
3240
- var import_zod12 = require("zod");
3352
+ var import_zod13 = require("zod");
3353
+
3354
+ // src/drift/git.ts
3355
+ var import_node_child_process3 = require("child_process");
3356
+ var import_node_util3 = require("util");
3357
+ var execFileAsync3 = (0, import_node_util3.promisify)(import_node_child_process3.execFile);
3358
+ var MAX_GIT_OUTPUT_BYTES = 1048576;
3359
+ var GIT_TIMEOUT_MS = 5e3;
3360
+ async function git2(cwd, args) {
3361
+ const env = { ...process.env };
3362
+ delete env["GIT_DIR"];
3363
+ delete env["GIT_WORK_TREE"];
3364
+ delete env["GIT_INDEX_FILE"];
3365
+ try {
3366
+ const { stdout } = await execFileAsync3("git", ["-C", cwd, ...args], {
3367
+ timeout: GIT_TIMEOUT_MS,
3368
+ maxBuffer: MAX_GIT_OUTPUT_BYTES,
3369
+ env
3370
+ });
3371
+ return { ok: true, stdout };
3372
+ } catch {
3373
+ return { ok: false };
3374
+ }
3375
+ }
3376
+ async function listRepoFiles(repoRoot) {
3377
+ const result = await git2(repoRoot, ["ls-files", "-z", "--cached"]);
3378
+ if (!result.ok) return [];
3379
+ return result.stdout.split("\0").filter(Boolean);
3380
+ }
3381
+ async function readOldSource(repoRoot, anchor) {
3382
+ if (!filePathIsSafe(anchor.file))
3383
+ return { ok: false, reason: "unrecoverable" };
3384
+ if (anchor.ref && refShapeIsSafe(anchor.ref)) {
3385
+ const shown2 = await showFile(repoRoot, anchor.ref, anchor.file);
3386
+ if (shown2 !== null) {
3387
+ return {
3388
+ ok: true,
3389
+ source: shown2,
3390
+ origin: { kind: "ref", ref: anchor.ref }
3391
+ };
3392
+ }
3393
+ }
3394
+ const at2 = anchor.resolved_at;
3395
+ if (!at2 || Number.isNaN(Date.parse(at2))) {
3396
+ return { ok: false, reason: "unrecoverable" };
3397
+ }
3398
+ const found = await git2(repoRoot, [
3399
+ "log",
3400
+ "-1",
3401
+ "--format=%H",
3402
+ `--before=${at2}`,
3403
+ "--end-of-options",
3404
+ "HEAD",
3405
+ "--",
3406
+ anchor.file
3407
+ ]);
3408
+ const sha = found.ok ? found.stdout.trim() : "";
3409
+ if (!sha || !refShapeIsSafe(sha))
3410
+ return { ok: false, reason: "unrecoverable" };
3411
+ const shown = await showFile(repoRoot, sha, anchor.file);
3412
+ if (shown === null) return { ok: false, reason: "unrecoverable" };
3413
+ return { ok: true, source: shown, origin: { kind: "history", ref: sha } };
3414
+ }
3415
+ async function showFile(repoRoot, ref, file) {
3416
+ const path = file.replace(/^\.\//, "");
3417
+ const result = await git2(repoRoot, [
3418
+ "show",
3419
+ "--end-of-options",
3420
+ `${ref}:${path}`
3421
+ ]);
3422
+ return result.ok ? result.stdout : null;
3423
+ }
3424
+
3425
+ // src/drift/moved.ts
3426
+ var import_promises7 = require("fs/promises");
3427
+ var MAX_MOVED_SEARCH_FILES = 2e3;
3428
+ var SEARCH_BATCH = 64;
3429
+ function movedSearch(repoRoot, options = {}) {
3430
+ const read = options.reader ?? anchorFileReader(repoRoot);
3431
+ const sizeOf = options.sizeOf ?? diskSize(repoRoot);
3432
+ const resolver = new TreeSitterResolver();
3433
+ let repoFiles;
3434
+ const prepared = /* @__PURE__ */ new Set();
3435
+ const filesForLanguage = async (language) => {
3436
+ repoFiles ??= listRepoFiles(repoRoot);
3437
+ return (await repoFiles).filter((file) => languageForFile(file) === language).slice(0, MAX_MOVED_SEARCH_FILES);
3438
+ };
3439
+ return {
3440
+ async find(anchor) {
3441
+ const stored = anchor.hash;
3442
+ if (!stored) return void 0;
3443
+ const language = languageForFile(anchor.file);
3444
+ if (!language) return sameFileWindow(anchor, read, stored);
3445
+ const candidates = await filesForLanguage(language);
3446
+ if (!prepared.has(language)) {
3447
+ await resolver.prepare(candidates.length ? candidates : [anchor.file]);
3448
+ prepared.add(language);
3449
+ }
3450
+ const floor = anchor.lines ?? 0;
3451
+ for (let at2 = 0; at2 < candidates.length; at2 += SEARCH_BATCH) {
3452
+ const batch = candidates.slice(at2, at2 + SEARCH_BATCH);
3453
+ const hits = await mapLimit(
3454
+ batch,
3455
+ DEFAULT_IO_CONCURRENCY,
3456
+ async (file) => {
3457
+ const size2 = await sizeOf(file);
3458
+ if (size2 !== null && size2 < floor) return void 0;
3459
+ return matchIn(resolver, read, anchor, stored, file);
3460
+ }
3461
+ );
3462
+ const found = hits.find((hit) => hit !== void 0);
3463
+ if (found) return found;
3464
+ }
3465
+ return void 0;
3466
+ }
3467
+ };
3468
+ }
3469
+ async function matchIn(resolver, read, anchor, stored, file) {
3470
+ const source = await read(file);
3471
+ if (!source.ok) return void 0;
3472
+ const normalized = source.source.replace(/\r\n/g, "\n");
3473
+ for (const found of resolver.spans(normalized, file)) {
3474
+ const text = anchor.hash_kind === "ast" ? resolver.normalize(found.span.text, file) : found.span.text;
3475
+ if (text === null || hashAnchorText(text) !== stored) continue;
3476
+ if (file === anchor.file && found.symbol === anchor.symbol) continue;
3477
+ return {
3478
+ file,
3479
+ symbol: found.symbol,
3480
+ startLine: found.span.startLine,
3481
+ endLine: found.span.endLine
3482
+ };
3483
+ }
3484
+ return void 0;
3485
+ }
3486
+ function diskSize(repoRoot) {
3487
+ return async (file) => {
3488
+ const path = anchorFilePath(repoRoot, file);
3489
+ if (path === null) return null;
3490
+ try {
3491
+ return (await (0, import_promises7.stat)(path)).size;
3492
+ } catch {
3493
+ return null;
3494
+ }
3495
+ };
3496
+ }
3497
+ async function sameFileWindow(anchor, read, stored) {
3498
+ const height = anchor.lines;
3499
+ if (!height || anchor.hash_kind === "ast") return void 0;
3500
+ const source = await read(anchor.file);
3501
+ if (!source.ok) return void 0;
3502
+ const lines = source.source.replace(/\r\n/g, "\n").split("\n");
3503
+ for (let at2 = 0; at2 + height <= lines.length; at2++) {
3504
+ if (hashAnchorText(lines.slice(at2, at2 + height).join("\n")) !== stored) {
3505
+ continue;
3506
+ }
3507
+ return {
3508
+ file: anchor.file,
3509
+ ...anchor.symbol ? { symbol: anchor.symbol } : {},
3510
+ startLine: at2 + 1,
3511
+ endLine: at2 + height
3512
+ };
3513
+ }
3514
+ return void 0;
3515
+ }
3516
+
3517
+ // src/drift/classify.ts
3518
+ async function classifyDrift(repoRoot, record, entries, options = {}) {
3519
+ const anchors = (record.frontmatter.strauss_anchors ?? []).filter(
3520
+ (anchor) => anchor.hash
3521
+ );
3522
+ const reader = options.reader ?? anchorFileReader(repoRoot);
3523
+ const treeSitter = new TreeSitterResolver();
3524
+ const resolvers = [treeSitter, regexResolver];
3525
+ const search = options.search ?? movedSearch(repoRoot, { ...options.reader ? { reader } : {} });
3526
+ const wanted = [];
3527
+ entries.forEach((entry, at2) => {
3528
+ const anchor = anchors[at2];
3529
+ if (!anchor) return;
3530
+ if (entry.state === "match" || isUncheckedReason(entry.reason)) return;
3531
+ wanted.push({ anchor, entry });
3532
+ });
3533
+ if (!wanted.length) return [];
3534
+ await prepareResolvers(
3535
+ resolvers,
3536
+ wanted.map(({ anchor }) => anchor.file)
3537
+ );
3538
+ const out = [];
3539
+ for (const { anchor, entry } of wanted) {
3540
+ const movedTo = await search.find(anchor);
3541
+ if (movedTo) {
3542
+ out.push({
3543
+ anchor,
3544
+ entry: { ...entry, class: "moved", movedTo },
3545
+ class: "moved"
3546
+ });
3547
+ continue;
3548
+ }
3549
+ const newText = await currentText(reader, anchor, resolvers);
3550
+ const old = options.withHistory === false ? { ok: false, reason: "unrecoverable" } : await readOldSource(repoRoot, anchor);
3551
+ const oldText = old.ok ? spanIn(old.source, anchor, resolvers) : void 0;
3552
+ const settled = newText !== void 0 && oldText !== void 0 && sameTokens(treeSitter, anchor.file, oldText, newText) ? "cosmetic" : entry.class ?? "changed";
3553
+ out.push({
3554
+ anchor,
3555
+ entry: { ...entry, class: settled },
3556
+ class: settled,
3557
+ ...newText !== void 0 ? { newText } : {},
3558
+ ...oldText !== void 0 ? { oldText } : {},
3559
+ ...old.ok ? { oldOrigin: old.origin } : {}
3560
+ });
3561
+ }
3562
+ return out;
3563
+ }
3564
+ function sameTokens(resolver, file, before, after) {
3565
+ if (before === after) return false;
3566
+ const left = resolver.normalize(before, file);
3567
+ const right = resolver.normalize(after, file);
3568
+ return left !== null && left === right;
3569
+ }
3570
+ async function currentText(reader, anchor, resolvers) {
3571
+ const read = await reader(anchor.file);
3572
+ if (!read.ok) return void 0;
3573
+ return spanIn(read.source, anchor, resolvers);
3574
+ }
3575
+ function spanIn(source, anchor, resolvers) {
3576
+ const outcome = resolveAnchorSpan(source, anchor, resolvers);
3577
+ return outcome.ok ? outcome.span.text : void 0;
3578
+ }
3579
+
3580
+ // src/drift/diff.ts
3581
+ var MAX_ANCHOR_DIFF_LINES = 200;
3582
+ var PACKET_DIFF_LINE_BUDGET = 200;
3583
+ var MIN_ANCHOR_DIFF_LINES = 12;
3584
+ function diffBudget(anchors) {
3585
+ if (anchors <= 0) return MAX_ANCHOR_DIFF_LINES;
3586
+ return Math.min(
3587
+ MAX_ANCHOR_DIFF_LINES,
3588
+ Math.max(
3589
+ MIN_ANCHOR_DIFF_LINES,
3590
+ Math.floor(PACKET_DIFF_LINE_BUDGET / anchors)
3591
+ )
3592
+ );
3593
+ }
3594
+ function unifiedDiff(before, after, options = {}) {
3595
+ const max = options.maxLines ?? MAX_ANCHOR_DIFF_LINES;
3596
+ const left = before.replace(/\r\n/g, "\n").split("\n");
3597
+ const right = after.replace(/\r\n/g, "\n").split("\n");
3598
+ const body = [];
3599
+ let added = 0;
3600
+ let removed = 0;
3601
+ for (const edit of edits(left, right)) {
3602
+ if (edit.kind === "same") body.push(` ${edit.line}`);
3603
+ else if (edit.kind === "remove") {
3604
+ body.push(`-${edit.line}`);
3605
+ removed += 1;
3606
+ } else {
3607
+ body.push(`+${edit.line}`);
3608
+ added += 1;
3609
+ }
3610
+ }
3611
+ const truncated = body.length > max;
3612
+ const shown = truncated ? body.slice(0, max) : body;
3613
+ const header = `@@ -1,${left.length} +1,${right.length} @@${options.oldLabel ? ` ${options.oldLabel} \u2192 ${options.newLabel ?? ""}`.trimEnd() : ""}`;
3614
+ const lines = [header, ...shown];
3615
+ if (truncated) lines.push(`\u2026 ${body.length - max} more diff lines`);
3616
+ return { text: lines.join("\n"), added, removed, truncated };
3617
+ }
3618
+ function edits(left, right) {
3619
+ const rows = left.length;
3620
+ const cols = right.length;
3621
+ const table2 = Array.from(
3622
+ { length: rows + 1 },
3623
+ () => new Array(cols + 1).fill(0)
3624
+ );
3625
+ for (let row2 = rows - 1; row2 >= 0; row2--) {
3626
+ for (let col2 = cols - 1; col2 >= 0; col2--) {
3627
+ table2[row2][col2] = left[row2] === right[col2] ? table2[row2 + 1][col2 + 1] + 1 : Math.max(
3628
+ table2[row2 + 1][col2],
3629
+ table2[row2][col2 + 1]
3630
+ );
3631
+ }
3632
+ }
3633
+ const out = [];
3634
+ let row = 0;
3635
+ let col = 0;
3636
+ while (row < rows && col < cols) {
3637
+ if (left[row] === right[col]) {
3638
+ out.push({ kind: "same", line: left[row] });
3639
+ row += 1;
3640
+ col += 1;
3641
+ } else if (table2[row + 1][col] >= table2[row][col + 1]) {
3642
+ out.push({ kind: "remove", line: left[row] });
3643
+ row += 1;
3644
+ } else {
3645
+ out.push({ kind: "add", line: right[col] });
3646
+ col += 1;
3647
+ }
3648
+ }
3649
+ for (; row < rows; row++)
3650
+ out.push({ kind: "remove", line: left[row] });
3651
+ for (; col < cols; col++)
3652
+ out.push({ kind: "add", line: right[col] });
3653
+ return out;
3654
+ }
3655
+
3656
+ // src/drift/packet.ts
3657
+ var PRESUMED_INVALID = [
3658
+ "fact",
3659
+ "constraint",
3660
+ "contract"
3661
+ ];
3662
+ var RATIONALE_SURVIVES = ["decision", "risk"];
3663
+ var DEFAULT_NOTES = {
3664
+ "presumed-invalidated": "the code this claim was taken from changed; presume it no longer holds until re-read",
3665
+ "rationale-may-survive": "the reasoning may outlive the code that implemented it; check whether it does",
3666
+ review: "re-read the record against the new code"
3667
+ };
3668
+ async function reassessPacket(repoRoot, record, entries, options = {}) {
3669
+ const classified = await classifyDrift(repoRoot, record, entries, {
3670
+ ...options.reader ? { reader: options.reader } : {},
3671
+ ...options.search ? { search: options.search } : {},
3672
+ withHistory: options.withDiff !== false
3673
+ });
3674
+ const open = classified.filter(
3675
+ (found) => found.class === "changed" || found.class === "gone"
3676
+ );
3677
+ if (!open.length) return { packet: null, classified };
3678
+ const budget = diffBudget(open.length);
3679
+ const anchors = open.map(
3680
+ (found) => anchorPacket(found, options.withDiff === true, budget)
3681
+ );
3682
+ const type = record.frontmatter.type;
3683
+ const fallback = isKbRecordType(type) ? PRESUMED_INVALID.includes(type) ? "presumed-invalidated" : RATIONALE_SURVIVES.includes(type) ? "rationale-may-survive" : "review" : "review";
3684
+ return {
3685
+ classified,
3686
+ packet: {
3687
+ conceptId: record.conceptId,
3688
+ title: record.frontmatter.title ?? null,
3689
+ type,
3690
+ standing: options.standing ?? "unsettled",
3691
+ why: record.frontmatter.description ?? null,
3692
+ claim: claimOf(record),
3693
+ anchors,
3694
+ impact: (options.impact?.impacted ?? []).map((entry) => ({
3695
+ conceptId: entry.conceptId,
3696
+ title: entry.title,
3697
+ standing: entry.standing,
3698
+ depth: entry.depth
3699
+ })),
3700
+ impactTruncated: options.impact?.truncated ?? false,
3701
+ default: fallback,
3702
+ defaultNote: DEFAULT_NOTES[fallback]
3703
+ }
3704
+ };
3705
+ }
3706
+ function anchorPacket(found, withDiff, maxLines) {
3707
+ const { entry } = found;
3708
+ const base2 = {
3709
+ file: entry.file,
3710
+ ...entry.symbol ? { symbol: entry.symbol } : {},
3711
+ class: found.class,
3712
+ ...entry.reason ? { reason: entry.reason } : {},
3713
+ storedHash: entry.storedHash,
3714
+ ...entry.currentHash ? { currentHash: entry.currentHash } : {},
3715
+ diffSize: entry.diffSize,
3716
+ ...entry.movedTo ? { movedTo: entry.movedTo } : {}
3717
+ };
3718
+ if (!withDiff) return base2;
3719
+ if (found.oldText === void 0 || !found.oldOrigin) {
3720
+ return { ...base2, diff: { status: "unrecoverable" } };
3721
+ }
3722
+ const rendered = unifiedDiff(found.oldText, found.newText ?? "", {
3723
+ maxLines
3724
+ });
3725
+ return {
3726
+ ...base2,
3727
+ diff: {
3728
+ status: "ok",
3729
+ source: found.oldOrigin.kind,
3730
+ ref: found.oldOrigin.ref,
3731
+ unified: rendered.text,
3732
+ added: rendered.added,
3733
+ removed: rendered.removed,
3734
+ truncated: rendered.truncated
3735
+ }
3736
+ };
3737
+ }
3738
+ function claimOf(record) {
3739
+ const type = record.frontmatter.type;
3740
+ const section = isKbRecordType(type) ? RECORD_TYPES[type].sections[0] : void 0;
3741
+ if (!section) return null;
3742
+ const lines = record.body.replace(/\r\n/g, "\n").split("\n");
3743
+ const start = lines.findIndex(
3744
+ (line) => line.trim().toLowerCase() === `## ${section}`.toLowerCase()
3745
+ );
3746
+ if (start < 0) return null;
3747
+ const rest = lines.slice(start + 1);
3748
+ const end = rest.findIndex((line) => line.startsWith("## "));
3749
+ const text = (end < 0 ? rest : rest.slice(0, end)).join("\n").trim();
3750
+ return text ? { section, text } : null;
3751
+ }
3241
3752
 
3242
3753
  // src/kb-edges.ts
3243
3754
  var KB_EDGE_KINDS = [
@@ -3487,18 +3998,18 @@ function expired(hits, now) {
3487
3998
  for (const hit of hits) {
3488
3999
  const raw = hit.record.frontmatter.stale_after;
3489
4000
  if (!raw) continue;
3490
- const at = Date.parse(raw);
3491
- if (Number.isNaN(at)) {
4001
+ const at2 = Date.parse(raw);
4002
+ if (Number.isNaN(at2)) {
3492
4003
  findings.push(
3493
4004
  finding(hit.record, `stale_after "${raw}" is not a readable date`)
3494
4005
  );
3495
4006
  continue;
3496
4007
  }
3497
- if (at < now.getTime()) {
4008
+ if (at2 < now.getTime()) {
3498
4009
  findings.push(
3499
4010
  finding(
3500
4011
  hit.record,
3501
- `stale since ${raw} (${daysBetween(at, now.getTime())} days ago)`
4012
+ `stale since ${raw} (${daysBetween(at2, now.getTime())} days ago)`
3502
4013
  )
3503
4014
  );
3504
4015
  }
@@ -3511,12 +4022,12 @@ function expiring(hits, now, withinDays) {
3511
4022
  for (const hit of hits) {
3512
4023
  const raw = hit.record.frontmatter.stale_after;
3513
4024
  if (!raw) continue;
3514
- const at = Date.parse(raw);
3515
- if (Number.isNaN(at) || at < now.getTime() || at > horizon) continue;
4025
+ const at2 = Date.parse(raw);
4026
+ if (Number.isNaN(at2) || at2 < now.getTime() || at2 > horizon) continue;
3516
4027
  findings.push(
3517
4028
  finding(
3518
4029
  hit.record,
3519
- `goes stale ${raw} (in ${daysBetween(now.getTime(), at)} days)`
4030
+ `goes stale ${raw} (in ${daysBetween(now.getTime(), at2)} days)`
3520
4031
  )
3521
4032
  );
3522
4033
  }
@@ -3686,13 +4197,16 @@ function anchorFindings(hits, kind, headline) {
3686
4197
  );
3687
4198
  }
3688
4199
  function describeAnchor(anchor) {
3689
- const at = anchor.symbol ? `${anchor.file}:${anchor.symbol}` : anchor.file;
3690
- if (anchor.reason) return `${at} (${anchor.reason})`;
4200
+ const at2 = anchor.symbol ? `${anchor.file}:${anchor.symbol}` : anchor.file;
4201
+ if (anchor.class === "gone") {
4202
+ return `${at2} gone${anchor.reason ? ` (${anchor.reason})` : ""}`;
4203
+ }
4204
+ if (anchor.reason) return `${at2} (${anchor.reason})`;
3691
4205
  if (anchor.remoteState === "drifted-on-default") {
3692
- return `${at} (matches ref, moved on the default branch)`;
4206
+ return `${at2} (matches ref, moved on the default branch)`;
3693
4207
  }
3694
- if (anchor.diffSize === null) return `${at} (changed, size unrecorded)`;
3695
- return anchor.diffSize === 0 ? `${at} (content changed, same line count)` : `${at} (${anchor.diffSize} line${anchor.diffSize === 1 ? "" : "s"} apart)`;
4208
+ if (anchor.diffSize === null) return `${at2} (changed, size unrecorded)`;
4209
+ return anchor.diffSize === 0 ? `${at2} (content changed, same line count)` : `${at2} (${anchor.diffSize} line${anchor.diffSize === 1 ? "" : "s"} apart)`;
3696
4210
  }
3697
4211
  function replaces(later, earlier) {
3698
4212
  return (later.frontmatter.strauss_supersedes ?? []).includes(earlier.conceptId) || earlier.frontmatter.strauss_superseded_by === later.conceptId;
@@ -3709,21 +4223,173 @@ function daysBetween(from, to) {
3709
4223
  return Math.max(0, Math.floor((to - from) / DAY_MS));
3710
4224
  }
3711
4225
  function ageInDays(record, now) {
3712
- const at = record.frontmatter.generated?.at;
3713
- if (!at) return null;
3714
- const written = Date.parse(at);
4226
+ const at2 = record.frontmatter.generated?.at;
4227
+ if (!at2) return null;
4228
+ const written = Date.parse(at2);
3715
4229
  if (Number.isNaN(written)) return null;
3716
4230
  return daysBetween(written, now.getTime());
3717
4231
  }
3718
4232
 
4233
+ // src/commands/reassess.ts
4234
+ var import_zod12 = require("zod");
4235
+ var reassessCommand = define({
4236
+ name: "reassess",
4237
+ tool: "kb_reassess",
4238
+ usage: "reassess <concept-id> [--repo-root <path>] [--with-diff]",
4239
+ description: "One drifted record, as something to judge: its claim, each anchor's drift class, the old-vs-new span diff, and the records that depend on it. Formatting-only drift is dropped. Empty when there is nothing to reassess. Writes: relocates moved anchors, keeping their hash; never verifies, supersedes, or changes standing.",
4240
+ input: import_zod12.z.object({
4241
+ bundlePath,
4242
+ conceptId,
4243
+ repoRoot: REPO_ROOT,
4244
+ withDiff: import_zod12.z.boolean().optional().describe(
4245
+ "Recover each anchor's committed span and render the diff. Reads git history."
4246
+ )
4247
+ }),
4248
+ fromArgv: (argv, path) => {
4249
+ const repoRoot = argvFlag(argv, "--repo-root");
4250
+ return {
4251
+ bundlePath: path,
4252
+ conceptId: argv[1],
4253
+ ...repoRoot !== void 0 ? { repoRoot } : {},
4254
+ ...argv.includes("--with-diff") ? { withDiff: true } : {}
4255
+ };
4256
+ },
4257
+ run: async ({ store, actor }, { bundlePath: path, conceptId: id, repoRoot, withDiff }) => {
4258
+ const root = repoRoot ?? process.cwd();
4259
+ const bundle = await store.list(path);
4260
+ const record = bundle.find((entry) => entry.conceptId === id);
4261
+ if (!record) throw new KbRecordNotFoundError(id);
4262
+ const drift = await store.detectDrift([record], repoRoot);
4263
+ const entries = drift?.get(id) ?? [];
4264
+ if (!entries.some((entry) => entry.state !== "match")) {
4265
+ return { conceptId: id, packet: null, rebaselined: [], cosmetic: 0 };
4266
+ }
4267
+ const standing = adjudicate(bundle, bundle).find(
4268
+ (hit) => hit.record.conceptId === id
4269
+ )?.standing;
4270
+ const impact2 = await store.impact(path, id);
4271
+ const { packet, classified } = await reassessPacket(root, record, entries, {
4272
+ ...withDiff ? { withDiff: true } : {},
4273
+ impact: impact2,
4274
+ ...standing ? { standing } : {}
4275
+ });
4276
+ const moves = classified.filter((found) => found.class === "moved");
4277
+ let frozen = false;
4278
+ const rebaselined = [];
4279
+ if (moves.length) {
4280
+ const relocated = /* @__PURE__ */ new Map();
4281
+ for (const found of moves) {
4282
+ const to = found.entry.movedTo;
4283
+ if (!to) continue;
4284
+ relocated.set(found.anchor, {
4285
+ ...found.anchor,
4286
+ file: to.file,
4287
+ ...to.symbol ? { symbol: to.symbol } : {}
4288
+ });
4289
+ rebaselined.push({
4290
+ file: found.anchor.file,
4291
+ ...found.anchor.symbol ? { symbol: found.anchor.symbol } : {},
4292
+ toFile: to.file,
4293
+ ...to.symbol ? { toSymbol: to.symbol } : {}
4294
+ });
4295
+ }
4296
+ try {
4297
+ await assertBaseNotFrozen(process.cwd(), path);
4298
+ } catch (error) {
4299
+ if (!(error instanceof KbBaseFrozenError)) throw error;
4300
+ frozen = true;
4301
+ }
4302
+ if (!frozen) {
4303
+ await store.updateAnchors(
4304
+ path,
4305
+ id,
4306
+ (record.frontmatter.strauss_anchors ?? []).map(
4307
+ (anchor) => relocated.get(anchor) ?? anchor
4308
+ ),
4309
+ actor
4310
+ );
4311
+ }
4312
+ }
4313
+ return {
4314
+ conceptId: id,
4315
+ packet,
4316
+ rebaselined: frozen ? [] : rebaselined,
4317
+ cosmetic: classified.filter((found) => found.class === "cosmetic").length,
4318
+ ...frozen ? {
4319
+ frozen: true,
4320
+ note: "base is frozen: nothing was rebaselined"
4321
+ } : {}
4322
+ };
4323
+ },
4324
+ render: (result) => renderReassess(result)
4325
+ });
4326
+ function renderReassess(result) {
4327
+ const lines = [];
4328
+ for (const move of result.rebaselined) {
4329
+ lines.push(
4330
+ `rebaselined: ${at(move.file, move.symbol)} \u2192 ${at(move.toFile, move.toSymbol)} (same code, new address)`
4331
+ );
4332
+ }
4333
+ if (result.cosmetic) {
4334
+ lines.push(
4335
+ `${result.cosmetic} anchor${result.cosmetic === 1 ? "" : "s"} changed formatting only.`
4336
+ );
4337
+ }
4338
+ if (result.note) lines.push(result.note);
4339
+ const packet = result.packet;
4340
+ if (!packet) {
4341
+ lines.push(`${result.conceptId}: nothing to reassess.`);
4342
+ return lines.join("\n");
4343
+ }
4344
+ lines.push(
4345
+ "",
4346
+ `# ${packet.conceptId}${packet.title ? ` \u2014 ${packet.title}` : ""}`,
4347
+ `type: ${packet.type} standing: ${packet.standing}`,
4348
+ ...packet.why ? [`why: ${packet.why}`] : [],
4349
+ ...packet.claim ? ["", `## ${packet.claim.section}`, packet.claim.text] : [],
4350
+ "",
4351
+ `## Anchors (${packet.anchors.length})`
4352
+ );
4353
+ for (const anchor of packet.anchors) {
4354
+ lines.push(
4355
+ `- ${at(anchor.file, anchor.symbol)} \u2014 ${anchor.class}${anchor.reason ? ` (${anchor.reason})` : ""}`
4356
+ );
4357
+ if (!anchor.diff) continue;
4358
+ if (anchor.diff.status === "unrecoverable") {
4359
+ lines.push(
4360
+ " diff: unrecoverable \u2014 no committed span to compare against"
4361
+ );
4362
+ continue;
4363
+ }
4364
+ lines.push(
4365
+ ` diff vs ${anchor.diff.ref} (${anchor.diff.source}): +${anchor.diff.added} \u2212${anchor.diff.removed}`,
4366
+ ...anchor.diff.unified.split("\n").map((line) => ` ${line}`)
4367
+ );
4368
+ }
4369
+ if (packet.impact.length) {
4370
+ lines.push("", `## Impact (${packet.impact.length})`);
4371
+ for (const entry of packet.impact) {
4372
+ lines.push(
4373
+ `- ${entry.conceptId} [${entry.standing}]${entry.title ? ` \u2014 ${entry.title}` : ""}`
4374
+ );
4375
+ }
4376
+ if (packet.impactTruncated) lines.push("- \u2026 walk truncated");
4377
+ }
4378
+ lines.push("", `Default: ${packet.default} \u2014 ${packet.defaultNote}.`);
4379
+ return lines.join("\n");
4380
+ }
4381
+ function at(file, symbol) {
4382
+ return symbol ? `${file}:${symbol}` : file;
4383
+ }
4384
+
3719
4385
  // src/commands/doctor.ts
3720
- var days = (what, fallback) => import_zod12.z.number().int().positive().optional().describe(`${what} Defaults to ${fallback}.`);
4386
+ var days = (what, fallback) => import_zod13.z.number().int().positive().optional().describe(`${what} Defaults to ${fallback}.`);
3721
4387
  var doctorCommand = define({
3722
4388
  name: "doctor",
3723
4389
  tool: "kb_doctor",
3724
- usage: "doctor [--expiring-days N] [--unverified-days N] [--aging-days N] [--repo-root PATH] [--offline] [--strict]",
3725
- description: "Read-only health sweep: expired, expiring, unverified, aging, orphaned, broken-supersession, superseded-but-cited, drifted and unchecked anchors. Every group is reported even when empty; nothing is written or re-stamped. Use it when picking up a base you have not touched in a while; kb_validate only checks that pointers between records agree.",
3726
- input: import_zod12.z.object({
4390
+ usage: "doctor [--expiring-days N] [--unverified-days N] [--aging-days N] [--repo-root PATH] [--offline] [--strict] [--drifted [--with-diff]]",
4391
+ description: "Read-only health sweep: expired, expiring, unverified, aging, orphaned, broken-supersession, superseded-but-cited, drifted and unchecked anchors. Every group is reported even when empty; nothing is written or re-stamped. `drifted` narrows it to a reassessment packet per drifted record, `with_diff` adding each anchor's old-vs-new span.",
4392
+ input: import_zod13.z.object({
3727
4393
  bundlePath,
3728
4394
  repoRoot: REPO_ROOT,
3729
4395
  expiringDays: days(
@@ -3738,11 +4404,17 @@ var doctorCommand = define({
3738
4404
  "How long a record may stay `open` or `proposed` before `aging` reports it, in days.",
3739
4405
  DEFAULT_AGING_DAYS
3740
4406
  ),
3741
- offline: import_zod12.z.boolean().optional().describe(
4407
+ offline: import_zod13.z.boolean().optional().describe(
3742
4408
  "Read foreign anchors from the local repo cache only, never fetching."
3743
4409
  ),
3744
- strict: import_zod12.z.boolean().optional().describe(
4410
+ strict: import_zod13.z.boolean().optional().describe(
3745
4411
  "Turn an expired record into a non-zero exit for the CLI. No effect on the report itself."
4412
+ ),
4413
+ drifted: import_zod13.z.boolean().optional().describe(
4414
+ "Report only drift, as a reassessment packet per record: claim, per-anchor class, and what depends on it."
4415
+ ),
4416
+ withDiff: import_zod13.z.boolean().optional().describe(
4417
+ "With `drifted`: recover each anchor's committed span and render the old-vs-new diff. Reads git history."
3746
4418
  )
3747
4419
  }),
3748
4420
  // Presence, not truthiness: `--expiring-days ""` is a caller who meant
@@ -3761,7 +4433,9 @@ var doctorCommand = define({
3761
4433
  ...unverified2 !== void 0 ? { unverifiedDays: Number(unverified2) } : {},
3762
4434
  ...agingDays !== void 0 ? { agingDays: Number(agingDays) } : {},
3763
4435
  ...argv.includes("--offline") ? { offline: true } : {},
3764
- ...argv.includes("--strict") ? { strict: true } : {}
4436
+ ...argv.includes("--strict") ? { strict: true } : {},
4437
+ ...argv.includes("--drifted") ? { drifted: true } : {},
4438
+ ...argv.includes("--with-diff") ? { withDiff: true } : {}
3765
4439
  };
3766
4440
  },
3767
4441
  run: async ({ store, now }, {
@@ -3770,7 +4444,9 @@ var doctorCommand = define({
3770
4444
  unverifiedDays,
3771
4445
  agingDays,
3772
4446
  repoRoot,
3773
- offline
4447
+ offline,
4448
+ drifted: drifted2,
4449
+ withDiff
3774
4450
  }) => {
3775
4451
  const checkedAt = now();
3776
4452
  const records = await store.list(path);
@@ -3785,10 +4461,51 @@ var doctorCommand = define({
3785
4461
  now: new Date(checkedAt)
3786
4462
  });
3787
4463
  const hints = grammarHints();
4464
+ if (!drifted2) {
4465
+ return {
4466
+ bundlePath: path,
4467
+ checkedAt,
4468
+ ...report,
4469
+ ...hints.length ? { hints } : {}
4470
+ };
4471
+ }
4472
+ const standings = new Map(
4473
+ adjudicate(records, records, new Date(checkedAt)).map((hit) => [
4474
+ hit.record.conceptId,
4475
+ hit.standing
4476
+ ])
4477
+ );
4478
+ const packets = [];
4479
+ const rebaselinable = [];
4480
+ const search = movedSearch(repoRoot ?? process.cwd());
4481
+ for (const found of report.groups.find((g) => g.check === "drifted")?.findings ?? []) {
4482
+ const record = records.find(
4483
+ (entry) => entry.conceptId === found.conceptId
4484
+ );
4485
+ if (!record) continue;
4486
+ const standing = standings.get(record.conceptId);
4487
+ const built = await reassessPacket(
4488
+ repoRoot ?? process.cwd(),
4489
+ record,
4490
+ anchorDrift?.get(record.conceptId) ?? [],
4491
+ {
4492
+ ...withDiff ? { withDiff: true } : {},
4493
+ impact: await store.impact(path, record.conceptId),
4494
+ ...standing ? { standing } : {},
4495
+ search
4496
+ }
4497
+ );
4498
+ if (built.packet) packets.push(built.packet);
4499
+ if (built.classified.some((entry) => entry.class === "moved")) {
4500
+ rebaselinable.push(record.conceptId);
4501
+ }
4502
+ }
3788
4503
  return {
3789
4504
  bundlePath: path,
3790
4505
  checkedAt,
3791
4506
  ...report,
4507
+ packets,
4508
+ rebaselinable,
3792
4509
  ...hints.length ? { hints } : {}
3793
4510
  };
3794
4511
  },
@@ -3802,6 +4519,7 @@ var doctorCommand = define({
3802
4519
  failsWhen: (result, input) => input.strict === true && result.counts.expired > 0
3803
4520
  });
3804
4521
  function render2(result) {
4522
+ if (result.packets) return renderPackets(result);
3805
4523
  const { thresholds } = result;
3806
4524
  const lines = [
3807
4525
  `# KB Doctor \u2014 ${result.bundlePath}`,
@@ -3835,21 +4553,45 @@ function render2(result) {
3835
4553
  );
3836
4554
  return lines.join("\n");
3837
4555
  }
4556
+ function renderPackets(result) {
4557
+ const packets = result.packets ?? [];
4558
+ const lines = [
4559
+ `# KB Drift \u2014 ${result.bundlePath}`,
4560
+ `checked: ${result.checkedAt}`,
4561
+ `${packets.length} record${packets.length === 1 ? "" : "s"} need a reading; ${result.counts.drifted} drifted in all.`
4562
+ ];
4563
+ if (result.rebaselinable?.length) {
4564
+ lines.push(
4565
+ `moved, rebaseline with \`kb_reassess\`: ${result.rebaselinable.join(", ")}`
4566
+ );
4567
+ }
4568
+ for (const packet of packets) {
4569
+ lines.push(
4570
+ renderReassess({
4571
+ conceptId: packet.conceptId,
4572
+ packet,
4573
+ rebaselined: [],
4574
+ cosmetic: 0
4575
+ })
4576
+ );
4577
+ }
4578
+ return lines.join("\n");
4579
+ }
3838
4580
 
3839
4581
  // src/commands/impact.ts
3840
- var import_zod13 = require("zod");
4582
+ var import_zod14 = require("zod");
3841
4583
  var impactCommand = define({
3842
4584
  name: "impact",
3843
4585
  tool: "kb_impact",
3844
4586
  usage: "impact <concept-id> [--depth N] [--rels a,b]",
3845
4587
  description: "What breaks if this record changes: its transitive set of dependants, each with its standing. Each rel declares which of its ends depends on the other, and the walk follows each rel in its own direction. Naming `related_to` or an unknown rel in `rels` is an error. kb_backlinks gives one flat hop.",
3846
- input: import_zod13.z.object({
4588
+ input: import_zod14.z.object({
3847
4589
  bundlePath,
3848
4590
  conceptId,
3849
- depth: import_zod13.z.number().int().positive().optional().describe(
4591
+ depth: import_zod14.z.number().int().positive().optional().describe(
3850
4592
  "Hops out from the record. Unbounded when omitted; a walk this cuts reports truncated: true."
3851
4593
  ),
3852
- rels: import_zod13.z.array(import_zod13.z.enum(KB_CAUSAL_LINK_RELS)).optional().describe(
4594
+ rels: import_zod14.z.array(import_zod14.z.enum(KB_CAUSAL_LINK_RELS)).optional().describe(
3853
4595
  "Narrow which rels the walk follows. Defaults to every rel that carries a dependence \u2014 all but related_to."
3854
4596
  )
3855
4597
  }),
@@ -3870,13 +4612,13 @@ var impactCommand = define({
3870
4612
  });
3871
4613
 
3872
4614
  // src/commands/list.ts
3873
- var import_zod14 = require("zod");
4615
+ var import_zod15 = require("zod");
3874
4616
  var listCommand = define({
3875
4617
  name: "list",
3876
4618
  tool: "kb_list",
3877
4619
  usage: "list [type]",
3878
4620
  description: "Every record, optionally one type. For enumerating; use kb_query for a question.",
3879
- input: import_zod14.z.object({ bundlePath, type: import_zod14.z.enum(KB_RECORD_TYPES).optional() }),
4621
+ input: import_zod15.z.object({ bundlePath, type: import_zod15.z.enum(KB_RECORD_TYPES).optional() }),
3880
4622
  fromArgv: (argv, path) => ({ bundlePath: path, type: argv[1] }),
3881
4623
  run: async ({ store }, { bundlePath: path, type }) => (await store.list(path, type)).map((record) => ({
3882
4624
  conceptId: record.conceptId,
@@ -3888,17 +4630,17 @@ var listCommand = define({
3888
4630
  });
3889
4631
 
3890
4632
  // src/commands/load.ts
3891
- var import_zod15 = require("zod");
4633
+ var import_zod16 = require("zod");
3892
4634
  var loadCommand = define({
3893
4635
  name: "load",
3894
4636
  tool: "kb_load",
3895
4637
  usage: "load [type] [--budget N | --all] [--repo-root PATH]",
3896
4638
  description: "Load the whole base, each record with its standing \u2014 call it first, at the point of use, since compaction drops it. Superseded records arrive as stubs; kb_trace has the history. Over budget it refuses: kb_catalog, then kb_pack, or narrow with `type`; `all` bypasses. Never read record files directly \u2014 only kb_* tools resolve supersession. `digest` stamps the base's content, so hooks know when to reload.",
3897
- input: import_zod15.z.object({
4639
+ input: import_zod16.z.object({
3898
4640
  bundlePath,
3899
- type: import_zod15.z.enum(KB_RECORD_TYPES).optional(),
3900
- budgetTokens: import_zod15.z.number().int().positive().optional().describe("Approximate token ceiling. Defaults to 25000."),
3901
- all: import_zod15.z.boolean().optional().describe(
4641
+ type: import_zod16.z.enum(KB_RECORD_TYPES).optional(),
4642
+ budgetTokens: import_zod16.z.number().int().positive().optional().describe("Approximate token ceiling. Defaults to 25000."),
4643
+ all: import_zod16.z.boolean().optional().describe(
3902
4644
  "Loads the entire base regardless of size, bypassing the token budget; mutually exclusive with budgetTokens."
3903
4645
  ),
3904
4646
  repoRoot: REPO_ROOT
@@ -3940,25 +4682,25 @@ var loadCommand = define({
3940
4682
  });
3941
4683
 
3942
4684
  // src/commands/log.ts
3943
- var import_zod16 = require("zod");
4685
+ var import_zod17 = require("zod");
3944
4686
  var logCommand = define({
3945
4687
  name: "log",
3946
4688
  tool: "kb_log",
3947
4689
  usage: "log",
3948
4690
  description: "Who touched what, and when. Append-only; malformed lines are reported, never repaired.",
3949
- input: import_zod16.z.object({ bundlePath }),
4691
+ input: import_zod17.z.object({ bundlePath }),
3950
4692
  fromArgv: (_argv, path) => ({ bundlePath: path }),
3951
4693
  run: ({ store }, { bundlePath: path }) => store.readLog(path)
3952
4694
  });
3953
4695
 
3954
4696
  // src/commands/no-decision.ts
3955
- var import_zod17 = require("zod");
4697
+ var import_zod18 = require("zod");
3956
4698
  var noDecisionCommand = define({
3957
4699
  name: "no-decision",
3958
4700
  tool: "kb_no_decision",
3959
4701
  usage: "no-decision <reason...>",
3960
4702
  description: "Record in one sentence that a piece of work had nothing to decide. Idempotent.",
3961
- input: import_zod17.z.object({ bundlePath, reason: import_zod17.z.string().min(1) }),
4703
+ input: import_zod18.z.object({ bundlePath, reason: import_zod18.z.string().min(1) }),
3962
4704
  fromArgv: (argv, path) => ({
3963
4705
  bundlePath: path,
3964
4706
  reason: argv.slice(1).join(" ").trim()
@@ -3975,20 +4717,20 @@ var noDecisionCommand = define({
3975
4717
  });
3976
4718
 
3977
4719
  // src/commands/pack.ts
3978
- var import_zod18 = require("zod");
4720
+ var import_zod19 = require("zod");
3979
4721
  var packCommand = define({
3980
4722
  name: "pack",
3981
4723
  tool: "kb_pack",
3982
4724
  usage: "pack <conceptId> [--hops N] [--max-nodes N] [--budget N]",
3983
4725
  description: "Bounded neighbourhood around one record: within `hops`, ranked, cut to `maxNodes`, with every cut record named under Excluded. Use when the base is over kb_load's budget and the work centres on a record you can name. Refuses over budget rather than truncating. Everything below the header is byte-stable across runs. Resolves supersession like kb_load.",
3984
- input: import_zod18.z.object({
4726
+ input: import_zod19.z.object({
3985
4727
  bundlePath,
3986
4728
  conceptId,
3987
- hops: import_zod18.z.number().int().positive().optional().describe("How far from the root the walk may reach. Defaults to 2."),
3988
- maxNodes: import_zod18.z.number().int().positive().optional().describe(
4729
+ hops: import_zod19.z.number().int().positive().optional().describe("How far from the root the walk may reach. Defaults to 2."),
4730
+ maxNodes: import_zod19.z.number().int().positive().optional().describe(
3989
4731
  "How many records the pack may hold, root included. Defaults to 20."
3990
4732
  ),
3991
- budgetTokens: import_zod18.z.number().int().positive().optional().describe(
4733
+ budgetTokens: import_zod19.z.number().int().positive().optional().describe(
3992
4734
  "Approximate token ceiling over what is actually emitted. Defaults to 25000."
3993
4735
  )
3994
4736
  }),
@@ -4013,12 +4755,12 @@ var packCommand = define({
4013
4755
  return render3(result, path, now());
4014
4756
  }
4015
4757
  });
4016
- function render3(result, bundle, at) {
4758
+ function render3(result, bundle, at2) {
4017
4759
  const lines = [
4018
4760
  `# KB Pack \u2014 ${result.root}`,
4019
4761
  `bundle: ${bundle}`,
4020
4762
  `budget: ~${result.tokensLoaded} of ${result.budgetTokens} tokens, ${result.recordCount} records`,
4021
- `packed: ${at}`,
4763
+ `packed: ${at2}`,
4022
4764
  "",
4023
4765
  `## Records (${result.records.length})`
4024
4766
  ];
@@ -4075,22 +4817,22 @@ function warningLabel(warning) {
4075
4817
  }
4076
4818
 
4077
4819
  // src/commands/pin.ts
4078
- var import_zod19 = require("zod");
4820
+ var import_zod20 = require("zod");
4079
4821
  var pinCommand = define({
4080
4822
  name: "pin",
4081
4823
  tool: "kb_pin",
4082
4824
  usage: "pin [bundle-path] [--mode full|index] [--profiles a,b] [--local|--user] [--frozen|--unfreeze]",
4083
4825
  description: "Pin a base into a workspace manifest so kb_context surfaces it. Layers, nearest wins: project `.strauss/kb-pins.json` (default), `--local` (personal, gitignored), `--user` (`~/.strauss`). Idempotent; `--mode full|index`, `--profiles`, `--frozen`/`--unfreeze` update only those fields. A path with no records pins with a warning. Never touches the base itself.",
4084
- input: import_zod19.z.object({
4826
+ input: import_zod20.z.object({
4085
4827
  bundlePath,
4086
- mode: import_zod19.z.enum(["full", "index"]).optional().describe(
4828
+ mode: import_zod20.z.enum(["full", "index"]).optional().describe(
4087
4829
  "full: always emit this base's records whole (still under the block budget); index: never upgrade. Absent: the profile's full-under threshold decides."
4088
4830
  ),
4089
- profiles: import_zod19.z.array(import_zod19.z.string()).optional().describe("Context profiles this pin surfaces in. Absent: all of them."),
4090
- layer: import_zod19.z.enum(["project", "local", "user"]).optional().describe(
4831
+ profiles: import_zod20.z.array(import_zod20.z.string()).optional().describe("Context profiles this pin surfaces in. Absent: all of them."),
4832
+ layer: import_zod20.z.enum(["project", "local", "user"]).optional().describe(
4091
4833
  "Which manifest to write: project (committed, default), local (personal, gitignored), user (~/.strauss, every workspace)."
4092
4834
  ),
4093
- frozen: import_zod19.z.boolean().optional().describe(
4835
+ frozen: import_zod20.z.boolean().optional().describe(
4094
4836
  "true: the base is concluded \u2014 writes against it refuse while pinned. false: lift a freeze."
4095
4837
  )
4096
4838
  }),
@@ -4119,29 +4861,29 @@ var pinCommand = define({
4119
4861
  });
4120
4862
 
4121
4863
  // src/commands/pins.ts
4122
- var import_zod20 = require("zod");
4864
+ var import_zod21 = require("zod");
4123
4865
  var pinsCommand = define({
4124
4866
  name: "pins",
4125
4867
  tool: "kb_pins",
4126
4868
  usage: "pins",
4127
4869
  description: "Every pinned base across the manifest layers, with its layer and whether it resolves to records. Takes no bundlePath.",
4128
- input: import_zod20.z.object({}),
4870
+ input: import_zod21.z.object({}),
4129
4871
  fromArgv: () => ({}),
4130
4872
  run: ({ store }) => listPins(store, process.cwd())
4131
4873
  });
4132
4874
 
4133
4875
  // src/commands/query.ts
4134
- var import_zod21 = require("zod");
4876
+ var import_zod22 = require("zod");
4135
4877
  var queryCommand = define({
4136
4878
  name: "query",
4137
4879
  tool: "kb_query",
4138
4880
  usage: "query <text...> [--repo-root PATH]",
4139
4881
  description: "Search; every hit carries its standing. Flagged, never filtered: a superseded hit returns with its replacement, a rejected one is marked. Prefer kb_load when the base fits its budget \u2014 a full read beats search. Results are volatile: place them at the tail, not the cached prefix. Never read record files directly.",
4140
- input: import_zod21.z.object({
4882
+ input: import_zod22.z.object({
4141
4883
  bundlePath,
4142
- text: import_zod21.z.string().optional(),
4143
- type: import_zod21.z.enum(KB_RECORD_TYPES).optional(),
4144
- includeNonCurrent: import_zod21.z.boolean().optional(),
4884
+ text: import_zod22.z.string().optional(),
4885
+ type: import_zod22.z.enum(KB_RECORD_TYPES).optional(),
4886
+ includeNonCurrent: import_zod22.z.boolean().optional(),
4145
4887
  repoRoot: REPO_ROOT
4146
4888
  }),
4147
4889
  // `--repo-root` is a flag, so its value must not fall into the search text.
@@ -4173,27 +4915,27 @@ var queryCommand = define({
4173
4915
  });
4174
4916
 
4175
4917
  // src/commands/read-index.ts
4176
- var import_zod22 = require("zod");
4918
+ var import_zod23 = require("zod");
4177
4919
  var readIndexCommand = define({
4178
4920
  name: "index",
4179
4921
  tool: "kb_index",
4180
4922
  usage: "index",
4181
4923
  description: "The index \u2014 title, type, status, description per record \u2014 rebuilt if stale. Cheapest re-orientation after compaction: call it (or kb_context) first, then kb_load or fetch by id.",
4182
- input: import_zod22.z.object({ bundlePath }),
4924
+ input: import_zod23.z.object({ bundlePath }),
4183
4925
  fromArgv: (_argv, path) => ({ bundlePath: path }),
4184
4926
  run: ({ store }, { bundlePath: path }) => store.readIndex(path)
4185
4927
  });
4186
4928
 
4187
4929
  // src/commands/schema.ts
4188
- var import_zod25 = require("zod");
4930
+ var import_zod26 = require("zod");
4189
4931
 
4190
4932
  // src/json-schema.ts
4191
- var import_zod24 = require("zod");
4933
+ var import_zod25 = require("zod");
4192
4934
 
4193
4935
  // src/kb-log.ts
4194
- var import_zod23 = require("zod");
4936
+ var import_zod24 = require("zod");
4195
4937
  var LOG_FILE = "log.jsonl";
4196
- var kbLogEntrySchema = import_zod23.z.object({
4938
+ var kbLogEntrySchema = import_zod24.z.object({
4197
4939
  // Validated, not just `min(1)`: `at` is a sort key (see `parseLog`
4198
4940
  // below), and a value that isn't actually chronological — a Unix
4199
4941
  // timestamp, a human-typed date, garbage — would sort wrong without
@@ -4202,12 +4944,12 @@ var kbLogEntrySchema = import_zod23.z.object({
4202
4944
  // and rejects everything else, including a non-`Z` offset — so a
4203
4945
  // malformed `at` is reported the same way a malformed line already is,
4204
4946
  // rather than silently sorting into the wrong place.
4205
- at: import_zod23.z.iso.datetime(),
4206
- by: import_zod23.z.string().min(1),
4207
- operation: import_zod23.z.string().min(1),
4208
- conceptId: import_zod23.z.string().min(1),
4947
+ at: import_zod24.z.iso.datetime(),
4948
+ by: import_zod24.z.string().min(1),
4949
+ operation: import_zod24.z.string().min(1),
4950
+ conceptId: import_zod24.z.string().min(1),
4209
4951
  /** Second concept id, where the operation relates two — supersession. */
4210
- target: import_zod23.z.string().min(1).optional()
4952
+ target: import_zod24.z.string().min(1).optional()
4211
4953
  }).strict();
4212
4954
  function renderLogEntry(entry) {
4213
4955
  return `${JSON.stringify(kbLogEntrySchema.parse(entry))}
@@ -4245,11 +4987,11 @@ function parseLog(raw) {
4245
4987
  // src/json-schema.ts
4246
4988
  function kbJsonSchemas() {
4247
4989
  return {
4248
- recordFrontmatter: import_zod24.z.toJSONSchema(kbRecordFrontmatterSchema, {
4990
+ recordFrontmatter: import_zod25.z.toJSONSchema(kbRecordFrontmatterSchema, {
4249
4991
  io: "input"
4250
4992
  }),
4251
- composeInput: import_zod24.z.toJSONSchema(composeInputSchema, { io: "input" }),
4252
- logEntry: import_zod24.z.toJSONSchema(kbLogEntrySchema, { io: "input" })
4993
+ composeInput: import_zod25.z.toJSONSchema(composeInputSchema, { io: "input" }),
4994
+ logEntry: import_zod25.z.toJSONSchema(kbLogEntrySchema, { io: "input" })
4253
4995
  };
4254
4996
  }
4255
4997
 
@@ -4259,25 +5001,25 @@ var schemaCommand = define({
4259
5001
  tool: "kb_schema",
4260
5002
  usage: "schema",
4261
5003
  description: "JSON Schema for frontmatter, write input, and log entries, generated from the enforcing code.",
4262
- input: import_zod25.z.object({}),
5004
+ input: import_zod26.z.object({}),
4263
5005
  fromArgv: () => ({}),
4264
5006
  run: () => Promise.resolve(kbJsonSchemas())
4265
5007
  });
4266
5008
 
4267
5009
  // src/commands/stamp.ts
4268
- var import_promises7 = require("fs/promises");
4269
- var import_zod26 = require("zod");
5010
+ var import_promises8 = require("fs/promises");
5011
+ var import_zod27 = require("zod");
4270
5012
  var DIGEST = /^[0-9a-f]{64}$/;
4271
5013
  var stampCommand = define({
4272
5014
  name: "stamp",
4273
5015
  tool: "kb_stamp",
4274
5016
  usage: "stamp [--bundle PATH] [--since DIGEST|FILE]",
4275
- description: "Content stamp of a base \u2014 `load`'s digest, record counts, per-record digests \u2014 without any bodies. Takes no bundlePath to stamp every pinned base. With `since`, reports only the bases that moved, naming the changed ids when the baseline is a prior stamp; silent when nothing changed. Reads, never writes.",
4276
- input: import_zod26.z.object({
4277
- bundlePath: import_zod26.z.string().min(1).optional().describe(
5017
+ description: "Content stamp of a base \u2014 `load`'s digest, record counts, per-record digests, how many records have drifted anchors \u2014 without any bodies. Takes no bundlePath to stamp every pinned base. With `since`, reports only the bases that moved, naming the changed ids. Reads, never writes.",
5018
+ input: import_zod27.z.object({
5019
+ bundlePath: import_zod27.z.string().min(1).optional().describe(
4278
5020
  "Absolute path to one knowledge base. Omit to stamp every pinned base."
4279
5021
  ),
4280
- since: import_zod26.z.string().min(1).optional().describe(
5022
+ since: import_zod27.z.string().min(1).optional().describe(
4281
5023
  "Prior digest, or path to a prior `stamp --json`; only moved bases return, with changed ids when the baseline is a file."
4282
5024
  )
4283
5025
  }),
@@ -4316,7 +5058,7 @@ var stampCommand = define({
4316
5058
  return reports;
4317
5059
  },
4318
5060
  render: (result) => result.map((report) => {
4319
- const counts = `${report.recordCount} record(s), ${report.superseded} superseded`;
5061
+ const counts = `${report.recordCount} record(s), ${report.superseded} superseded${report.drifted ? `, ${report.drifted} drifted` : ""}`;
4320
5062
  const head = `${report.path} ${report.digest} ${counts}${report.newestAt ? ` newest ${report.newestAt}` : ""}`;
4321
5063
  return report.changed?.length ? `${head}
4322
5064
  changed: ${report.changed.join(", ")}` : head;
@@ -4339,7 +5081,7 @@ async function readBaseline(since) {
4339
5081
  if (DIGEST.test(since)) return { digest: since, byPath: /* @__PURE__ */ new Map() };
4340
5082
  let parsed;
4341
5083
  try {
4342
- parsed = JSON.parse(await (0, import_promises7.readFile)(since, "utf8"));
5084
+ parsed = JSON.parse(await (0, import_promises8.readFile)(since, "utf8"));
4343
5085
  } catch {
4344
5086
  throw new KbStampBaselineError(since);
4345
5087
  }
@@ -4363,16 +5105,16 @@ async function readBaseline(since) {
4363
5105
  }
4364
5106
 
4365
5107
  // src/commands/status.ts
4366
- var import_zod27 = require("zod");
5108
+ var import_zod28 = require("zod");
4367
5109
  var statusCommand = define({
4368
5110
  name: "status",
4369
5111
  tool: "kb_status",
4370
5112
  usage: "status <concept-id> <status>",
4371
5113
  description: "Move a record's status. Compare-and-swap: a concurrent change fails instead of being overwritten.",
4372
- input: import_zod27.z.object({
5114
+ input: import_zod28.z.object({
4373
5115
  bundlePath,
4374
5116
  conceptId,
4375
- status: import_zod27.z.enum(KB_RECORD_STATUSES)
5117
+ status: import_zod28.z.enum(KB_RECORD_STATUSES)
4376
5118
  }),
4377
5119
  fromArgv: (argv, path) => ({
4378
5120
  bundlePath: path,
@@ -4387,13 +5129,13 @@ var statusCommand = define({
4387
5129
  });
4388
5130
 
4389
5131
  // src/commands/supersede.ts
4390
- var import_zod28 = require("zod");
5132
+ var import_zod29 = require("zod");
4391
5133
  var supersedeCommand = define({
4392
5134
  name: "supersede",
4393
5135
  tool: "kb_supersede",
4394
5136
  usage: "supersede <concept-id> <replacement-id>",
4395
5137
  description: "Mark a record superseded by another, linked in both directions. Use instead of editing a record whose meaning changed.",
4396
- input: import_zod28.z.object({ bundlePath, conceptId, replacementId: conceptId }),
5138
+ input: import_zod29.z.object({ bundlePath, conceptId, replacementId: conceptId }),
4397
5139
  fromArgv: (argv, path) => ({
4398
5140
  bundlePath: path,
4399
5141
  conceptId: argv[1],
@@ -4407,16 +5149,16 @@ var supersedeCommand = define({
4407
5149
  });
4408
5150
 
4409
5151
  // src/commands/sync-instructions.ts
4410
- var import_zod29 = require("zod");
5152
+ var import_zod30 = require("zod");
4411
5153
  var syncInstructionsCommand = define({
4412
5154
  name: "sync-instructions",
4413
5155
  usage: "sync-instructions <file> [--profile NAME] [--budget N] [--full-under N]",
4414
5156
  description: "CLI-only: plant the kb_context block between sentinel comments in AGENTS.md or CLAUDE.md, idempotently.",
4415
- input: import_zod29.z.object({
4416
- file: import_zod29.z.string().min(1).describe("The instruction file to edit in place."),
4417
- budgetTokens: import_zod29.z.number().int().positive().optional(),
4418
- fullUnderTokens: import_zod29.z.number().int().positive().optional(),
4419
- profile: import_zod29.z.string().optional()
5157
+ input: import_zod30.z.object({
5158
+ file: import_zod30.z.string().min(1).describe("The instruction file to edit in place."),
5159
+ budgetTokens: import_zod30.z.number().int().positive().optional(),
5160
+ fullUnderTokens: import_zod30.z.number().int().positive().optional(),
5161
+ profile: import_zod30.z.string().optional()
4420
5162
  }),
4421
5163
  fromArgv: (argv) => {
4422
5164
  const budget = argvFlag(argv, "--budget");
@@ -4442,7 +5184,7 @@ var syncInstructionsCommand = define({
4442
5184
  });
4443
5185
 
4444
5186
  // src/commands/trace.ts
4445
- var import_zod30 = require("zod");
5187
+ var import_zod31 = require("zod");
4446
5188
 
4447
5189
  // src/trace.ts
4448
5190
  var TRACE_EDGES = [
@@ -4488,8 +5230,8 @@ function trace(seedId, bundle, options = {}) {
4488
5230
  return [...reached.values()].sort(byGeneratedAt);
4489
5231
  }
4490
5232
  function byGeneratedAt(left, right) {
4491
- const at = (step) => step.record.frontmatter.generated?.at ?? "";
4492
- return at(left).localeCompare(at(right)) || left.depth - right.depth;
5233
+ const at2 = (step) => step.record.frontmatter.generated?.at ?? "";
5234
+ return at2(left).localeCompare(at2(right)) || left.depth - right.depth;
4493
5235
  }
4494
5236
 
4495
5237
  // src/commands/trace.ts
@@ -4498,11 +5240,11 @@ var traceCommand = define({
4498
5240
  tool: "kb_trace",
4499
5241
  usage: "trace <concept-id> [edges...]",
4500
5242
  description: 'Timeline of how a position was reached, ordered by write time, following supersession, shared anchors and shared sources. Includes rejected, draft and superseded records \u2014 in a history they are the content. For "why is it like this"; kb_load answers "what holds now".',
4501
- input: import_zod30.z.object({
5243
+ input: import_zod31.z.object({
4502
5244
  bundlePath,
4503
5245
  conceptId,
4504
- edges: import_zod30.z.array(import_zod30.z.enum(TRACE_EDGES)).optional(),
4505
- depth: import_zod30.z.number().int().positive().optional()
5246
+ edges: import_zod31.z.array(import_zod31.z.enum(TRACE_EDGES)).optional(),
5247
+ depth: import_zod31.z.number().int().positive().optional()
4506
5248
  }),
4507
5249
  fromArgv: (argv, path) => ({
4508
5250
  bundlePath: path,
@@ -4524,37 +5266,37 @@ var traceCommand = define({
4524
5266
  });
4525
5267
 
4526
5268
  // src/commands/types.ts
4527
- var import_zod31 = require("zod");
5269
+ var import_zod32 = require("zod");
4528
5270
  var typesCommand = define({
4529
5271
  name: "types",
4530
5272
  tool: "kb_types",
4531
5273
  usage: "types",
4532
5274
  description: "The twelve record types with their purpose, body sections, and starting status. Read this before writing rather than guessing headings \u2014 a section the type does not define is rejected.",
4533
- input: import_zod31.z.object({}),
5275
+ input: import_zod32.z.object({}),
4534
5276
  fromArgv: () => ({}),
4535
5277
  run: () => Promise.resolve(RECORD_TYPES)
4536
5278
  });
4537
5279
 
4538
5280
  // src/commands/unpin.ts
4539
- var import_zod32 = require("zod");
5281
+ var import_zod33 = require("zod");
4540
5282
  var unpinCommand = define({
4541
5283
  name: "unpin",
4542
5284
  tool: "kb_unpin",
4543
5285
  usage: "unpin [bundle-path]",
4544
5286
  description: "Remove a base from every manifest layer that holds it. Reports the layers touched.",
4545
- input: import_zod32.z.object({ bundlePath }),
5287
+ input: import_zod33.z.object({ bundlePath }),
4546
5288
  fromArgv: (argv, path) => ({ bundlePath: argv[1] ?? path }),
4547
5289
  run: (_ctx, { bundlePath: path }) => unpinBase(process.cwd(), path)
4548
5290
  });
4549
5291
 
4550
5292
  // src/commands/validate.ts
4551
- var import_zod33 = require("zod");
5293
+ var import_zod34 = require("zod");
4552
5294
  var validateCommand = define({
4553
5295
  name: "validate",
4554
5296
  tool: "kb_validate",
4555
5297
  usage: "validate",
4556
5298
  description: "Check pointers no single record can see: supersession links that disagree between the two records, typed causal links, and assumptions that cite sources. Each finding carries a severity: errors fail the exit code, warnings do not.",
4557
- input: import_zod33.z.object({ bundlePath }),
5299
+ input: import_zod34.z.object({ bundlePath }),
4558
5300
  fromArgv: (_argv, path) => ({ bundlePath: path }),
4559
5301
  run: async ({ store }, { bundlePath: path }) => validateBundle(await store.list(path)),
4560
5302
  // Warnings never fail the exit code; every other severity does.
@@ -4564,16 +5306,16 @@ var validateCommand = define({
4564
5306
  });
4565
5307
 
4566
5308
  // src/commands/verify.ts
4567
- var import_zod34 = require("zod");
5309
+ var import_zod35 = require("zod");
4568
5310
  var verifyCommand = define({
4569
5311
  name: "verify",
4570
5312
  tool: "kb_verify",
4571
5313
  usage: "verify <concept-id> --note <text>",
4572
5314
  description: "Append a verified[] event: who checked, when, and what was found. Append-only. A record's own generator is refused unless the actor is `human:`-prefixed.",
4573
- input: import_zod34.z.object({
5315
+ input: import_zod35.z.object({
4574
5316
  bundlePath,
4575
5317
  conceptId,
4576
- note: import_zod34.z.string().refine((s) => s.trim().length > 0, {
5318
+ note: import_zod35.z.string().refine((s) => s.trim().length > 0, {
4577
5319
  message: "note must say what the check found"
4578
5320
  })
4579
5321
  }),
@@ -4593,15 +5335,15 @@ var verifyCommand = define({
4593
5335
  });
4594
5336
 
4595
5337
  // src/commands/write.ts
4596
- var import_zod35 = require("zod");
5338
+ var import_zod36 = require("zod");
4597
5339
  var writeCommand = define({
4598
5340
  name: "write",
4599
5341
  tool: "kb_write",
4600
5342
  usage: "write <type> < record.json",
4601
5343
  description: "Write one record. Search first \u2014 a duplicate concept id is rejected, not overwritten; kb_types lists each type's sections. An unsourced claim is an `assumption` with assumption: true, never a vague `fact`. Conflicting records get a `risk`, `open-question`, or superseding `decision`. Prefer a new short record over overloading one. Never delete; supersede.",
4602
- input: import_zod35.z.object({
5344
+ input: import_zod36.z.object({
4603
5345
  bundlePath,
4604
- type: import_zod35.z.enum(KB_RECORD_TYPES),
5346
+ type: import_zod36.z.enum(KB_RECORD_TYPES),
4605
5347
  input: composeInputSchema
4606
5348
  }),
4607
5349
  fromArgv: async (argv, path, stdin) => ({
@@ -4625,13 +5367,13 @@ var writeCommand = define({
4625
5367
  });
4626
5368
 
4627
5369
  // src/commands/write-decision.ts
4628
- var import_zod36 = require("zod");
5370
+ var import_zod37 = require("zod");
4629
5371
  var writeDecisionCommand = define({
4630
5372
  name: "write-decision",
4631
5373
  tool: "kb_write_decision",
4632
5374
  usage: "write-decision < decision.json",
4633
5375
  description: "Write a decision, with `alternative` (what was rejected and why) and `impact` as fields. Record one when a later reader would otherwise simplify the constraint away; skip when the diff already answers it. `sources` for material read, `anchors` for code, `relatedConceptIds` for records.",
4634
- input: import_zod36.z.object({ bundlePath, input: decisionInputSchema }),
5376
+ input: import_zod37.z.object({ bundlePath, input: decisionInputSchema }),
4635
5377
  fromArgv: async (_argv, path, stdin) => ({
4636
5378
  bundlePath: path,
4637
5379
  input: JSON.parse(await stdin())
@@ -4661,6 +5403,7 @@ var KB_COMMANDS = [
4661
5403
  answerCommand,
4662
5404
  verifyCommand,
4663
5405
  anchorResolveCommand,
5406
+ reassessCommand,
4664
5407
  loadCommand,
4665
5408
  catalogCommand,
4666
5409
  packCommand,
@@ -4687,7 +5430,7 @@ var KB_COMMANDS_BY_NAME = new Map(
4687
5430
  );
4688
5431
 
4689
5432
  // src/kb-store.ts
4690
- var import_promises9 = require("fs/promises");
5433
+ var import_promises10 = require("fs/promises");
4691
5434
  var import_node_path11 = require("path");
4692
5435
 
4693
5436
  // src/markdown.ts
@@ -4748,7 +5491,7 @@ function bundleDigest(records, superseded) {
4748
5491
  }
4749
5492
 
4750
5493
  // src/search-index.ts
4751
- var import_promises8 = require("fs/promises");
5494
+ var import_promises9 = require("fs/promises");
4752
5495
  var import_node_path10 = require("path");
4753
5496
  var SEARCH_INDEX_FILE = ".index.sqlite";
4754
5497
  var COLLECTION = "kb";
@@ -4793,7 +5536,7 @@ async function searchBase(bundlePath2, query, options = {}) {
4793
5536
  }
4794
5537
  }
4795
5538
  async function isStale(bundlePath2) {
4796
- const indexAt = await (0, import_promises8.stat)((0, import_node_path10.join)(bundlePath2, SEARCH_INDEX_FILE)).then((s) => s.mtimeMs).catch(() => 0);
5539
+ const indexAt = await (0, import_promises9.stat)((0, import_node_path10.join)(bundlePath2, SEARCH_INDEX_FILE)).then((s) => s.mtimeMs).catch(() => 0);
4797
5540
  if (!indexAt) return true;
4798
5541
  const { readdir: readdir2 } = await import("fs/promises");
4799
5542
  const names = (await readdir2(bundlePath2).catch(() => [])).filter(
@@ -4802,8 +5545,8 @@ async function isStale(bundlePath2) {
4802
5545
  let stale = false;
4803
5546
  await mapLimit(names, DEFAULT_IO_CONCURRENCY, async (name) => {
4804
5547
  if (stale) return;
4805
- const at = await (0, import_promises8.stat)((0, import_node_path10.join)(bundlePath2, name)).then((s) => s.mtimeMs).catch(() => 0);
4806
- if (at > indexAt) stale = true;
5548
+ const at2 = await (0, import_promises9.stat)((0, import_node_path10.join)(bundlePath2, name)).then((s) => s.mtimeMs).catch(() => 0);
5549
+ if (at2 > indexAt) stale = true;
4807
5550
  });
4808
5551
  return stale;
4809
5552
  }
@@ -5111,7 +5854,7 @@ var KbStore = class {
5111
5854
  const conceptId2 = `${input.type}.${input.slug}`;
5112
5855
  const root = this.root(bundlePath2);
5113
5856
  const target = this.recordPath(bundlePath2, conceptId2);
5114
- await (0, import_promises9.mkdir)(root, { recursive: true });
5857
+ await (0, import_promises10.mkdir)(root, { recursive: true });
5115
5858
  await this.publish(
5116
5859
  target,
5117
5860
  stringifyMarkdownWithFrontmatter(input.body, frontmatter),
@@ -5150,7 +5893,7 @@ var KbStore = class {
5150
5893
  const target = this.recordPath(bundlePath2, conceptId2);
5151
5894
  let raw;
5152
5895
  try {
5153
- raw = await (0, import_promises9.readFile)(target, "utf8");
5896
+ raw = await (0, import_promises10.readFile)(target, "utf8");
5154
5897
  } catch {
5155
5898
  return null;
5156
5899
  }
@@ -5167,7 +5910,7 @@ var KbStore = class {
5167
5910
  const root = this.root(bundlePath2);
5168
5911
  let names;
5169
5912
  try {
5170
- names = await (0, import_promises9.readdir)(root);
5913
+ names = await (0, import_promises10.readdir)(root);
5171
5914
  } catch {
5172
5915
  return [];
5173
5916
  }
@@ -5175,7 +5918,7 @@ var KbStore = class {
5175
5918
  const records = await mapLimit(
5176
5919
  wanted,
5177
5920
  DEFAULT_IO_CONCURRENCY,
5178
- async ({ name, conceptId: conceptId2 }) => this.parse(conceptId2, await (0, import_promises9.readFile)((0, import_node_path11.join)(root, name), "utf8"))
5921
+ async ({ name, conceptId: conceptId2 }) => this.parse(conceptId2, await (0, import_promises10.readFile)((0, import_node_path11.join)(root, name), "utf8"))
5179
5922
  );
5180
5923
  return records.filter((record) => record !== null);
5181
5924
  }
@@ -5223,8 +5966,8 @@ var KbStore = class {
5223
5966
  * and the refusal is logged under its own operation name — `mutate` only
5224
5967
  * logs what it publishes.
5225
5968
  */
5226
- async verify(bundlePath2, conceptId2, note, actor = "unknown", at = (/* @__PURE__ */ new Date()).toISOString()) {
5227
- const event = kbVerifiedEventSchema.parse({ by: actor, at, note });
5969
+ async verify(bundlePath2, conceptId2, note, actor = "unknown", at2 = (/* @__PURE__ */ new Date()).toISOString()) {
5970
+ const event = kbVerifiedEventSchema.parse({ by: actor, at: at2, note });
5228
5971
  const existing = await this.read(bundlePath2, conceptId2);
5229
5972
  if (!existing) throw new KbRecordNotFoundError(conceptId2);
5230
5973
  const generatedBy = existing.frontmatter.generated?.by;
@@ -5276,14 +6019,14 @@ var KbStore = class {
5276
6019
  return superseded;
5277
6020
  }
5278
6021
  /** Resolves an open question, stamping who answered and when. */
5279
- async answer(bundlePath2, conceptId2, answer, actor = "unknown", at = (/* @__PURE__ */ new Date()).toISOString()) {
6022
+ async answer(bundlePath2, conceptId2, answer, actor = "unknown", at2 = (/* @__PURE__ */ new Date()).toISOString()) {
5280
6023
  return this.mutate(
5281
6024
  bundlePath2,
5282
6025
  conceptId2,
5283
6026
  (frontmatter) => ({
5284
6027
  ...frontmatter,
5285
6028
  strauss_status: "resolved",
5286
- strauss_answered: { by: actor, at }
6029
+ strauss_answered: { by: actor, at: at2 }
5287
6030
  }),
5288
6031
  { operation: "answer", by: actor },
5289
6032
  (body) => `${body.trimEnd()}
@@ -5452,24 +6195,34 @@ ${answer}
5452
6195
  }
5453
6196
  /**
5454
6197
  * `load`'s digest without `load`'s bodies — the same records, adjudicated
5455
- * the same way, handed back as a stamp. Skips the anchor drift pass, which
5456
- * reads source files and only ever adds warnings: no warning reaches the
5457
- * digest, so the value is identical to the one `load` returns.
6198
+ * the same way, handed back as a stamp.
6199
+ *
6200
+ * Drift is counted but kept out of the digest, which is what lets the reload
6201
+ * hook ask one question and get two answers: whether the base moved, and
6202
+ * whether the code under it did. A `load` and a `stamp` of the same base
6203
+ * still agree on the digest, because no warning has ever reached it.
5458
6204
  */
5459
- async stamp(bundlePath2) {
6205
+ async stamp(bundlePath2, options = {}) {
5460
6206
  const bundle = await this.list(bundlePath2);
5461
6207
  const adjudicated = adjudicate(bundle, bundle, /* @__PURE__ */ new Date());
5462
6208
  const current = adjudicated.filter((hit) => hit.standing !== "superseded");
5463
6209
  const superseded = adjudicated.filter((hit) => hit.standing === "superseded").map(stub);
5464
6210
  const stamped = bundleStamp(current, superseded);
5465
- const dates = bundle.map((record) => record.frontmatter.generated?.at ?? null).filter((at) => typeof at === "string").sort();
6211
+ const dates = bundle.map((record) => record.frontmatter.generated?.at ?? null).filter((at2) => typeof at2 === "string").sort();
6212
+ const drift = await this.detectDrift(bundle, options.repoRoot);
6213
+ const drifted2 = drift === void 0 ? null : [...drift.values()].filter(
6214
+ (entries) => entries.some(
6215
+ (entry) => entry.state !== "match" && !isUncheckedReason(entry.reason)
6216
+ )
6217
+ ).length;
5466
6218
  return {
5467
6219
  path: bundlePath2,
5468
6220
  digest: stamped.digest,
5469
6221
  recordCount: bundle.length,
5470
6222
  superseded: superseded.length,
5471
6223
  newestAt: dates.at(-1) ?? null,
5472
- records: stamped.records
6224
+ records: stamped.records,
6225
+ drifted: drifted2
5473
6226
  };
5474
6227
  }
5475
6228
  /** How a position was arrived at, as a timeline. See `trace.ts`. */
@@ -5502,7 +6255,7 @@ ${answer}
5502
6255
  async readIndex(bundlePath2) {
5503
6256
  const root = this.root(bundlePath2);
5504
6257
  const expected = renderIndex(await this.list(bundlePath2));
5505
- const stored = await (0, import_promises9.readFile)((0, import_node_path11.join)(root, INDEX_FILE), "utf8").catch(
6258
+ const stored = await (0, import_promises10.readFile)((0, import_node_path11.join)(root, INDEX_FILE), "utf8").catch(
5506
6259
  () => null
5507
6260
  );
5508
6261
  if (indexIsStale(stored, expected)) {
@@ -5523,7 +6276,7 @@ ${answer}
5523
6276
  * knows which agent touched what. So a bad line is surfaced and left alone.
5524
6277
  */
5525
6278
  async readLog(bundlePath2) {
5526
- const raw = await (0, import_promises9.readFile)(
6279
+ const raw = await (0, import_promises10.readFile)(
5527
6280
  (0, import_node_path11.join)(this.root(bundlePath2), LOG_FILE),
5528
6281
  "utf8"
5529
6282
  ).catch(() => "");
@@ -5575,14 +6328,14 @@ ${answer}
5575
6328
  }
5576
6329
  async mutate(bundlePath2, conceptId2, change, entry, changeBody = (body) => body) {
5577
6330
  const target = this.recordPath(bundlePath2, conceptId2);
5578
- const before = await (0, import_promises9.readFile)(target, "utf8").catch(() => null);
6331
+ const before = await (0, import_promises10.readFile)(target, "utf8").catch(() => null);
5579
6332
  if (before === null) throw new KbRecordNotFoundError(conceptId2);
5580
6333
  const parsed = this.parse(conceptId2, before);
5581
6334
  if (!parsed) throw new KbRecordNotFoundError(conceptId2);
5582
6335
  const frontmatter = change(parsed.frontmatter);
5583
6336
  const body = changeBody(parsed.body);
5584
6337
  const contents = stringifyMarkdownWithFrontmatter(body, frontmatter);
5585
- const witness = await (0, import_promises9.readFile)(target, "utf8").catch(() => null);
6338
+ const witness = await (0, import_promises10.readFile)(target, "utf8").catch(() => null);
5586
6339
  if (witness === null || sha2563(witness) !== sha2563(before)) {
5587
6340
  throw new KbWriteConflictError(conceptId2);
5588
6341
  }
@@ -5608,20 +6361,20 @@ ${answer}
5608
6361
  */
5609
6362
  async publish(target, contents, overwrite, conceptId2) {
5610
6363
  const staging = `${target}.${process.pid}.tmp`;
5611
- await (0, import_promises9.writeFile)(staging, contents, "utf8");
6364
+ await (0, import_promises10.writeFile)(staging, contents, "utf8");
5612
6365
  try {
5613
6366
  if (overwrite) {
5614
- await (0, import_promises9.rename)(staging, target);
6367
+ await (0, import_promises10.rename)(staging, target);
5615
6368
  return;
5616
6369
  }
5617
- await (0, import_promises9.link)(staging, target);
6370
+ await (0, import_promises10.link)(staging, target);
5618
6371
  } catch (error) {
5619
6372
  if (error.code === "EEXIST") {
5620
6373
  throw new KbRecordAlreadyExistsError(conceptId2);
5621
6374
  }
5622
6375
  throw error;
5623
6376
  } finally {
5624
- await (0, import_promises9.unlink)(staging).catch(() => void 0);
6377
+ await (0, import_promises10.unlink)(staging).catch(() => void 0);
5625
6378
  }
5626
6379
  }
5627
6380
  /**
@@ -5669,14 +6422,14 @@ ${answer}
5669
6422
  try {
5670
6423
  let existing;
5671
6424
  try {
5672
- existing = await (0, import_promises9.readFile)(target, "utf8");
6425
+ existing = await (0, import_promises10.readFile)(target, "utf8");
5673
6426
  } catch (error) {
5674
6427
  if (error.code !== "ENOENT") throw error;
5675
6428
  existing = null;
5676
6429
  }
5677
6430
  if (existing === null) {
5678
6431
  try {
5679
- await (0, import_promises9.writeFile)(target, appendUnionMergeLine(""), {
6432
+ await (0, import_promises10.writeFile)(target, appendUnionMergeLine(""), {
5680
6433
  encoding: "utf8",
5681
6434
  flag: "wx"
5682
6435
  });
@@ -5697,7 +6450,7 @@ ${answer}
5697
6450
  return;
5698
6451
  }
5699
6452
  if (!hasMergeDeclaration(existing)) {
5700
- await (0, import_promises9.appendFile)(target, appendUnionMergeLine(existing), "utf8");
6453
+ await (0, import_promises10.appendFile)(target, appendUnionMergeLine(existing), "utf8");
5701
6454
  this.logger.info?.({
5702
6455
  operation: "kb.gitattributes.ensure",
5703
6456
  bundlePath: root,
@@ -5716,7 +6469,7 @@ ${answer}
5716
6469
  async record(root, entry) {
5717
6470
  await this.ensureGitattributes(root);
5718
6471
  const line = renderLogEntry({ at: (/* @__PURE__ */ new Date()).toISOString(), ...entry });
5719
- await (0, import_promises9.appendFile)((0, import_node_path11.join)(root, LOG_FILE), line, "utf8").catch((error) => {
6472
+ await (0, import_promises10.appendFile)((0, import_node_path11.join)(root, LOG_FILE), line, "utf8").catch((error) => {
5720
6473
  this.logger.warn?.({
5721
6474
  operation: "kb.log.append",
5722
6475
  outcome: "failed",
@@ -5793,7 +6546,7 @@ function normalizeActor(id) {
5793
6546
  }
5794
6547
 
5795
6548
  // src/version.ts
5796
- var VERSION = true ? "0.1.17" : "0.0.0-dev";
6549
+ var VERSION = true ? "0.1.18" : "0.0.0-dev";
5797
6550
 
5798
6551
  // src/mcp.ts
5799
6552
  function createKbMcpServer() {