@saasontools/strauss-kb 0.1.16 → 0.1.17

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
@@ -23,6 +23,10 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
23
  mod
24
24
  ));
25
25
 
26
+ // ../../node_modules/.pnpm/tsup@8.5.1_jiti@2.6.1_postcss@8.5.26_supports-color@8.1.1_typescript@6.0.3_yaml@2.9.0/node_modules/tsup/assets/cjs_shims.js
27
+ var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
28
+ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
29
+
26
30
  // src/mcp.ts
27
31
  var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
28
32
  var import_stdio = require("@modelcontextprotocol/sdk/server/stdio.js");
@@ -78,7 +82,13 @@ var kbAnchorSchema = import_zod.z.object({
78
82
  /** ISO 8601 timestamp of the last successful resolution. */
79
83
  resolved_at: import_zod.z.string().min(1).optional(),
80
84
  /** Line count of the text the hash was taken over. */
81
- lines: import_zod.z.number().int().positive().optional()
85
+ lines: import_zod.z.number().int().positive().optional(),
86
+ /**
87
+ * Which resolver produced the hashed span. Absent means an anchor stamped
88
+ * before resolvers were named, which is read as `regex` — the only one
89
+ * there was. A hash from a different resolver is drift, not a match.
90
+ */
91
+ resolver: import_zod.z.enum(["tree-sitter", "regex"]).optional()
82
92
  }).strict();
83
93
  var kbLinkSchema = import_zod.z.object({
84
94
  target: import_zod.z.string().min(1),
@@ -442,7 +452,7 @@ function composeNoDecisionRecord(reason, writtenBy, writtenAt) {
442
452
  }
443
453
 
444
454
  // src/commands/anchor-resolve.ts
445
- var import_zod6 = require("zod");
455
+ var import_zod7 = require("zod");
446
456
 
447
457
  // src/concurrency.ts
448
458
  var DEFAULT_IO_CONCURRENCY = 16;
@@ -739,18 +749,18 @@ async function readOneRepo(repo, url, declared, context) {
739
749
  if (!repoUrlIsSafe(url)) return all({ ok: false, reason: "repo-invalid" });
740
750
  const cache = cachePathFor(repo, context.cacheDir);
741
751
  if (!cache) return all({ ok: false, reason: "remote-unreachable" });
742
- const rejected = /* @__PURE__ */ new Map();
752
+ const rejected2 = /* @__PURE__ */ new Map();
743
753
  const usable = [];
744
754
  for (const want of wants) {
745
755
  const reason = wantReason(want);
746
756
  if (reason)
747
- rejected.set(wantKey(repo, want.ref, want.file), { ok: false, reason });
757
+ rejected2.set(wantKey(repo, want.ref, want.file), { ok: false, reason });
748
758
  else usable.push(want);
749
759
  }
750
- if (!usable.length) return rejected;
760
+ if (!usable.length) return rejected2;
751
761
  wants = usable;
752
762
  const opened = await openCache(cache, url, context);
753
- if (opened) return new Map([...rejected, ...all(opened)]);
763
+ if (opened) return new Map([...rejected2, ...all(opened)]);
754
764
  const wantsDefault = wants.some((want) => want.ref === void 0);
755
765
  const branch = wantsDefault ? await defaultBranch(cache, context) : {};
756
766
  const revs = /* @__PURE__ */ new Map();
@@ -777,7 +787,7 @@ async function readOneRepo(repo, url, declared, context) {
777
787
  }
778
788
  );
779
789
  return new Map([
780
- ...rejected,
790
+ ...rejected2,
781
791
  ...wants.map(
782
792
  (want, at) => [wantKey(repo, want.ref, want.file), reads[at]]
783
793
  )
@@ -829,13 +839,13 @@ async function defaultBranch(cache, context) {
829
839
  if (!listed.ok) {
830
840
  const reason = transportReason(listed.stderr);
831
841
  if (reason !== "ref-not-found") {
832
- const cached2 = await cachedBranch(cache);
833
- return cached2 ? { name: cached2 } : { reason };
842
+ const cached3 = await cachedBranch(cache);
843
+ return cached3 ? { name: cached3 } : { reason };
834
844
  }
835
845
  }
836
846
  }
837
- const cached = await cachedBranch(cache);
838
- if (cached) return { name: cached };
847
+ const cached2 = await cachedBranch(cache);
848
+ if (cached2) return { name: cached2 };
839
849
  return {
840
850
  reason: context.offline ? "remote-unreachable" : "default-branch-unknown"
841
851
  };
@@ -862,8 +872,8 @@ async function ensureRev(cache, rev, context) {
862
872
  cwd: cache
863
873
  }
864
874
  );
865
- const cached = have.ok && have.stdout.trim().length > 0;
866
- if (cached && (context.offline || IMMUTABLE_REV.test(rev))) return void 0;
875
+ const cached2 = have.ok && have.stdout.trim().length > 0;
876
+ if (cached2 && (context.offline || IMMUTABLE_REV.test(rev))) return void 0;
867
877
  if (context.offline) return { ok: false, reason: "remote-unreachable" };
868
878
  const fetched = await git(
869
879
  [
@@ -879,7 +889,7 @@ async function ensureRev(cache, rev, context) {
879
889
  );
880
890
  if (!fetched.ok) {
881
891
  const reason = transportReason(fetched.stderr);
882
- if (cached && reason !== "ref-not-found") return void 0;
892
+ if (cached2 && reason !== "ref-not-found") return void 0;
883
893
  return { ok: false, reason };
884
894
  }
885
895
  const head = await git(["rev-parse", "FETCH_HEAD"], { cwd: cache });
@@ -994,63 +1004,577 @@ async function readAnchorFiles(files, read, concurrency = DEFAULT_IO_CONCURRENCY
994
1004
  }
995
1005
 
996
1006
  // src/anchor-resolver/resolver.ts
1007
+ var import_node_crypto3 = require("crypto");
1008
+
1009
+ // src/tree-sitter-resolver/languages.ts
1010
+ var import_node_path5 = require("path");
1011
+
1012
+ // src/grammars/index.ts
1013
+ var import_promises4 = require("fs/promises");
1014
+
1015
+ // src/grammars/store.ts
997
1016
  var import_node_crypto = require("crypto");
1017
+ var import_promises3 = require("fs/promises");
1018
+ var import_node_os2 = require("os");
1019
+ var import_node_path3 = require("path");
1020
+ function grammarsCacheRoot(override) {
1021
+ return override ?? process.env["STRAUSS_KB_GRAMMARS_DIR"] ?? (0, import_node_path3.join)((0, import_node_os2.homedir)(), ".strauss", "grammars");
1022
+ }
1023
+ function grammarCachePath(root, language, sha2564, extension = "wasm") {
1024
+ return (0, import_node_path3.join)(root, language, `${sha2564.slice(0, 12)}.${extension}`);
1025
+ }
1026
+ function sha256(bytes) {
1027
+ return (0, import_node_crypto.createHash)("sha256").update(bytes).digest("hex");
1028
+ }
1029
+ function matches(bytes, entry) {
1030
+ if (entry.bytes !== void 0 && bytes.byteLength !== entry.bytes)
1031
+ return false;
1032
+ return sha256(bytes) === entry.sha256;
1033
+ }
1034
+ async function verifyCached(path, entry) {
1035
+ let bytes;
1036
+ try {
1037
+ bytes = await (0, import_promises3.readFile)(path);
1038
+ } catch {
1039
+ return false;
1040
+ }
1041
+ if (matches(bytes, entry)) return true;
1042
+ await (0, import_promises3.rm)(path, { force: true });
1043
+ return false;
1044
+ }
1045
+ async function writeCached(path, bytes) {
1046
+ await (0, import_promises3.mkdir)((0, import_node_path3.dirname)(path), { recursive: true });
1047
+ const temporary = `${path}.${process.pid}.${(0, import_node_crypto.randomBytes)(4).toString("hex")}.tmp`;
1048
+ try {
1049
+ await (0, import_promises3.writeFile)(temporary, bytes);
1050
+ await (0, import_promises3.rename)(temporary, path);
1051
+ } catch (error) {
1052
+ await (0, import_promises3.rm)(temporary, { force: true });
1053
+ throw error;
1054
+ }
1055
+ }
1056
+
1057
+ // src/grammars/fetch.ts
1058
+ var ATTEMPTS = 3;
1059
+ var BACKOFF_MS = 250;
1060
+ function grammarUrl(url, override) {
1061
+ const base2 = grammarsBaseUrl(override);
1062
+ if (!base2) return url;
1063
+ let root = base2;
1064
+ while (root.endsWith("/")) root = root.slice(0, -1);
1065
+ const pinned = new URL(url);
1066
+ return `${root}${pinned.pathname}${pinned.search}`;
1067
+ }
1068
+ function grammarsBaseUrl(override) {
1069
+ return override ?? process.env["STRAUSS_KB_GRAMMARS_URL"];
1070
+ }
1071
+ async function downloadPart(url, name, entry, options = {}) {
1072
+ const log = options.log ?? ((line) => void process.stderr.write(line));
1073
+ const weight = entry.bytes === void 0 ? "" : ` (${size(entry.bytes)} from manifest)`;
1074
+ log(`strauss-kb: downloading ${name}${weight} from ${url}
1075
+ `);
1076
+ let cause = "";
1077
+ for (let attempt = 1; attempt <= ATTEMPTS; attempt++) {
1078
+ const outcome = await attemptDownload(url, entry, options.fetchTimeoutMs);
1079
+ if ("bytes" in outcome) return outcome;
1080
+ cause = outcome.cause;
1081
+ log(
1082
+ `strauss-kb: ${name} attempt ${attempt}/${ATTEMPTS} failed: ${cause}
1083
+ `
1084
+ );
1085
+ if (!outcome.retry) break;
1086
+ if (attempt < ATTEMPTS) await pause(BACKOFF_MS * attempt);
1087
+ }
1088
+ log(`strauss-kb: ${name} not downloaded: ${cause}
1089
+ `);
1090
+ return { cause };
1091
+ }
1092
+ async function attemptDownload(url, entry, timeoutMs) {
1093
+ try {
1094
+ const response = await fetch(url, {
1095
+ signal: AbortSignal.timeout(fetchTimeoutMs(timeoutMs))
1096
+ });
1097
+ if (!response.ok) {
1098
+ return {
1099
+ cause: `HTTP ${response.status}`,
1100
+ retry: response.status >= 500 || response.status === 429
1101
+ };
1102
+ }
1103
+ const bytes = new Uint8Array(await response.arrayBuffer());
1104
+ if (!matches(bytes, entry))
1105
+ return { cause: "sha256 mismatch", retry: false };
1106
+ return { bytes };
1107
+ } catch (error) {
1108
+ const timedOut = error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
1109
+ return { cause: timedOut ? "timeout" : "network error", retry: true };
1110
+ }
1111
+ }
1112
+ function size(bytes) {
1113
+ return bytes >= 1024 * 1024 ? `${(bytes / (1024 * 1024)).toFixed(1)} MB` : `${Math.round(bytes / 1024)} KB`;
1114
+ }
1115
+ function pause(ms) {
1116
+ return new Promise((resolve6) => setTimeout(resolve6, ms));
1117
+ }
1118
+
1119
+ // src/grammars/manifest.ts
1120
+ var import_node_fs = require("fs");
1121
+ var import_node_path4 = require("path");
1122
+ var import_node_url = require("url");
1123
+
1124
+ // src/grammars/model.ts
1125
+ var import_zod4 = require("zod");
1126
+ var sha2562 = import_zod4.z.string().regex(/^[0-9a-f]{64}$/);
1127
+ var grammarWasmSchema = import_zod4.z.object({
1128
+ url: import_zod4.z.string().min(1),
1129
+ sha256: sha2562,
1130
+ bytes: import_zod4.z.number().int().positive()
1131
+ });
1132
+ var grammarTagsSchema = import_zod4.z.object({ url: import_zod4.z.string().min(1), sha256: sha2562 });
1133
+ var grammarPackSchema = import_zod4.z.object({
1134
+ package: import_zod4.z.string().min(1),
1135
+ wasm: grammarWasmSchema,
1136
+ tags: import_zod4.z.array(grammarTagsSchema),
1137
+ license: import_zod4.z.string().min(1),
1138
+ extensions: import_zod4.z.array(import_zod4.z.string().min(1))
1139
+ });
1140
+ var grammarManifestSchema = import_zod4.z.object({
1141
+ /** The runtime the packs were proved against. */
1142
+ webTreeSitter: import_zod4.z.string().min(1),
1143
+ linguist: import_zod4.z.object({ tag: import_zod4.z.string().min(1), commit: import_zod4.z.string().min(1) }),
1144
+ packs: import_zod4.z.record(import_zod4.z.string().min(1), grammarPackSchema)
1145
+ });
1146
+
1147
+ // src/grammars/manifest.ts
1148
+ var cached;
1149
+ function grammarManifest() {
1150
+ cached ??= grammarManifestSchema.parse(
1151
+ JSON.parse((0, import_node_fs.readFileSync)(grammarsDataPath("manifest.json"), "utf8"))
1152
+ );
1153
+ return cached;
1154
+ }
1155
+ function grammarsDataPath(...segments) {
1156
+ let dir = (0, import_node_path4.dirname)((0, import_node_url.fileURLToPath)(importMetaUrl));
1157
+ for (let up = 0; up < 5; up++) {
1158
+ const candidate = (0, import_node_path4.join)(dir, "grammars");
1159
+ if ((0, import_node_fs.existsSync)((0, import_node_path4.join)(candidate, "manifest.json")))
1160
+ return (0, import_node_path4.join)(candidate, ...segments);
1161
+ dir = (0, import_node_path4.dirname)(dir);
1162
+ }
1163
+ throw new Error("grammars/manifest.json is missing from the package");
1164
+ }
1165
+
1166
+ // src/grammars/index.ts
1167
+ var inFlight = /* @__PURE__ */ new Map();
1168
+ var missing = /* @__PURE__ */ new Map();
1169
+ var uncompilable = /* @__PURE__ */ new Map();
1170
+ var rejected = /* @__PURE__ */ new Map();
1171
+ function grammarsDownloadDisabled() {
1172
+ return process.env["STRAUSS_KB_GRAMMARS"] === "off";
1173
+ }
1174
+ async function ensureGrammar(language, options = {}) {
1175
+ const pack2 = grammarManifest().packs[language];
1176
+ if (!pack2) return null;
1177
+ const root = grammarsCacheRoot(options.cacheRoot);
1178
+ const wasm = grammarCachePath(root, language, pack2.wasm.sha256);
1179
+ const key = `${wasm} ${grammarsBaseUrl(options.baseUrl) ?? ""}`;
1180
+ const existing = inFlight.get(key);
1181
+ if (existing) return existing;
1182
+ const pending = (async () => {
1183
+ const grammar = await ensurePart(
1184
+ wasm,
1185
+ `tree-sitter-${language}`,
1186
+ pack2.wasm,
1187
+ options
1188
+ );
1189
+ if (grammar !== true)
1190
+ return miss(language, `grammar tree-sitter-${language}`, grammar);
1191
+ const parts = [];
1192
+ 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}` : ""}`;
1195
+ const path = grammarCachePath(root, language, part.sha256, "scm");
1196
+ const held = await ensurePart(path, name, part, options);
1197
+ if (held !== true) return miss(language, name, held);
1198
+ parts.push(`; ${part.url}
1199
+ ${lf(await (0, import_promises4.readFile)(path, "utf8"))}`);
1200
+ }
1201
+ missing.delete(language);
1202
+ return { wasm, query: total ? parts.join("\n") : void 0 };
1203
+ })();
1204
+ inFlight.set(key, pending);
1205
+ const result = await pending;
1206
+ if (result === null) inFlight.delete(key);
1207
+ return result;
1208
+ }
1209
+ async function ensurePart(path, name, entry, options) {
1210
+ if (await verifyCached(path, entry)) return true;
1211
+ if (options.offline === true || grammarsDownloadDisabled()) return {};
1212
+ const download = await downloadPart(
1213
+ grammarUrl(entry.url, options.baseUrl),
1214
+ name,
1215
+ entry,
1216
+ options
1217
+ );
1218
+ if ("cause" in download) return { cause: download.cause };
1219
+ await writeCached(path, download.bytes).catch(() => null);
1220
+ return true;
1221
+ }
1222
+ function miss(language, subject, failure) {
1223
+ missing.set(language, { subject, ...failure });
1224
+ return null;
1225
+ }
1226
+ function lf(body) {
1227
+ return body.replace(/\r\n/g, "\n");
1228
+ }
1229
+ function noteUncompilableQuery(language, cause) {
1230
+ uncompilable.set(language, cause);
1231
+ }
1232
+ function noteRejectedGrammar(language, cause) {
1233
+ rejected.set(language, cause);
1234
+ }
1235
+ function grammarHints() {
1236
+ const manifest = grammarManifest();
1237
+ const packs = manifest.packs;
1238
+ const lines = /* @__PURE__ */ new Map();
1239
+ for (const [language, { subject, cause }] of missing)
1240
+ lines.set(
1241
+ language,
1242
+ `${subject} not cached${cause ? ` (${cause})` : ""}; run online once, or set STRAUSS_KB_GRAMMARS_DIR`
1243
+ );
1244
+ for (const [language, cause] of rejected)
1245
+ lines.set(
1246
+ language,
1247
+ `${packs[language]?.package ?? `tree-sitter-${language}`} rejected by web-tree-sitter ${manifest.webTreeSitter}${cause ? `: ${cause}` : ""}; re-pin with pnpm grammars pin ${language}`
1248
+ );
1249
+ for (const [language, cause] of uncompilable)
1250
+ lines.set(
1251
+ language,
1252
+ `tags query for ${language} does not compile against ${packs[language]?.package ?? `tree-sitter-${language}`}: ${cause}; re-pin with pnpm grammars pin ${language}`
1253
+ );
1254
+ return [...lines].sort(([a], [b]) => a.localeCompare(b)).map(([, line]) => line);
1255
+ }
1256
+
1257
+ // src/tree-sitter-resolver/languages.ts
1258
+ var table;
1259
+ function extensionTable() {
1260
+ const manifest = grammarManifest();
1261
+ if (table?.of !== manifest)
1262
+ table = {
1263
+ of: manifest,
1264
+ extensions: Object.fromEntries(
1265
+ Object.entries(manifest.packs).flatMap(
1266
+ ([language, pack2]) => pack2.extensions.map((extension) => [extension, language])
1267
+ )
1268
+ )
1269
+ };
1270
+ return table.extensions;
1271
+ }
1272
+ function hasQuery(language) {
1273
+ return (grammarManifest().packs[language]?.tags.length ?? 0) > 0;
1274
+ }
1275
+ function languageForFile(file) {
1276
+ const language = extensionTable()[(0, import_node_path5.extname)(file).toLowerCase()];
1277
+ return language && hasQuery(language) ? language : void 0;
1278
+ }
1279
+
1280
+ // src/tree-sitter-resolver/resolver.ts
1281
+ var import_node_crypto2 = require("crypto");
1282
+ var import_web_tree_sitter = require("web-tree-sitter");
1283
+
1284
+ // src/tree-sitter-resolver/definitions.ts
1285
+ var SCOPE_ONLY = "reference.implementation";
1286
+ function index(tree, query) {
1287
+ const byName = /* @__PURE__ */ new Map();
1288
+ for (const match of query.matches(tree.rootNode)) {
1289
+ const nameNode = match.captures.find((capture) => capture.name === "name");
1290
+ const defNode = match.captures.find(
1291
+ (capture) => capture.name.startsWith("definition.") || capture.name === SCOPE_ONLY
1292
+ );
1293
+ if (!nameNode || !defNode) continue;
1294
+ const candidate = {
1295
+ node: defNode.node,
1296
+ name: nameNode.node.text,
1297
+ target: defNode.name !== SCOPE_ONLY
1298
+ };
1299
+ const existing = byName.get(nameNode.node.id);
1300
+ if (existing && width(existing.node) <= width(candidate.node)) continue;
1301
+ byName.set(nameNode.node.id, candidate);
1302
+ }
1303
+ const definitions = [...byName.values()];
1304
+ return {
1305
+ tree,
1306
+ byNodeId: new Map(
1307
+ definitions.map((definition) => [definition.node.id, definition])
1308
+ ),
1309
+ definitions
1310
+ };
1311
+ }
1312
+ function select(parsed, wanted) {
1313
+ const matches3 = parsed.definitions.filter(
1314
+ (definition) => definition.target && endsWith(chainOf(definition, parsed.byNodeId), wanted)
1315
+ );
1316
+ if (matches3.length < 2) return matches3;
1317
+ const bodied = matches3.filter(
1318
+ (definition) => definition.node.childForFieldName("body") !== null
1319
+ );
1320
+ return bodied.length === 1 ? bodied : matches3;
1321
+ }
1322
+ function chainOf(definition, byNodeId) {
1323
+ const chain = [definition.name];
1324
+ const receiver = definition.node.childForFieldName("receiver");
1325
+ const type = receiver && typeNameIn(receiver);
1326
+ if (type) chain.unshift(type);
1327
+ for (let node = definition.node.parent; node; node = node.parent) {
1328
+ const enclosing = byNodeId.get(node.id);
1329
+ if (enclosing && enclosing.node !== definition.node)
1330
+ chain.unshift(enclosing.name);
1331
+ }
1332
+ return chain;
1333
+ }
1334
+ function typeNameIn(receiver) {
1335
+ const stack = [receiver];
1336
+ while (stack.length) {
1337
+ const node = stack.pop();
1338
+ if (node.type === "type_identifier") return node.text;
1339
+ for (let at = 0; at < node.childCount; at++) {
1340
+ const child = node.child(at);
1341
+ if (child) stack.push(child);
1342
+ }
1343
+ }
1344
+ return void 0;
1345
+ }
1346
+ function endsWith(chain, wanted) {
1347
+ if (wanted.length > chain.length) return false;
1348
+ const offset = chain.length - wanted.length;
1349
+ return wanted.every((segment, at) => chain[offset + at] === segment);
1350
+ }
1351
+ function width(node) {
1352
+ return node.endIndex - node.startIndex;
1353
+ }
1354
+ function spanOf(definition, source) {
1355
+ let start = definition.node;
1356
+ let end = definition.node;
1357
+ for (let sibling = start.previousSibling; sibling?.type === "decorator"; sibling = sibling.previousSibling) {
1358
+ start = sibling;
1359
+ }
1360
+ const parent = end.parent;
1361
+ if (parent?.type === "export_statement" && parent.childForFieldName("declaration")?.id === end.id) {
1362
+ start = parent;
1363
+ end = parent;
1364
+ }
1365
+ const lines = source.split("\n");
1366
+ const startLine = start.startPosition.row;
1367
+ const endLine = end.endPosition.column === 0 && end.endPosition.row > startLine ? end.endPosition.row - 1 : end.endPosition.row;
1368
+ return {
1369
+ text: lines.slice(startLine, endLine + 1).join("\n"),
1370
+ startLine: startLine + 1,
1371
+ endLine: endLine + 1
1372
+ };
1373
+ }
1374
+
1375
+ // src/tree-sitter-resolver/resolver.ts
1376
+ var TREE_CACHE_LIMIT = 32;
1377
+ var TreeSitterResolver = class {
1378
+ name = "tree-sitter";
1379
+ grammars;
1380
+ loaded = /* @__PURE__ */ new Map();
1381
+ trees = /* @__PURE__ */ new Map();
1382
+ parser;
1383
+ initialized = false;
1384
+ /** Cache effectiveness, for tests and for the latency numbers. */
1385
+ stats = { parses: 0, cacheHits: 0 };
1386
+ constructor(options = {}) {
1387
+ this.grammars = options;
1388
+ }
1389
+ /**
1390
+ * Loads the grammars these files need, once per language per process,
1391
+ * downloading each one on first use.
1392
+ *
1393
+ * A grammar that will not load is remembered as unavailable rather than
1394
+ * retried per anchor, and never throws: an unobtainable WASM is a finding.
1395
+ */
1396
+ async prepare(files) {
1397
+ const wanted = /* @__PURE__ */ new Set();
1398
+ for (const file of files) {
1399
+ const language = languageForFile(file);
1400
+ if (language && !this.loaded.has(language)) wanted.add(language);
1401
+ }
1402
+ if (!wanted.size) return;
1403
+ if (!this.initialized) {
1404
+ try {
1405
+ await import_web_tree_sitter.Parser.init();
1406
+ this.parser = new import_web_tree_sitter.Parser();
1407
+ this.initialized = true;
1408
+ } catch {
1409
+ for (const language of wanted) this.loaded.set(language, null);
1410
+ return;
1411
+ }
1412
+ }
1413
+ const languages = [...wanted];
1414
+ const loaded = await mapLimit(
1415
+ languages,
1416
+ Math.min(DEFAULT_IO_CONCURRENCY, languages.length),
1417
+ (language) => this.load(language)
1418
+ );
1419
+ languages.forEach(
1420
+ (language, at) => this.loaded.set(language, loaded[at] ?? null)
1421
+ );
1422
+ }
1423
+ /**
1424
+ * An unobtainable grammar, one this runtime refuses, and a query that will
1425
+ * not compile are three faults with three repairs; all are reported through
1426
+ * the grammars module so every hint has one home.
1427
+ */
1428
+ async load(language) {
1429
+ let pack2;
1430
+ try {
1431
+ pack2 = await ensureGrammar(language, this.grammars);
1432
+ } catch {
1433
+ return null;
1434
+ }
1435
+ if (!pack2?.query) return null;
1436
+ let grammar;
1437
+ try {
1438
+ grammar = await import_web_tree_sitter.Language.load(pack2.wasm);
1439
+ } catch (error) {
1440
+ noteRejectedGrammar(language, why(error));
1441
+ return null;
1442
+ }
1443
+ try {
1444
+ return { language: grammar, query: new import_web_tree_sitter.Query(grammar, pack2.query) };
1445
+ } catch (error) {
1446
+ noteUncompilableQuery(language, why(error));
1447
+ return null;
1448
+ }
1449
+ }
1450
+ /**
1451
+ * Abstains on an extension with no grammar so the regex resolver gets a
1452
+ * turn; reports `resolver-unavailable` when the grammar exists in principle
1453
+ * but could not be loaded, because falling back there would silently trade a
1454
+ * precise span for a guessed one.
1455
+ */
1456
+ attempt(source, symbol, file) {
1457
+ const language = file ? languageForFile(file) : void 0;
1458
+ if (!language) return { kind: "abstain" };
1459
+ if (!this.loaded.has(language)) return { kind: "abstain" };
1460
+ const loaded = this.loaded.get(language);
1461
+ if (!loaded) return { kind: "unresolved", reason: "resolver-unavailable" };
1462
+ const parsed = this.parse(language, loaded, source);
1463
+ if (!parsed) return { kind: "unresolved", reason: "resolver-unavailable" };
1464
+ const wanted = symbol.split(".").filter(Boolean);
1465
+ if (!wanted.length)
1466
+ return { kind: "unresolved", reason: "symbol-not-found" };
1467
+ const matches3 = select(parsed, wanted);
1468
+ if (!matches3.length)
1469
+ return { kind: "unresolved", reason: "symbol-not-found" };
1470
+ if (matches3.length > 1)
1471
+ return { kind: "unresolved", reason: "symbol-ambiguous" };
1472
+ return { kind: "resolved", span: spanOf(matches3[0], source) };
1473
+ }
1474
+ resolve(source, symbol, file) {
1475
+ const attempt = this.attempt(source, symbol, file);
1476
+ return attempt.kind === "resolved" ? attempt.span : null;
1477
+ }
1478
+ /** Parsed trees are keyed by content hash, so an unchanged file parses once. */
1479
+ parse(language, loaded, source) {
1480
+ const key = `${language}:${(0, import_node_crypto2.createHash)("sha256").update(source).digest("hex")}`;
1481
+ const cached2 = this.trees.get(key);
1482
+ if (cached2) {
1483
+ this.stats.cacheHits += 1;
1484
+ return cached2;
1485
+ }
1486
+ const parser = this.parser;
1487
+ if (!parser) return null;
1488
+ let parsed;
1489
+ try {
1490
+ parser.setLanguage(loaded.language);
1491
+ const tree = parser.parse(source);
1492
+ if (!tree) return null;
1493
+ parsed = index(tree, loaded.query);
1494
+ } catch {
1495
+ return null;
1496
+ }
1497
+ this.stats.parses += 1;
1498
+ if (this.trees.size >= TREE_CACHE_LIMIT) {
1499
+ const oldest = this.trees.keys().next();
1500
+ if (!oldest.done) {
1501
+ this.trees.get(oldest.value)?.tree.delete();
1502
+ this.trees.delete(oldest.value);
1503
+ }
1504
+ }
1505
+ this.trees.set(key, parsed);
1506
+ return parsed;
1507
+ }
1508
+ /** Drops cached trees. Grammars stay loaded — they are immutable. */
1509
+ reset() {
1510
+ for (const parsed of this.trees.values()) parsed.tree.delete();
1511
+ this.trees.clear();
1512
+ this.stats.parses = 0;
1513
+ this.stats.cacheHits = 0;
1514
+ }
1515
+ };
1516
+ function why(error) {
1517
+ const text = error instanceof Error ? error.message : String(error);
1518
+ return text || "no reason given";
1519
+ }
1520
+
1521
+ // src/anchor-resolver/resolver.ts
998
1522
  var PARENT_SCOPE_LINES = 50;
999
1523
  var CLEAN_STATE = { blockComment: false, template: false };
1000
1524
  function stripLine(line, state) {
1001
1525
  let out = "";
1002
- let index = 0;
1526
+ let index2 = 0;
1003
1527
  let { blockComment, template } = state;
1004
- while (index < line.length) {
1005
- const char = line[index];
1006
- const next = line[index + 1];
1528
+ while (index2 < line.length) {
1529
+ const char = line[index2];
1530
+ const next = line[index2 + 1];
1007
1531
  if (blockComment) {
1008
1532
  if (char === "*" && next === "/") {
1009
1533
  blockComment = false;
1010
- index += 2;
1534
+ index2 += 2;
1011
1535
  continue;
1012
1536
  }
1013
- index += 1;
1537
+ index2 += 1;
1014
1538
  continue;
1015
1539
  }
1016
1540
  if (template) {
1017
1541
  if (char === "\\") {
1018
- index += 2;
1542
+ index2 += 2;
1019
1543
  continue;
1020
1544
  }
1021
1545
  if (char === "`") template = false;
1022
- index += 1;
1546
+ index2 += 1;
1023
1547
  continue;
1024
1548
  }
1025
1549
  if (char === "/" && next === "*") {
1026
1550
  blockComment = true;
1027
- index += 2;
1551
+ index2 += 2;
1028
1552
  continue;
1029
1553
  }
1030
1554
  if (char === "/" && next === "/") break;
1031
1555
  if (char === "`") {
1032
1556
  template = true;
1033
- index += 1;
1557
+ index2 += 1;
1034
1558
  continue;
1035
1559
  }
1036
1560
  if (char === "'" || char === '"') {
1037
1561
  const quote = char;
1038
- index += 1;
1039
- while (index < line.length) {
1040
- if (line[index] === "\\") {
1041
- index += 2;
1562
+ index2 += 1;
1563
+ while (index2 < line.length) {
1564
+ if (line[index2] === "\\") {
1565
+ index2 += 2;
1042
1566
  continue;
1043
1567
  }
1044
- if (line[index] === quote) {
1045
- index += 1;
1568
+ if (line[index2] === quote) {
1569
+ index2 += 1;
1046
1570
  break;
1047
1571
  }
1048
- index += 1;
1572
+ index2 += 1;
1049
1573
  }
1050
1574
  continue;
1051
1575
  }
1052
1576
  out += char;
1053
- index += 1;
1577
+ index2 += 1;
1054
1578
  }
1055
1579
  return { code: out, state: { blockComment, template } };
1056
1580
  }
@@ -1065,8 +1589,8 @@ function captureBraceBlock(lines, matchLine) {
1065
1589
  let depth = 0;
1066
1590
  let opened = false;
1067
1591
  let state = CLEAN_STATE;
1068
- for (let index = matchLine; index < lines.length; index++) {
1069
- const stripped = stripLine(lines[index] ?? "", state);
1592
+ for (let index2 = matchLine; index2 < lines.length; index2++) {
1593
+ const stripped = stripLine(lines[index2] ?? "", state);
1070
1594
  state = stripped.state;
1071
1595
  for (const char of stripped.code) {
1072
1596
  if (char === "{") {
@@ -1075,10 +1599,10 @@ function captureBraceBlock(lines, matchLine) {
1075
1599
  } else if (char === "}") {
1076
1600
  depth = Math.max(0, depth - 1);
1077
1601
  } else if (char === ";" && !opened) {
1078
- return span(lines, matchLine, index);
1602
+ return span(lines, matchLine, index2);
1079
1603
  }
1080
1604
  }
1081
- if (opened && depth === 0) return span(lines, matchLine, index);
1605
+ if (opened && depth === 0) return span(lines, matchLine, index2);
1082
1606
  }
1083
1607
  return null;
1084
1608
  }
@@ -1087,22 +1611,22 @@ function captureIndentedBlock(lines, matchLine) {
1087
1611
  const header = lines[matchLine] ?? "";
1088
1612
  const indent = header.length - header.trimStart().length;
1089
1613
  let headerEnd = -1;
1090
- for (let index = matchLine; index < lines.length && index <= matchLine + 20; index++) {
1091
- const code = stripLine(lines[index] ?? "", CLEAN_STATE).code.trimEnd();
1614
+ for (let index2 = matchLine; index2 < lines.length && index2 <= matchLine + 20; index2++) {
1615
+ const code = stripLine(lines[index2] ?? "", CLEAN_STATE).code.trimEnd();
1092
1616
  if (code.endsWith(":")) {
1093
- headerEnd = index;
1617
+ headerEnd = index2;
1094
1618
  break;
1095
1619
  }
1096
- if (code.includes(":")) return span(lines, matchLine, index);
1620
+ if (code.includes(":")) return span(lines, matchLine, index2);
1097
1621
  }
1098
1622
  if (headerEnd === -1) return null;
1099
1623
  let end = headerEnd;
1100
- for (let index = headerEnd + 1; index < lines.length; index++) {
1101
- const line = lines[index] ?? "";
1624
+ for (let index2 = headerEnd + 1; index2 < lines.length; index2++) {
1625
+ const line = lines[index2] ?? "";
1102
1626
  if (line.trim() === "") continue;
1103
1627
  const lineIndent = line.length - line.trimStart().length;
1104
1628
  if (lineIndent <= indent) break;
1105
- end = index;
1629
+ end = index2;
1106
1630
  }
1107
1631
  return end === headerEnd ? null : span(lines, matchLine, end);
1108
1632
  }
@@ -1126,11 +1650,11 @@ var regexResolver = {
1126
1650
  const lines = source.split("\n");
1127
1651
  for (const tier of TIERS) {
1128
1652
  const pattern = tier(escaped);
1129
- let candidates = lines.map((line, index) => ({ line, index })).filter((entry) => pattern.test(entry.line)).map((entry) => entry.index);
1653
+ let candidates = lines.map((line, index2) => ({ line, index: index2 })).filter((entry) => pattern.test(entry.line)).map((entry) => entry.index);
1130
1654
  if (!candidates.length) continue;
1131
1655
  if (parentPattern && candidates.length > 1) {
1132
1656
  const distances = candidates.map(
1133
- (index) => distanceToParent(lines, index, parentPattern)
1657
+ (index2) => distanceToParent(lines, index2, parentPattern)
1134
1658
  );
1135
1659
  const nearest = Math.min(...distances);
1136
1660
  if (Number.isFinite(nearest)) {
@@ -1147,34 +1671,75 @@ var regexResolver = {
1147
1671
  function escapeRegExp(value) {
1148
1672
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1149
1673
  }
1150
- function distanceToParent(lines, index, parent) {
1151
- const floor = Math.max(0, index - PARENT_SCOPE_LINES);
1152
- for (let at = index; at >= floor; at--) {
1153
- if (parent.test(lines[at] ?? "")) return index - at;
1674
+ function distanceToParent(lines, index2, parent) {
1675
+ 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;
1154
1678
  }
1155
1679
  return Number.POSITIVE_INFINITY;
1156
1680
  }
1157
1681
  function hashAnchorText(text) {
1158
- return `sha256:${(0, import_node_crypto.createHash)("sha256").update(text.replace(/\r\n/g, "\n")).digest("hex")}`;
1682
+ return `sha256:${(0, import_node_crypto3.createHash)("sha256").update(text.replace(/\r\n/g, "\n")).digest("hex")}`;
1159
1683
  }
1160
- function resolveAnchor(source, anchor, resolver = regexResolver) {
1684
+ function resolveAnchorSpan(source, anchor, resolvers = [regexResolver]) {
1161
1685
  const normalized = source.replace(/\r\n/g, "\n");
1162
1686
  if (!anchor.symbol) {
1163
1687
  const lines = normalized.split("\n");
1164
1688
  if (lines.length > 1 && lines[lines.length - 1] === "") lines.pop();
1165
1689
  return {
1166
- text: normalized,
1167
- startLine: 1,
1168
- endLine: Math.max(1, lines.length)
1690
+ ok: true,
1691
+ span: {
1692
+ text: normalized,
1693
+ startLine: 1,
1694
+ endLine: Math.max(1, lines.length)
1695
+ }
1169
1696
  };
1170
1697
  }
1171
- return resolver.resolve(normalized, anchor.symbol);
1698
+ for (const resolver of resolvers) {
1699
+ const attempt = resolver.attempt ? resolver.attempt(normalized, anchor.symbol, anchor.file) : fromResolve(resolver, normalized, anchor.symbol, anchor.file);
1700
+ if (attempt.kind === "abstain") continue;
1701
+ if (attempt.kind === "unresolved") {
1702
+ if (attempt.reason === "symbol-not-found") continue;
1703
+ return { ok: false, reason: attempt.reason };
1704
+ }
1705
+ return {
1706
+ ok: true,
1707
+ span: attempt.span,
1708
+ ...isResolverName(resolver.name) ? { resolver: resolver.name } : {}
1709
+ };
1710
+ }
1711
+ return { ok: false, reason: "symbol-not-found" };
1712
+ }
1713
+ function fromResolve(resolver, source, symbol, file) {
1714
+ const span2 = resolver.resolve(source, symbol, file);
1715
+ return span2 ? { kind: "resolved", span: span2 } : { kind: "unresolved", reason: "symbol-not-found" };
1716
+ }
1717
+ function isResolverName(name) {
1718
+ return name === "tree-sitter" || name === "regex";
1719
+ }
1720
+ async function prepareResolvers(resolvers, files) {
1721
+ for (const resolver of resolvers) await resolver.prepare?.(files);
1722
+ }
1723
+ function defaultAnchorResolvers(grammars = {}) {
1724
+ return [new TreeSitterResolver(grammars), regexResolver];
1725
+ }
1726
+ function resolverChanged(source, anchor, produced) {
1727
+ const previous = anchor.resolver ?? "regex";
1728
+ if (!produced || !anchor.symbol || previous === produced) return false;
1729
+ if (previous !== "regex") return false;
1730
+ const before = regexResolver.resolve(
1731
+ source.replace(/\r\n/g, "\n"),
1732
+ anchor.symbol
1733
+ );
1734
+ return before !== null && hashAnchorText(before.text) === anchor.hash;
1172
1735
  }
1173
1736
 
1174
1737
  // src/anchor-resolver/drift.ts
1175
1738
  async function detectAnchorDrift(records, options = {}) {
1176
1739
  const repoRoot = options.repoRoot ?? process.cwd();
1177
- const resolver = options.resolver ?? regexResolver;
1740
+ const resolvers = options.resolvers ?? (options.resolver ? [options.resolver] : defaultAnchorResolvers({
1741
+ offline: options.remote?.offline === true
1742
+ }));
1178
1743
  const origin = new LazyOrigin(repoRoot);
1179
1744
  const planned = /* @__PURE__ */ new Map();
1180
1745
  let declaresRepo = false;
@@ -1212,12 +1777,16 @@ async function detectAnchorDrift(records, options = {}) {
1212
1777
  ),
1213
1778
  (options.readRemote ?? readRemoteAnchors)(wants, options.remote ?? {})
1214
1779
  ]);
1780
+ await prepareResolvers(resolvers, [
1781
+ ...files,
1782
+ ...wants.map((want) => want.file)
1783
+ ]);
1215
1784
  const drift = /* @__PURE__ */ new Map();
1216
1785
  for (const record of records) {
1217
1786
  const entries = [];
1218
1787
  for (const { anchor, foreign } of planned.get(record.conceptId) ?? []) {
1219
1788
  entries.push(
1220
- foreign ? remoteEntry(anchor, remote, resolver) : localEntry(anchor, reads.get(anchor.file), resolver)
1789
+ foreign ? remoteEntry(anchor, remote, resolvers) : localEntry(anchor, reads.get(anchor.file), resolvers)
1221
1790
  );
1222
1791
  }
1223
1792
  if (entries.length) drift.set(record.conceptId, entries);
@@ -1246,12 +1815,22 @@ function unresolved(anchor, reason, repo) {
1246
1815
  ...repo ? { repo } : {}
1247
1816
  };
1248
1817
  }
1249
- function hashIn(source, anchor, resolver) {
1250
- const resolved = resolveAnchor(source, anchor, resolver);
1251
- if (!resolved) return null;
1818
+ function hashIn(source, anchor, resolvers) {
1819
+ const outcome = resolveAnchorSpan(source, anchor, resolvers);
1820
+ if (!outcome.ok) return { ok: false, reason: outcome.reason };
1252
1821
  return {
1253
- hash: hashAnchorText(resolved.text),
1254
- lines: resolved.endLine - resolved.startLine + 1
1822
+ ok: true,
1823
+ current: {
1824
+ hash: hashAnchorText(outcome.span.text),
1825
+ lines: outcome.span.endLine - outcome.span.startLine + 1,
1826
+ ...outcome.resolver ? { resolver: outcome.resolver } : {}
1827
+ }
1828
+ };
1829
+ }
1830
+ function resolverExtras(source, anchor, current) {
1831
+ return {
1832
+ ...current.resolver ? { resolver: current.resolver } : {},
1833
+ ...current.hash !== anchor.hash && resolverChanged(source, anchor, current.resolver) ? { reason: "resolver-changed" } : {}
1255
1834
  };
1256
1835
  }
1257
1836
  function compared(anchor, current, extra = {}) {
@@ -1263,30 +1842,48 @@ function compared(anchor, current, extra = {}) {
1263
1842
  ...extra
1264
1843
  };
1265
1844
  }
1266
- function localEntry(anchor, read, resolver) {
1845
+ function localEntry(anchor, read, resolvers) {
1267
1846
  if (!read.ok) return unresolved(anchor, read.reason);
1268
- const current = hashIn(read.source, anchor, resolver);
1269
- return current ? compared(anchor, current) : unresolved(anchor, "symbol-not-found");
1847
+ const found = hashIn(read.source, anchor, resolvers);
1848
+ if (!found.ok) return unresolved(anchor, found.reason);
1849
+ return compared(
1850
+ anchor,
1851
+ found.current,
1852
+ resolverExtras(read.source, anchor, found.current)
1853
+ );
1270
1854
  }
1271
- function remoteEntry(anchor, remote, resolver) {
1855
+ function remoteEntry(anchor, remote, resolvers) {
1272
1856
  const repo = anchor.repo;
1273
1857
  const key = normalizeRepoUrl(repo);
1274
1858
  const atDefault = remote.get(wantKey(key, void 0, anchor.file));
1275
1859
  const primary = anchor.ref ? remote.get(wantKey(key, anchor.ref, anchor.file)) : atDefault;
1276
1860
  if (!primary) return unresolved(anchor, "remote-unreachable", repo);
1277
1861
  if (!primary.ok) return unresolved(anchor, primary.reason, repo);
1278
- const current = hashIn(primary.source, anchor, resolver);
1279
- if (!current) return unresolved(anchor, "symbol-not-found", repo);
1280
- if (!anchor.ref) return compared(anchor, current, { repo });
1862
+ const found = hashIn(primary.source, anchor, resolvers);
1863
+ if (!found.ok) return unresolved(anchor, found.reason, repo);
1864
+ const current = found.current;
1865
+ const extras = resolverExtras(primary.source, anchor, current);
1866
+ if (!anchor.ref) return compared(anchor, current, { repo, ...extras });
1281
1867
  if (current.hash !== anchor.hash) {
1282
- return compared(anchor, current, { repo, remoteState: "drifted-from-ref" });
1868
+ return compared(anchor, current, {
1869
+ repo,
1870
+ ...extras,
1871
+ remoteState: "drifted-from-ref"
1872
+ });
1283
1873
  }
1284
- const head = atDefault?.ok ? hashIn(atDefault.source, anchor, resolver) : null;
1285
- return head && head.hash !== anchor.hash ? {
1286
- ...compared(anchor, head, { repo }),
1874
+ const head = atDefault?.ok ? hashIn(atDefault.source, anchor, resolvers) : null;
1875
+ return head?.ok && head.current.hash !== anchor.hash ? {
1876
+ ...compared(anchor, head.current, {
1877
+ repo,
1878
+ ...head.current.resolver ? { resolver: head.current.resolver } : {}
1879
+ }),
1287
1880
  state: "drifted",
1288
1881
  remoteState: "drifted-on-default"
1289
- } : compared(anchor, current, { repo, remoteState: "matches-ref" });
1882
+ } : compared(anchor, current, {
1883
+ repo,
1884
+ ...extras,
1885
+ remoteState: "matches-ref"
1886
+ });
1290
1887
  }
1291
1888
 
1292
1889
  // src/errors.ts
@@ -1474,9 +2071,9 @@ var KbStampDigestBaselineError = class extends BaseError {
1474
2071
  // src/kb-pins/budgets.ts
1475
2072
  function asBudgets(value) {
1476
2073
  if (value === null || typeof value !== "object") return {};
1477
- const table = value;
2074
+ const table2 = value;
1478
2075
  const pick = (key, min) => {
1479
- const raw = table[key];
2076
+ const raw = table2[key];
1480
2077
  return typeof raw === "number" && Number.isInteger(raw) && raw >= min ? raw : void 0;
1481
2078
  };
1482
2079
  const budgetTokens = pick("budgetTokens", 1);
@@ -1487,9 +2084,9 @@ function asBudgets(value) {
1487
2084
  };
1488
2085
  }
1489
2086
  function contextProfileBudgets(manifest, profile) {
1490
- const table = manifest.context;
1491
- if (table === null || typeof table !== "object") return {};
1492
- const entries = table;
2087
+ const table2 = manifest.context;
2088
+ if (table2 === null || typeof table2 !== "object") return {};
2089
+ const entries = table2;
1493
2090
  return {
1494
2091
  ...asBudgets(entries["default"]),
1495
2092
  ...profile ? asBudgets(entries[profile]) : {}
@@ -1520,23 +2117,23 @@ var KbBaseFrozenError = class extends Error {
1520
2117
  };
1521
2118
 
1522
2119
  // src/kb-pins/frozen.ts
1523
- var import_node_path5 = require("path");
2120
+ var import_node_path8 = require("path");
1524
2121
 
1525
2122
  // src/kb-pins/layers.ts
1526
- var import_promises3 = require("fs/promises");
1527
- var import_node_os2 = require("os");
1528
- var import_node_path4 = require("path");
2123
+ var import_promises5 = require("fs/promises");
2124
+ var import_node_os3 = require("os");
2125
+ var import_node_path7 = require("path");
1529
2126
 
1530
2127
  // src/kb-pins/model.ts
1531
- var import_node_path3 = require("path");
1532
- var import_zod4 = require("zod");
1533
- var PINS_FILE = (0, import_node_path3.join)(".strauss", "kb-pins.json");
1534
- var PINS_LOCAL_FILE = (0, import_node_path3.join)(".strauss", "kb-pins.local.json");
2128
+ var import_node_path6 = require("path");
2129
+ var import_zod5 = require("zod");
2130
+ var PINS_FILE = (0, import_node_path6.join)(".strauss", "kb-pins.json");
2131
+ var PINS_LOCAL_FILE = (0, import_node_path6.join)(".strauss", "kb-pins.local.json");
1535
2132
  var PIN_LAYERS = ["project", "local", "user"];
1536
- var pinSchema = import_zod4.z.object({
2133
+ var pinSchema = import_zod5.z.object({
1537
2134
  /** Relative to the manifest's root, so the file is committable. */
1538
- path: import_zod4.z.string().min(1),
1539
- pinnedAt: import_zod4.z.string().min(1).optional(),
2135
+ path: import_zod5.z.string().min(1),
2136
+ pinnedAt: import_zod5.z.string().min(1).optional(),
1540
2137
  /**
1541
2138
  * How `context` renders this base. `full` preloads the whole base into
1542
2139
  * the block regardless of the full-under threshold — for a base whose
@@ -1546,7 +2143,7 @@ var pinSchema = import_zod4.z.object({
1546
2143
  * Absent: the profile's full-under threshold decides. Invalid values
1547
2144
  * degrade to absent rather than failing the manifest.
1548
2145
  */
1549
- mode: import_zod4.z.enum(["full", "index"]).optional().catch(void 0),
2146
+ mode: import_zod5.z.enum(["full", "index"]).optional().catch(void 0),
1550
2147
  /**
1551
2148
  * Context profiles this pin surfaces in (e.g. only at session-start,
1552
2149
  * not per turn). Absent: every profile. A run without a profile sees
@@ -1554,17 +2151,17 @@ var pinSchema = import_zod4.z.object({
1554
2151
  * that skill at point of use than pinned at all — pins are what every
1555
2152
  * session should see.
1556
2153
  */
1557
- profiles: import_zod4.z.array(import_zod4.z.string()).optional().catch(void 0),
2154
+ profiles: import_zod5.z.array(import_zod5.z.string()).optional().catch(void 0),
1558
2155
  /**
1559
2156
  * The base is concluded — a finished piece of research, a frozen ADR
1560
2157
  * set. Write commands against it refuse while this workspace holds the
1561
2158
  * pin, and `context` labels it read-only. Workspace policy, not base
1562
2159
  * state: the base itself stays copyable and writable elsewhere.
1563
2160
  */
1564
- frozen: import_zod4.z.boolean().optional().catch(void 0)
2161
+ frozen: import_zod5.z.boolean().optional().catch(void 0)
1565
2162
  }).passthrough();
1566
- var pinsManifestSchema = import_zod4.z.object({
1567
- pins: import_zod4.z.array(pinSchema).default([]),
2163
+ var pinsManifestSchema = import_zod5.z.object({
2164
+ pins: import_zod5.z.array(pinSchema).default([]),
1568
2165
  /**
1569
2166
  * Per-repo budgets for the `context` command, keyed by profile —
1570
2167
  * `"session-start"`, `"compact"`, `"turn"`, or `"default"` for all of
@@ -1573,18 +2170,18 @@ var pinsManifestSchema = import_zod4.z.object({
1573
2170
  * the index at every session start. `contextProfileBudgets` does the
1574
2171
  * tolerant read.
1575
2172
  */
1576
- context: import_zod4.z.unknown().optional()
2173
+ context: import_zod5.z.unknown().optional()
1577
2174
  }).passthrough();
1578
2175
 
1579
2176
  // src/kb-pins/layers.ts
1580
2177
  function userRoot() {
1581
- return process.env.STRAUSS_KB_USER_ROOT || (0, import_node_os2.homedir)();
2178
+ return process.env.STRAUSS_KB_USER_ROOT || (0, import_node_os3.homedir)();
1582
2179
  }
1583
2180
  function layerRoot(workspaceDir, layer) {
1584
- return layer === "user" ? userRoot() : (0, import_node_path4.resolve)(workspaceDir);
2181
+ return layer === "user" ? userRoot() : (0, import_node_path7.resolve)(workspaceDir);
1585
2182
  }
1586
2183
  function layerFile(workspaceDir, layer) {
1587
- return (0, import_node_path4.join)(
2184
+ return (0, import_node_path7.join)(
1588
2185
  layerRoot(workspaceDir, layer),
1589
2186
  layer === "local" ? PINS_LOCAL_FILE : PINS_FILE
1590
2187
  );
@@ -1593,7 +2190,7 @@ async function readPinsLayer(workspaceDir, layer) {
1593
2190
  const file = layerFile(workspaceDir, layer);
1594
2191
  let raw;
1595
2192
  try {
1596
- raw = await (0, import_promises3.readFile)(file, "utf8");
2193
+ raw = await (0, import_promises5.readFile)(file, "utf8");
1597
2194
  } catch {
1598
2195
  return { pins: [] };
1599
2196
  }
@@ -1617,16 +2214,16 @@ async function readPinsLayer(workspaceDir, layer) {
1617
2214
  }
1618
2215
  async function writePinsLayer(workspaceDir, layer, manifest) {
1619
2216
  const file = layerFile(workspaceDir, layer);
1620
- await (0, import_promises3.mkdir)((0, import_node_path4.dirname)(file), { recursive: true });
1621
- await (0, import_promises3.writeFile)(file, `${JSON.stringify(manifest, null, 2)}
2217
+ await (0, import_promises5.mkdir)((0, import_node_path7.dirname)(file), { recursive: true });
2218
+ await (0, import_promises5.writeFile)(file, `${JSON.stringify(manifest, null, 2)}
1622
2219
  `, "utf8");
1623
2220
  }
1624
2221
  function resolvePinPath(rootDir, path) {
1625
- return (0, import_node_path4.isAbsolute)(path) ? (0, import_node_path4.resolve)(path) : (0, import_node_path4.resolve)(rootDir, path.split("/").join(import_node_path4.sep));
2222
+ return (0, import_node_path7.isAbsolute)(path) ? (0, import_node_path7.resolve)(path) : (0, import_node_path7.resolve)(rootDir, path.split("/").join(import_node_path7.sep));
1626
2223
  }
1627
2224
  function storablePath(rootDir, bundlePath2) {
1628
- const rel = (0, import_node_path4.relative)((0, import_node_path4.resolve)(rootDir), (0, import_node_path4.resolve)(bundlePath2));
1629
- return (rel === "" ? "." : rel).split(import_node_path4.sep).join("/");
2225
+ const rel = (0, import_node_path7.relative)((0, import_node_path7.resolve)(rootDir), (0, import_node_path7.resolve)(bundlePath2));
2226
+ return (rel === "" ? "." : rel).split(import_node_path7.sep).join("/");
1630
2227
  }
1631
2228
  async function readMergedPins(workspaceDir) {
1632
2229
  const manifests = {};
@@ -1654,7 +2251,7 @@ async function readMergedPins(workspaceDir) {
1654
2251
  // src/kb-pins/frozen.ts
1655
2252
  async function assertBaseNotFrozen(workspaceDir, bundlePath2) {
1656
2253
  const merged = await readMergedPins(workspaceDir);
1657
- const absolute = (0, import_node_path5.resolve)(bundlePath2);
2254
+ const absolute = (0, import_node_path8.resolve)(bundlePath2);
1658
2255
  const pin = merged.pins.find((entry) => entry.absolutePath === absolute);
1659
2256
  if (pin?.frozen === true) {
1660
2257
  throw new KbBaseFrozenError(pin.path, pin.layer);
@@ -1739,7 +2336,7 @@ async function pinBase(store, workspaceDir, bundlePath2, at, options = {}) {
1739
2336
  }
1740
2337
 
1741
2338
  // src/kb-pins/unpin.ts
1742
- var import_node_path6 = require("path");
2339
+ var import_node_path9 = require("path");
1743
2340
  async function unpinBase(workspaceDir, bundlePath2) {
1744
2341
  const layers = [];
1745
2342
  for (const layer of PIN_LAYERS) {
@@ -1760,17 +2357,17 @@ async function unpinBase(workspaceDir, bundlePath2) {
1760
2357
  }
1761
2358
  }
1762
2359
  return {
1763
- path: storablePath((0, import_node_path6.resolve)(workspaceDir), bundlePath2),
2360
+ path: storablePath((0, import_node_path9.resolve)(workspaceDir), bundlePath2),
1764
2361
  removed: layers.length > 0,
1765
2362
  layers
1766
2363
  };
1767
2364
  }
1768
2365
 
1769
2366
  // src/commands/model.ts
1770
- var import_zod5 = require("zod");
1771
- var bundlePath = import_zod5.z.string().min(1).describe("Absolute path to the knowledge base directory.");
1772
- var conceptId = import_zod5.z.string().min(1).describe("e.g. decision.cursor-v2");
1773
- var REPO_ROOT = import_zod5.z.string().min(1).optional().describe(
2367
+ var import_zod6 = require("zod");
2368
+ var bundlePath = import_zod6.z.string().min(1).describe("Absolute path to the knowledge base directory.");
2369
+ var conceptId = import_zod6.z.string().min(1).describe("e.g. decision.cursor-v2");
2370
+ var REPO_ROOT = import_zod6.z.string().min(1).optional().describe(
1774
2371
  "Where the anchored source lives, for the drift check. Defaults to the working directory."
1775
2372
  );
1776
2373
  function define(command) {
@@ -1793,22 +2390,30 @@ function argvFlag(argv, name) {
1793
2390
  }
1794
2391
 
1795
2392
  // src/commands/anchor-resolve.ts
2393
+ function resolverSummary(results) {
2394
+ const names = [
2395
+ ...new Set(
2396
+ results.flatMap((entry) => entry.resolver ? [entry.resolver] : [])
2397
+ )
2398
+ ].sort();
2399
+ return names.length ? `${names.join(" + ")} resolver` : "whole-file";
2400
+ }
1796
2401
  var anchorResolveCommand = define({
1797
2402
  name: "anchor-resolve",
1798
2403
  tool: "kb_anchor_resolve",
1799
2404
  usage: "anchor-resolve <concept-id> [--repo-root <path>] [--offline] [--rebaseline] [--restamp]",
1800
2405
  description: "Resolve a record's anchors: stamp a hash onto anchors that lack one, report drift where the code moved. An anchor naming another repository is read from that remote through a bare cache; --offline uses the cache only. kb_verify's mechanical counterpart \u2014 reach for it when the question is whether the code still is what it was. Exits non-zero on drift.",
1801
- input: import_zod6.z.object({
2406
+ input: import_zod7.z.object({
1802
2407
  bundlePath,
1803
2408
  conceptId,
1804
- repoRoot: import_zod6.z.string().min(1).optional(),
1805
- offline: import_zod6.z.boolean().optional().describe(
2409
+ repoRoot: import_zod7.z.string().min(1).optional(),
2410
+ offline: import_zod7.z.boolean().optional().describe(
1806
2411
  "Resolve foreign anchors from the local repo cache only, never fetching."
1807
2412
  ),
1808
- rebaseline: import_zod6.z.boolean().optional().describe(
2413
+ rebaseline: import_zod7.z.boolean().optional().describe(
1809
2414
  "Accept the current code as the new baseline for anchors that drifted."
1810
2415
  ),
1811
- restamp: import_zod6.z.boolean().optional().describe(
2416
+ restamp: import_zod7.z.boolean().optional().describe(
1812
2417
  "Refresh `resolved_at` on anchors that already match. Off by default, so a green run writes nothing."
1813
2418
  )
1814
2419
  }),
@@ -1837,6 +2442,11 @@ var anchorResolveCommand = define({
1837
2442
  const updated = [];
1838
2443
  let dirty = false;
1839
2444
  const sources = await readSources(anchors, root, offline === true);
2445
+ const resolvers = defaultAnchorResolvers({ offline: offline === true });
2446
+ await prepareResolvers(
2447
+ resolvers,
2448
+ anchors.map((anchor) => anchor.file)
2449
+ );
1840
2450
  for (const anchor of anchors) {
1841
2451
  const base2 = {
1842
2452
  file: anchor.file,
@@ -1853,27 +2463,35 @@ var anchorResolveCommand = define({
1853
2463
  updated.push(anchor);
1854
2464
  continue;
1855
2465
  }
1856
- const resolved = resolveAnchor(source.source, anchor);
1857
- if (!resolved) {
2466
+ const outcome = resolveAnchorSpan(source.source, anchor, resolvers);
2467
+ if (!outcome.ok) {
1858
2468
  results.push({
1859
2469
  ...base2,
1860
2470
  state: "unresolved",
1861
- reason: "symbol-not-found"
2471
+ reason: outcome.reason
1862
2472
  });
1863
2473
  updated.push(anchor);
1864
2474
  continue;
1865
2475
  }
2476
+ const resolved = outcome.span;
2477
+ const producedBy = outcome.resolver;
1866
2478
  const currentHash = hashAnchorText(resolved.text);
1867
2479
  const currentLines = resolved.endLine - resolved.startLine + 1;
1868
2480
  const stamped = {
1869
2481
  ...anchor,
1870
2482
  hash: currentHash,
1871
2483
  lines: currentLines,
1872
- resolved_at: now()
2484
+ resolved_at: now(),
2485
+ ...producedBy ? { resolver: producedBy } : {}
1873
2486
  };
1874
2487
  const pinned = anchor.ref !== void 0 && source.repo !== void 0;
1875
2488
  if (!anchor.hash) {
1876
- results.push({ ...base2, state: "stamped", currentHash });
2489
+ results.push({
2490
+ ...base2,
2491
+ state: "stamped",
2492
+ currentHash,
2493
+ ...producedBy ? { resolver: producedBy } : {}
2494
+ });
1877
2495
  updated.push(stamped);
1878
2496
  dirty = true;
1879
2497
  continue;
@@ -1884,6 +2502,10 @@ var anchorResolveCommand = define({
1884
2502
  state: "drifted",
1885
2503
  currentHash,
1886
2504
  diffSize: lineDelta(anchor, currentLines),
2505
+ ...producedBy ? { resolver: producedBy } : {},
2506
+ // A regex-stamped anchor re-read by tree-sitter drifts because the
2507
+ // resolver changed, not because the code did.
2508
+ ...resolverChanged(source.source, anchor, producedBy) ? { reason: "resolver-changed" } : {},
1887
2509
  ...pinned ? { remoteState: "drifted-from-ref" } : {},
1888
2510
  ...rebaseline ? { rebaselined: true } : {}
1889
2511
  });
@@ -1891,7 +2513,7 @@ var anchorResolveCommand = define({
1891
2513
  if (rebaseline) dirty = true;
1892
2514
  continue;
1893
2515
  }
1894
- const onDefault = pinned ? headHash(source, anchor) : void 0;
2516
+ const onDefault = pinned ? headHash(source, anchor, resolvers) : void 0;
1895
2517
  if (onDefault && onDefault.hash !== anchor.hash) {
1896
2518
  results.push({
1897
2519
  ...base2,
@@ -1907,6 +2529,7 @@ var anchorResolveCommand = define({
1907
2529
  ...base2,
1908
2530
  state: "match",
1909
2531
  currentHash,
2532
+ ...producedBy ? { resolver: producedBy } : {},
1910
2533
  ...pinned ? { remoteState: "matches-ref" } : {}
1911
2534
  });
1912
2535
  const refresh = restamp || anchor.resolved_at === void 0;
@@ -1924,19 +2547,21 @@ var anchorResolveCommand = define({
1924
2547
  if (!frozen) await store.updateAnchors(path, id, updated, actor);
1925
2548
  }
1926
2549
  const frozenNote = frozen ? { frozen: true, note: "base is frozen: nothing was stamped" } : {};
2550
+ const hints = grammarHints();
2551
+ const hintNote = hints.length ? { hints } : {};
1927
2552
  const unreachable = results.filter(
1928
2553
  (entry) => isUncheckedReason(entry.reason)
1929
2554
  ).length;
1930
2555
  const checked = results.length - unreachable;
1931
- const matches2 = results.filter((entry) => entry.state === "match").length;
1932
- const note = `${matches2}/${checked} anchors match${unreachable ? `, ${unreachable} unreachable` : ""}`;
1933
- const clean = checked > 0 && matches2 === checked && unreachable === 0;
2556
+ const matches3 = results.filter((entry) => entry.state === "match").length;
2557
+ const note = `${matches3}/${checked} anchors match${unreachable ? `, ${unreachable} unreachable` : ""}`;
2558
+ const clean = checked > 0 && matches3 === checked && unreachable === 0;
1934
2559
  if (clean) {
1935
2560
  try {
1936
2561
  await store.verify(
1937
2562
  path,
1938
2563
  id,
1939
- `anchor-resolve: ${note} (regex resolver)`,
2564
+ `anchor-resolve: ${note} (${resolverSummary(results)})`,
1940
2565
  actor,
1941
2566
  now()
1942
2567
  );
@@ -1947,17 +2572,25 @@ var anchorResolveCommand = define({
1947
2572
  results,
1948
2573
  verified: false,
1949
2574
  verifyRefused: "self-verification",
1950
- ...frozenNote
2575
+ ...frozenNote,
2576
+ ...hintNote
1951
2577
  };
1952
2578
  }
1953
- return { conceptId: id, results, verified: true, ...frozenNote };
2579
+ return {
2580
+ conceptId: id,
2581
+ results,
2582
+ verified: true,
2583
+ ...frozenNote,
2584
+ ...hintNote
2585
+ };
1954
2586
  }
1955
2587
  return {
1956
2588
  conceptId: id,
1957
2589
  results,
1958
2590
  verified: false,
1959
2591
  ...unreachable ? { note } : {},
1960
- ...frozenNote
2592
+ ...frozenNote,
2593
+ ...hintNote
1961
2594
  };
1962
2595
  },
1963
2596
  // A stored hash that no longer resolves is a broken anchor, not an absence:
@@ -1973,13 +2606,13 @@ var anchorResolveCommand = define({
1973
2606
  function lineDelta(anchor, current) {
1974
2607
  return anchor.lines === void 0 ? null : Math.abs(current - anchor.lines);
1975
2608
  }
1976
- function headHash(source, anchor) {
2609
+ function headHash(source, anchor, resolvers) {
1977
2610
  if (source.head === void 0) return void 0;
1978
- const resolved = resolveAnchor(source.head, anchor);
1979
- if (!resolved) return void 0;
2611
+ const outcome = resolveAnchorSpan(source.head, anchor, resolvers);
2612
+ if (!outcome.ok) return void 0;
1980
2613
  return {
1981
- hash: hashAnchorText(resolved.text),
1982
- lines: resolved.endLine - resolved.startLine + 1
2614
+ hash: hashAnchorText(outcome.span.text),
2615
+ lines: outcome.span.endLine - outcome.span.startLine + 1
1983
2616
  };
1984
2617
  }
1985
2618
  async function readSources(anchors, root, offline) {
@@ -2029,13 +2662,13 @@ async function readSources(anchors, root, offline) {
2029
2662
  }
2030
2663
 
2031
2664
  // src/commands/answer.ts
2032
- var import_zod7 = require("zod");
2665
+ var import_zod8 = require("zod");
2033
2666
  var answerCommand = define({
2034
2667
  name: "answer",
2035
2668
  tool: "kb_answer",
2036
2669
  usage: "answer <concept-id> <answer...>",
2037
2670
  description: "Resolve an open question: set status, stamp who and when, append an Answer section. If the answer overturns a decision or assumption, supersede that record explicitly.",
2038
- input: import_zod7.z.object({ bundlePath, conceptId, answer: import_zod7.z.string().min(1) }),
2671
+ input: import_zod8.z.object({ bundlePath, conceptId, answer: import_zod8.z.string().min(1) }),
2039
2672
  fromArgv: (argv, path) => ({
2040
2673
  bundlePath: path,
2041
2674
  conceptId: argv[1],
@@ -2049,19 +2682,19 @@ var answerCommand = define({
2049
2682
  });
2050
2683
 
2051
2684
  // src/commands/backlinks.ts
2052
- var import_zod8 = require("zod");
2685
+ var import_zod9 = require("zod");
2053
2686
  var backlinksCommand = define({
2054
2687
  name: "backlinks",
2055
2688
  tool: "kb_backlinks",
2056
2689
  usage: "backlinks <concept-id>",
2057
2690
  description: "Who points at this record: every inbound typed causal link (`strauss_links`), one hop, every rel including `related_to`, each with its rel and the standing of the record that made it. Use it when you need the exact edges \u2014 reviewing or renaming a record.",
2058
- input: import_zod8.z.object({ bundlePath, conceptId }),
2691
+ input: import_zod9.z.object({ bundlePath, conceptId }),
2059
2692
  fromArgv: (argv, path) => ({ bundlePath: path, conceptId: argv[1] }),
2060
2693
  run: async ({ store }, { bundlePath: path, conceptId: id }) => store.backlinks(path, id)
2061
2694
  });
2062
2695
 
2063
2696
  // src/commands/catalog.ts
2064
- var import_zod9 = require("zod");
2697
+ var import_zod10 = require("zod");
2065
2698
 
2066
2699
  // src/adjudicate.ts
2067
2700
  var STANDING = {
@@ -2139,8 +2772,8 @@ function resolveHeads(from, byId) {
2139
2772
  while (queue.length) {
2140
2773
  const current = queue.shift();
2141
2774
  const next = successors(current, byId);
2142
- for (const missing of next.missing) {
2143
- warnings.push({ kind: "broken-chain", missing });
2775
+ for (const missing2 of next.missing) {
2776
+ warnings.push({ kind: "broken-chain", missing: missing2 });
2144
2777
  }
2145
2778
  if (!next.records.length) {
2146
2779
  if (current.conceptId !== from.conceptId)
@@ -2171,13 +2804,13 @@ function successors(record, byId) {
2171
2804
  }
2172
2805
  }
2173
2806
  const records = [];
2174
- const missing = [];
2807
+ const missing2 = [];
2175
2808
  for (const id of ids) {
2176
2809
  const found = byId.get(id);
2177
2810
  if (found) records.push(found);
2178
- else missing.push(id);
2811
+ else missing2.push(id);
2179
2812
  }
2180
- return { records, missing };
2813
+ return { records, missing: missing2 };
2181
2814
  }
2182
2815
 
2183
2816
  // src/catalog.ts
@@ -2232,9 +2865,9 @@ var catalogCommand = define({
2232
2865
  tool: "kb_catalog",
2233
2866
  usage: "catalog [type]",
2234
2867
  description: "Lists every record as one line \u2014 concept id, type, title, standing, and a stale flag \u2014 at roughly thirty tokens each. Pick this over kb_load once kb_load refuses: kb_catalog never refuses. Superseded records show only their replacement; fetch bodies with kb_load, kb_pack, kb_query, or kb_trace.",
2235
- input: import_zod9.z.object({
2868
+ input: import_zod10.z.object({
2236
2869
  bundlePath,
2237
- type: import_zod9.z.enum(KB_RECORD_TYPES).optional()
2870
+ type: import_zod10.z.enum(KB_RECORD_TYPES).optional()
2238
2871
  }),
2239
2872
  fromArgv: (argv, path) => ({
2240
2873
  bundlePath: path,
@@ -2289,10 +2922,10 @@ function count(value, noun) {
2289
2922
  }
2290
2923
 
2291
2924
  // src/commands/context.ts
2292
- var import_zod10 = require("zod");
2925
+ var import_zod11 = require("zod");
2293
2926
 
2294
2927
  // src/kb-context.ts
2295
- var import_promises4 = require("fs/promises");
2928
+ var import_promises6 = require("fs/promises");
2296
2929
 
2297
2930
  // src/kb-index.ts
2298
2931
  var INDEX_FILE = "INDEX.md";
@@ -2519,13 +3152,13 @@ function toHookJson(block, event) {
2519
3152
  var CONTEXT_BEGIN = "<!-- strauss-kb:begin -->";
2520
3153
  var CONTEXT_END = "<!-- strauss-kb:end -->";
2521
3154
  async function syncInstructions(file, block) {
2522
- const existing = await (0, import_promises4.readFile)(file, "utf8").catch(() => null);
3155
+ const existing = await (0, import_promises6.readFile)(file, "utf8").catch(() => null);
2523
3156
  const region = block ? `${CONTEXT_BEGIN}
2524
3157
  ${block.trim()}
2525
3158
  ${CONTEXT_END}` : null;
2526
3159
  if (existing === null) {
2527
3160
  if (!region) return { file, action: "unchanged" };
2528
- await (0, import_promises4.writeFile)(file, `${region}
3161
+ await (0, import_promises6.writeFile)(file, `${region}
2529
3162
  `, "utf8");
2530
3163
  return { file, action: "created" };
2531
3164
  }
@@ -2536,11 +3169,11 @@ ${CONTEXT_END}` : null;
2536
3169
  const after = existing.slice(end + CONTEXT_END.length);
2537
3170
  const next = region ? `${before}${region}${after}` : `${before.replace(/\n+$/, "\n")}${after.replace(/^\n+/, "\n")}`;
2538
3171
  if (next === existing) return { file, action: "unchanged" };
2539
- await (0, import_promises4.writeFile)(file, next, "utf8");
3172
+ await (0, import_promises6.writeFile)(file, next, "utf8");
2540
3173
  return { file, action: region ? "replaced" : "removed" };
2541
3174
  }
2542
3175
  if (!region) return { file, action: "unchanged" };
2543
- await (0, import_promises4.writeFile)(
3176
+ await (0, import_promises6.writeFile)(
2544
3177
  file,
2545
3178
  `${existing.replace(/\n*$/, "\n\n")}${region}
2546
3179
  `,
@@ -2555,20 +3188,20 @@ var contextCommand = define({
2555
3188
  tool: "kb_context",
2556
3189
  usage: "context [--profile NAME] [--budget N] [--full-under N] [--format json] [--event NAME]",
2557
3190
  description: "Index block of pinned bases (ids, titles, standing) for injection at context birth. Takes no bundlePath \u2014 reads the workspace pin manifests. Empty when nothing is pinned; refuses over budget rather than truncating. Budget precedence: flags, then the manifest `context[profile]` over `context.default`, then the built-in profile, then package defaults.",
2558
- input: import_zod10.z.object({
2559
- budgetTokens: import_zod10.z.number().int().positive().optional().describe(
3191
+ input: import_zod11.z.object({
3192
+ budgetTokens: import_zod11.z.number().int().positive().optional().describe(
2560
3193
  "Ceiling on the whole emitted block; past it the command refuses with a list of bases rather than truncating. Defaults to 4000."
2561
3194
  ),
2562
- fullUnderTokens: import_zod10.z.number().int().positive().optional().describe(
3195
+ fullUnderTokens: import_zod11.z.number().int().positive().optional().describe(
2563
3196
  "Per-base rendering threshold, applied before the budget: a base whose complete load fits under this arrives as full records instead of index lines, and the whole block still answers to budgetTokens. Off by default \u2014 index-only is the safe default at a context birth, because injected bodies outlive the qualifiers on them; the session-start profile opts tiny bases in at 1500."
2564
3197
  ),
2565
- profile: import_zod10.z.string().optional().describe(
3198
+ profile: import_zod11.z.string().optional().describe(
2566
3199
  "Named budget set: built-ins are session-start (full-under 1500), compact and turn (budget 2500); the manifests' `context` tables override per repo. Unknown names fall through to defaults rather than failing."
2567
3200
  ),
2568
- format: import_zod10.z.enum(["markdown", "json"]).optional().describe(
3201
+ format: import_zod11.z.enum(["markdown", "json"]).optional().describe(
2569
3202
  "CLI envelope for hook protocols that require strict JSON on stdout. MCP callers omit this \u2014 the block itself is identical."
2570
3203
  ),
2571
- event: import_zod10.z.string().optional().describe(
3204
+ event: import_zod11.z.string().optional().describe(
2572
3205
  "hookEventName stamped into the JSON envelope. Only meaningful with format=json."
2573
3206
  )
2574
3207
  }),
@@ -2604,7 +3237,7 @@ var contextCommand = define({
2604
3237
  });
2605
3238
 
2606
3239
  // src/commands/doctor.ts
2607
- var import_zod11 = require("zod");
3240
+ var import_zod12 = require("zod");
2608
3241
 
2609
3242
  // src/kb-edges.ts
2610
3243
  var KB_EDGE_KINDS = [
@@ -2790,6 +3423,18 @@ var CHECK_HEADLINES = {
2790
3423
  unchecked: "an anchor in another repository nothing could reach"
2791
3424
  };
2792
3425
  var DAY_MS = 864e5;
3426
+ function anchorResolverCounts(bundle) {
3427
+ let treeSitter = 0;
3428
+ let regex = 0;
3429
+ for (const record of bundle) {
3430
+ for (const anchor of record.frontmatter.strauss_anchors ?? []) {
3431
+ if (!anchor.hash || !anchor.symbol) continue;
3432
+ if (anchor.resolver === "tree-sitter") treeSitter += 1;
3433
+ else regex += 1;
3434
+ }
3435
+ }
3436
+ return { total: treeSitter + regex, treeSitter, regex };
3437
+ }
2793
3438
  function doctor(bundle, options = {}) {
2794
3439
  const thresholds = {
2795
3440
  expiringDays: options.expiringDays ?? DEFAULT_EXPIRING_DAYS,
@@ -2825,6 +3470,7 @@ function doctor(bundle, options = {}) {
2825
3470
  counts,
2826
3471
  groups,
2827
3472
  findingCount,
3473
+ anchorResolvers: anchorResolverCounts(bundle),
2828
3474
  healthy: findingCount === 0
2829
3475
  };
2830
3476
  }
@@ -3071,13 +3717,13 @@ function ageInDays(record, now) {
3071
3717
  }
3072
3718
 
3073
3719
  // src/commands/doctor.ts
3074
- var days = (what, fallback) => import_zod11.z.number().int().positive().optional().describe(`${what} Defaults to ${fallback}.`);
3720
+ var days = (what, fallback) => import_zod12.z.number().int().positive().optional().describe(`${what} Defaults to ${fallback}.`);
3075
3721
  var doctorCommand = define({
3076
3722
  name: "doctor",
3077
3723
  tool: "kb_doctor",
3078
3724
  usage: "doctor [--expiring-days N] [--unverified-days N] [--aging-days N] [--repo-root PATH] [--offline] [--strict]",
3079
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.",
3080
- input: import_zod11.z.object({
3726
+ input: import_zod12.z.object({
3081
3727
  bundlePath,
3082
3728
  repoRoot: REPO_ROOT,
3083
3729
  expiringDays: days(
@@ -3092,10 +3738,10 @@ var doctorCommand = define({
3092
3738
  "How long a record may stay `open` or `proposed` before `aging` reports it, in days.",
3093
3739
  DEFAULT_AGING_DAYS
3094
3740
  ),
3095
- offline: import_zod11.z.boolean().optional().describe(
3741
+ offline: import_zod12.z.boolean().optional().describe(
3096
3742
  "Read foreign anchors from the local repo cache only, never fetching."
3097
3743
  ),
3098
- strict: import_zod11.z.boolean().optional().describe(
3744
+ strict: import_zod12.z.boolean().optional().describe(
3099
3745
  "Turn an expired record into a non-zero exit for the CLI. No effect on the report itself."
3100
3746
  )
3101
3747
  }),
@@ -3138,7 +3784,13 @@ var doctorCommand = define({
3138
3784
  ...anchorDrift !== void 0 ? { anchorDrift } : {},
3139
3785
  now: new Date(checkedAt)
3140
3786
  });
3141
- return { bundlePath: path, checkedAt, ...report };
3787
+ const hints = grammarHints();
3788
+ return {
3789
+ bundlePath: path,
3790
+ checkedAt,
3791
+ ...report,
3792
+ ...hints.length ? { hints } : {}
3793
+ };
3142
3794
  },
3143
3795
  render: (result) => render2(result),
3144
3796
  // Only expiry, and only under --strict. The other seven checks report debt a
@@ -3156,12 +3808,15 @@ function render2(result) {
3156
3808
  `records: ${result.recordCount}`,
3157
3809
  `thresholds: expiring within ${thresholds.expiringDays}d, unverified over ${thresholds.unverifiedDays}d, aging over ${thresholds.agingDays}d`,
3158
3810
  `checked: ${result.checkedAt}`,
3811
+ ...result.anchorResolvers.total ? [
3812
+ `anchors: ${result.anchorResolvers.total} hashed \u2014 ${result.anchorResolvers.treeSitter} tree-sitter, ${result.anchorResolvers.regex} regex`
3813
+ ] : [],
3159
3814
  ""
3160
3815
  ];
3161
- const width = Math.max(...result.groups.map((group2) => group2.check.length));
3816
+ const width2 = Math.max(...result.groups.map((group2) => group2.check.length));
3162
3817
  for (const group2 of result.groups) {
3163
3818
  lines.push(
3164
- ` ${group2.check.padEnd(width)} ${String(group2.count).padStart(3)} ${group2.headline}`
3819
+ ` ${group2.check.padEnd(width2)} ${String(group2.count).padStart(3)} ${group2.headline}`
3165
3820
  );
3166
3821
  }
3167
3822
  for (const group2 of result.groups) {
@@ -3173,6 +3828,7 @@ function render2(result) {
3173
3828
  );
3174
3829
  }
3175
3830
  }
3831
+ for (const hint of result.hints ?? []) lines.push("", hint);
3176
3832
  lines.push(
3177
3833
  "",
3178
3834
  result.healthy ? "Nothing to repair." : `${result.findingCount} finding${result.findingCount === 1 ? "" : "s"} across ${result.groups.filter((group2) => group2.count).length} of ${result.groups.length} checks.`
@@ -3181,19 +3837,19 @@ function render2(result) {
3181
3837
  }
3182
3838
 
3183
3839
  // src/commands/impact.ts
3184
- var import_zod12 = require("zod");
3840
+ var import_zod13 = require("zod");
3185
3841
  var impactCommand = define({
3186
3842
  name: "impact",
3187
3843
  tool: "kb_impact",
3188
3844
  usage: "impact <concept-id> [--depth N] [--rels a,b]",
3189
3845
  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.",
3190
- input: import_zod12.z.object({
3846
+ input: import_zod13.z.object({
3191
3847
  bundlePath,
3192
3848
  conceptId,
3193
- depth: import_zod12.z.number().int().positive().optional().describe(
3849
+ depth: import_zod13.z.number().int().positive().optional().describe(
3194
3850
  "Hops out from the record. Unbounded when omitted; a walk this cuts reports truncated: true."
3195
3851
  ),
3196
- rels: import_zod12.z.array(import_zod12.z.enum(KB_CAUSAL_LINK_RELS)).optional().describe(
3852
+ rels: import_zod13.z.array(import_zod13.z.enum(KB_CAUSAL_LINK_RELS)).optional().describe(
3197
3853
  "Narrow which rels the walk follows. Defaults to every rel that carries a dependence \u2014 all but related_to."
3198
3854
  )
3199
3855
  }),
@@ -3214,13 +3870,13 @@ var impactCommand = define({
3214
3870
  });
3215
3871
 
3216
3872
  // src/commands/list.ts
3217
- var import_zod13 = require("zod");
3873
+ var import_zod14 = require("zod");
3218
3874
  var listCommand = define({
3219
3875
  name: "list",
3220
3876
  tool: "kb_list",
3221
3877
  usage: "list [type]",
3222
3878
  description: "Every record, optionally one type. For enumerating; use kb_query for a question.",
3223
- input: import_zod13.z.object({ bundlePath, type: import_zod13.z.enum(KB_RECORD_TYPES).optional() }),
3879
+ input: import_zod14.z.object({ bundlePath, type: import_zod14.z.enum(KB_RECORD_TYPES).optional() }),
3224
3880
  fromArgv: (argv, path) => ({ bundlePath: path, type: argv[1] }),
3225
3881
  run: async ({ store }, { bundlePath: path, type }) => (await store.list(path, type)).map((record) => ({
3226
3882
  conceptId: record.conceptId,
@@ -3232,17 +3888,17 @@ var listCommand = define({
3232
3888
  });
3233
3889
 
3234
3890
  // src/commands/load.ts
3235
- var import_zod14 = require("zod");
3891
+ var import_zod15 = require("zod");
3236
3892
  var loadCommand = define({
3237
3893
  name: "load",
3238
3894
  tool: "kb_load",
3239
3895
  usage: "load [type] [--budget N | --all] [--repo-root PATH]",
3240
3896
  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.",
3241
- input: import_zod14.z.object({
3897
+ input: import_zod15.z.object({
3242
3898
  bundlePath,
3243
- type: import_zod14.z.enum(KB_RECORD_TYPES).optional(),
3244
- budgetTokens: import_zod14.z.number().int().positive().optional().describe("Approximate token ceiling. Defaults to 25000."),
3245
- all: import_zod14.z.boolean().optional().describe(
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(
3246
3902
  "Loads the entire base regardless of size, bypassing the token budget; mutually exclusive with budgetTokens."
3247
3903
  ),
3248
3904
  repoRoot: REPO_ROOT
@@ -3284,25 +3940,25 @@ var loadCommand = define({
3284
3940
  });
3285
3941
 
3286
3942
  // src/commands/log.ts
3287
- var import_zod15 = require("zod");
3943
+ var import_zod16 = require("zod");
3288
3944
  var logCommand = define({
3289
3945
  name: "log",
3290
3946
  tool: "kb_log",
3291
3947
  usage: "log",
3292
3948
  description: "Who touched what, and when. Append-only; malformed lines are reported, never repaired.",
3293
- input: import_zod15.z.object({ bundlePath }),
3949
+ input: import_zod16.z.object({ bundlePath }),
3294
3950
  fromArgv: (_argv, path) => ({ bundlePath: path }),
3295
3951
  run: ({ store }, { bundlePath: path }) => store.readLog(path)
3296
3952
  });
3297
3953
 
3298
3954
  // src/commands/no-decision.ts
3299
- var import_zod16 = require("zod");
3955
+ var import_zod17 = require("zod");
3300
3956
  var noDecisionCommand = define({
3301
3957
  name: "no-decision",
3302
3958
  tool: "kb_no_decision",
3303
3959
  usage: "no-decision <reason...>",
3304
3960
  description: "Record in one sentence that a piece of work had nothing to decide. Idempotent.",
3305
- input: import_zod16.z.object({ bundlePath, reason: import_zod16.z.string().min(1) }),
3961
+ input: import_zod17.z.object({ bundlePath, reason: import_zod17.z.string().min(1) }),
3306
3962
  fromArgv: (argv, path) => ({
3307
3963
  bundlePath: path,
3308
3964
  reason: argv.slice(1).join(" ").trim()
@@ -3319,20 +3975,20 @@ var noDecisionCommand = define({
3319
3975
  });
3320
3976
 
3321
3977
  // src/commands/pack.ts
3322
- var import_zod17 = require("zod");
3978
+ var import_zod18 = require("zod");
3323
3979
  var packCommand = define({
3324
3980
  name: "pack",
3325
3981
  tool: "kb_pack",
3326
3982
  usage: "pack <conceptId> [--hops N] [--max-nodes N] [--budget N]",
3327
3983
  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.",
3328
- input: import_zod17.z.object({
3984
+ input: import_zod18.z.object({
3329
3985
  bundlePath,
3330
3986
  conceptId,
3331
- hops: import_zod17.z.number().int().positive().optional().describe("How far from the root the walk may reach. Defaults to 2."),
3332
- maxNodes: import_zod17.z.number().int().positive().optional().describe(
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(
3333
3989
  "How many records the pack may hold, root included. Defaults to 20."
3334
3990
  ),
3335
- budgetTokens: import_zod17.z.number().int().positive().optional().describe(
3991
+ budgetTokens: import_zod18.z.number().int().positive().optional().describe(
3336
3992
  "Approximate token ceiling over what is actually emitted. Defaults to 25000."
3337
3993
  )
3338
3994
  }),
@@ -3419,22 +4075,22 @@ function warningLabel(warning) {
3419
4075
  }
3420
4076
 
3421
4077
  // src/commands/pin.ts
3422
- var import_zod18 = require("zod");
4078
+ var import_zod19 = require("zod");
3423
4079
  var pinCommand = define({
3424
4080
  name: "pin",
3425
4081
  tool: "kb_pin",
3426
4082
  usage: "pin [bundle-path] [--mode full|index] [--profiles a,b] [--local|--user] [--frozen|--unfreeze]",
3427
4083
  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.",
3428
- input: import_zod18.z.object({
4084
+ input: import_zod19.z.object({
3429
4085
  bundlePath,
3430
- mode: import_zod18.z.enum(["full", "index"]).optional().describe(
4086
+ mode: import_zod19.z.enum(["full", "index"]).optional().describe(
3431
4087
  "full: always emit this base's records whole (still under the block budget); index: never upgrade. Absent: the profile's full-under threshold decides."
3432
4088
  ),
3433
- profiles: import_zod18.z.array(import_zod18.z.string()).optional().describe("Context profiles this pin surfaces in. Absent: all of them."),
3434
- layer: import_zod18.z.enum(["project", "local", "user"]).optional().describe(
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(
3435
4091
  "Which manifest to write: project (committed, default), local (personal, gitignored), user (~/.strauss, every workspace)."
3436
4092
  ),
3437
- frozen: import_zod18.z.boolean().optional().describe(
4093
+ frozen: import_zod19.z.boolean().optional().describe(
3438
4094
  "true: the base is concluded \u2014 writes against it refuse while pinned. false: lift a freeze."
3439
4095
  )
3440
4096
  }),
@@ -3463,29 +4119,29 @@ var pinCommand = define({
3463
4119
  });
3464
4120
 
3465
4121
  // src/commands/pins.ts
3466
- var import_zod19 = require("zod");
4122
+ var import_zod20 = require("zod");
3467
4123
  var pinsCommand = define({
3468
4124
  name: "pins",
3469
4125
  tool: "kb_pins",
3470
4126
  usage: "pins",
3471
4127
  description: "Every pinned base across the manifest layers, with its layer and whether it resolves to records. Takes no bundlePath.",
3472
- input: import_zod19.z.object({}),
4128
+ input: import_zod20.z.object({}),
3473
4129
  fromArgv: () => ({}),
3474
4130
  run: ({ store }) => listPins(store, process.cwd())
3475
4131
  });
3476
4132
 
3477
4133
  // src/commands/query.ts
3478
- var import_zod20 = require("zod");
4134
+ var import_zod21 = require("zod");
3479
4135
  var queryCommand = define({
3480
4136
  name: "query",
3481
4137
  tool: "kb_query",
3482
4138
  usage: "query <text...> [--repo-root PATH]",
3483
4139
  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.",
3484
- input: import_zod20.z.object({
4140
+ input: import_zod21.z.object({
3485
4141
  bundlePath,
3486
- text: import_zod20.z.string().optional(),
3487
- type: import_zod20.z.enum(KB_RECORD_TYPES).optional(),
3488
- includeNonCurrent: import_zod20.z.boolean().optional(),
4142
+ text: import_zod21.z.string().optional(),
4143
+ type: import_zod21.z.enum(KB_RECORD_TYPES).optional(),
4144
+ includeNonCurrent: import_zod21.z.boolean().optional(),
3489
4145
  repoRoot: REPO_ROOT
3490
4146
  }),
3491
4147
  // `--repo-root` is a flag, so its value must not fall into the search text.
@@ -3517,27 +4173,27 @@ var queryCommand = define({
3517
4173
  });
3518
4174
 
3519
4175
  // src/commands/read-index.ts
3520
- var import_zod21 = require("zod");
4176
+ var import_zod22 = require("zod");
3521
4177
  var readIndexCommand = define({
3522
4178
  name: "index",
3523
4179
  tool: "kb_index",
3524
4180
  usage: "index",
3525
4181
  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.",
3526
- input: import_zod21.z.object({ bundlePath }),
4182
+ input: import_zod22.z.object({ bundlePath }),
3527
4183
  fromArgv: (_argv, path) => ({ bundlePath: path }),
3528
4184
  run: ({ store }, { bundlePath: path }) => store.readIndex(path)
3529
4185
  });
3530
4186
 
3531
4187
  // src/commands/schema.ts
3532
- var import_zod24 = require("zod");
4188
+ var import_zod25 = require("zod");
3533
4189
 
3534
4190
  // src/json-schema.ts
3535
- var import_zod23 = require("zod");
4191
+ var import_zod24 = require("zod");
3536
4192
 
3537
4193
  // src/kb-log.ts
3538
- var import_zod22 = require("zod");
4194
+ var import_zod23 = require("zod");
3539
4195
  var LOG_FILE = "log.jsonl";
3540
- var kbLogEntrySchema = import_zod22.z.object({
4196
+ var kbLogEntrySchema = import_zod23.z.object({
3541
4197
  // Validated, not just `min(1)`: `at` is a sort key (see `parseLog`
3542
4198
  // below), and a value that isn't actually chronological — a Unix
3543
4199
  // timestamp, a human-typed date, garbage — would sort wrong without
@@ -3546,12 +4202,12 @@ var kbLogEntrySchema = import_zod22.z.object({
3546
4202
  // and rejects everything else, including a non-`Z` offset — so a
3547
4203
  // malformed `at` is reported the same way a malformed line already is,
3548
4204
  // rather than silently sorting into the wrong place.
3549
- at: import_zod22.z.iso.datetime(),
3550
- by: import_zod22.z.string().min(1),
3551
- operation: import_zod22.z.string().min(1),
3552
- conceptId: import_zod22.z.string().min(1),
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),
3553
4209
  /** Second concept id, where the operation relates two — supersession. */
3554
- target: import_zod22.z.string().min(1).optional()
4210
+ target: import_zod23.z.string().min(1).optional()
3555
4211
  }).strict();
3556
4212
  function renderLogEntry(entry) {
3557
4213
  return `${JSON.stringify(kbLogEntrySchema.parse(entry))}
@@ -3561,18 +4217,18 @@ function parseLog(raw) {
3561
4217
  const entries = [];
3562
4218
  const malformed = [];
3563
4219
  const seen = /* @__PURE__ */ new Set();
3564
- raw.split("\n").forEach((text, index) => {
4220
+ raw.split("\n").forEach((text, index2) => {
3565
4221
  if (!text.trim()) return;
3566
4222
  let value;
3567
4223
  try {
3568
4224
  value = JSON.parse(text);
3569
4225
  } catch {
3570
- malformed.push({ line: index + 1, text });
4226
+ malformed.push({ line: index2 + 1, text });
3571
4227
  return;
3572
4228
  }
3573
4229
  const parsed = kbLogEntrySchema.safeParse(value);
3574
4230
  if (!parsed.success) {
3575
- malformed.push({ line: index + 1, text });
4231
+ malformed.push({ line: index2 + 1, text });
3576
4232
  return;
3577
4233
  }
3578
4234
  const key = JSON.stringify(parsed.data);
@@ -3589,11 +4245,11 @@ function parseLog(raw) {
3589
4245
  // src/json-schema.ts
3590
4246
  function kbJsonSchemas() {
3591
4247
  return {
3592
- recordFrontmatter: import_zod23.z.toJSONSchema(kbRecordFrontmatterSchema, {
4248
+ recordFrontmatter: import_zod24.z.toJSONSchema(kbRecordFrontmatterSchema, {
3593
4249
  io: "input"
3594
4250
  }),
3595
- composeInput: import_zod23.z.toJSONSchema(composeInputSchema, { io: "input" }),
3596
- logEntry: import_zod23.z.toJSONSchema(kbLogEntrySchema, { io: "input" })
4251
+ composeInput: import_zod24.z.toJSONSchema(composeInputSchema, { io: "input" }),
4252
+ logEntry: import_zod24.z.toJSONSchema(kbLogEntrySchema, { io: "input" })
3597
4253
  };
3598
4254
  }
3599
4255
 
@@ -3603,25 +4259,25 @@ var schemaCommand = define({
3603
4259
  tool: "kb_schema",
3604
4260
  usage: "schema",
3605
4261
  description: "JSON Schema for frontmatter, write input, and log entries, generated from the enforcing code.",
3606
- input: import_zod24.z.object({}),
4262
+ input: import_zod25.z.object({}),
3607
4263
  fromArgv: () => ({}),
3608
4264
  run: () => Promise.resolve(kbJsonSchemas())
3609
4265
  });
3610
4266
 
3611
4267
  // src/commands/stamp.ts
3612
- var import_promises5 = require("fs/promises");
3613
- var import_zod25 = require("zod");
4268
+ var import_promises7 = require("fs/promises");
4269
+ var import_zod26 = require("zod");
3614
4270
  var DIGEST = /^[0-9a-f]{64}$/;
3615
4271
  var stampCommand = define({
3616
4272
  name: "stamp",
3617
4273
  tool: "kb_stamp",
3618
4274
  usage: "stamp [--bundle PATH] [--since DIGEST|FILE]",
3619
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.",
3620
- input: import_zod25.z.object({
3621
- bundlePath: import_zod25.z.string().min(1).optional().describe(
4276
+ input: import_zod26.z.object({
4277
+ bundlePath: import_zod26.z.string().min(1).optional().describe(
3622
4278
  "Absolute path to one knowledge base. Omit to stamp every pinned base."
3623
4279
  ),
3624
- since: import_zod25.z.string().min(1).optional().describe(
4280
+ since: import_zod26.z.string().min(1).optional().describe(
3625
4281
  "Prior digest, or path to a prior `stamp --json`; only moved bases return, with changed ids when the baseline is a file."
3626
4282
  )
3627
4283
  }),
@@ -3683,7 +4339,7 @@ async function readBaseline(since) {
3683
4339
  if (DIGEST.test(since)) return { digest: since, byPath: /* @__PURE__ */ new Map() };
3684
4340
  let parsed;
3685
4341
  try {
3686
- parsed = JSON.parse(await (0, import_promises5.readFile)(since, "utf8"));
4342
+ parsed = JSON.parse(await (0, import_promises7.readFile)(since, "utf8"));
3687
4343
  } catch {
3688
4344
  throw new KbStampBaselineError(since);
3689
4345
  }
@@ -3707,16 +4363,16 @@ async function readBaseline(since) {
3707
4363
  }
3708
4364
 
3709
4365
  // src/commands/status.ts
3710
- var import_zod26 = require("zod");
4366
+ var import_zod27 = require("zod");
3711
4367
  var statusCommand = define({
3712
4368
  name: "status",
3713
4369
  tool: "kb_status",
3714
4370
  usage: "status <concept-id> <status>",
3715
4371
  description: "Move a record's status. Compare-and-swap: a concurrent change fails instead of being overwritten.",
3716
- input: import_zod26.z.object({
4372
+ input: import_zod27.z.object({
3717
4373
  bundlePath,
3718
4374
  conceptId,
3719
- status: import_zod26.z.enum(KB_RECORD_STATUSES)
4375
+ status: import_zod27.z.enum(KB_RECORD_STATUSES)
3720
4376
  }),
3721
4377
  fromArgv: (argv, path) => ({
3722
4378
  bundlePath: path,
@@ -3731,13 +4387,13 @@ var statusCommand = define({
3731
4387
  });
3732
4388
 
3733
4389
  // src/commands/supersede.ts
3734
- var import_zod27 = require("zod");
4390
+ var import_zod28 = require("zod");
3735
4391
  var supersedeCommand = define({
3736
4392
  name: "supersede",
3737
4393
  tool: "kb_supersede",
3738
4394
  usage: "supersede <concept-id> <replacement-id>",
3739
4395
  description: "Mark a record superseded by another, linked in both directions. Use instead of editing a record whose meaning changed.",
3740
- input: import_zod27.z.object({ bundlePath, conceptId, replacementId: conceptId }),
4396
+ input: import_zod28.z.object({ bundlePath, conceptId, replacementId: conceptId }),
3741
4397
  fromArgv: (argv, path) => ({
3742
4398
  bundlePath: path,
3743
4399
  conceptId: argv[1],
@@ -3751,16 +4407,16 @@ var supersedeCommand = define({
3751
4407
  });
3752
4408
 
3753
4409
  // src/commands/sync-instructions.ts
3754
- var import_zod28 = require("zod");
4410
+ var import_zod29 = require("zod");
3755
4411
  var syncInstructionsCommand = define({
3756
4412
  name: "sync-instructions",
3757
4413
  usage: "sync-instructions <file> [--profile NAME] [--budget N] [--full-under N]",
3758
4414
  description: "CLI-only: plant the kb_context block between sentinel comments in AGENTS.md or CLAUDE.md, idempotently.",
3759
- input: import_zod28.z.object({
3760
- file: import_zod28.z.string().min(1).describe("The instruction file to edit in place."),
3761
- budgetTokens: import_zod28.z.number().int().positive().optional(),
3762
- fullUnderTokens: import_zod28.z.number().int().positive().optional(),
3763
- profile: import_zod28.z.string().optional()
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()
3764
4420
  }),
3765
4421
  fromArgv: (argv) => {
3766
4422
  const budget = argvFlag(argv, "--budget");
@@ -3786,7 +4442,7 @@ var syncInstructionsCommand = define({
3786
4442
  });
3787
4443
 
3788
4444
  // src/commands/trace.ts
3789
- var import_zod29 = require("zod");
4445
+ var import_zod30 = require("zod");
3790
4446
 
3791
4447
  // src/trace.ts
3792
4448
  var TRACE_EDGES = [
@@ -3842,11 +4498,11 @@ var traceCommand = define({
3842
4498
  tool: "kb_trace",
3843
4499
  usage: "trace <concept-id> [edges...]",
3844
4500
  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".',
3845
- input: import_zod29.z.object({
4501
+ input: import_zod30.z.object({
3846
4502
  bundlePath,
3847
4503
  conceptId,
3848
- edges: import_zod29.z.array(import_zod29.z.enum(TRACE_EDGES)).optional(),
3849
- depth: import_zod29.z.number().int().positive().optional()
4504
+ edges: import_zod30.z.array(import_zod30.z.enum(TRACE_EDGES)).optional(),
4505
+ depth: import_zod30.z.number().int().positive().optional()
3850
4506
  }),
3851
4507
  fromArgv: (argv, path) => ({
3852
4508
  bundlePath: path,
@@ -3868,37 +4524,37 @@ var traceCommand = define({
3868
4524
  });
3869
4525
 
3870
4526
  // src/commands/types.ts
3871
- var import_zod30 = require("zod");
4527
+ var import_zod31 = require("zod");
3872
4528
  var typesCommand = define({
3873
4529
  name: "types",
3874
4530
  tool: "kb_types",
3875
4531
  usage: "types",
3876
4532
  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.",
3877
- input: import_zod30.z.object({}),
4533
+ input: import_zod31.z.object({}),
3878
4534
  fromArgv: () => ({}),
3879
4535
  run: () => Promise.resolve(RECORD_TYPES)
3880
4536
  });
3881
4537
 
3882
4538
  // src/commands/unpin.ts
3883
- var import_zod31 = require("zod");
4539
+ var import_zod32 = require("zod");
3884
4540
  var unpinCommand = define({
3885
4541
  name: "unpin",
3886
4542
  tool: "kb_unpin",
3887
4543
  usage: "unpin [bundle-path]",
3888
4544
  description: "Remove a base from every manifest layer that holds it. Reports the layers touched.",
3889
- input: import_zod31.z.object({ bundlePath }),
4545
+ input: import_zod32.z.object({ bundlePath }),
3890
4546
  fromArgv: (argv, path) => ({ bundlePath: argv[1] ?? path }),
3891
4547
  run: (_ctx, { bundlePath: path }) => unpinBase(process.cwd(), path)
3892
4548
  });
3893
4549
 
3894
4550
  // src/commands/validate.ts
3895
- var import_zod32 = require("zod");
4551
+ var import_zod33 = require("zod");
3896
4552
  var validateCommand = define({
3897
4553
  name: "validate",
3898
4554
  tool: "kb_validate",
3899
4555
  usage: "validate",
3900
4556
  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.",
3901
- input: import_zod32.z.object({ bundlePath }),
4557
+ input: import_zod33.z.object({ bundlePath }),
3902
4558
  fromArgv: (_argv, path) => ({ bundlePath: path }),
3903
4559
  run: async ({ store }, { bundlePath: path }) => validateBundle(await store.list(path)),
3904
4560
  // Warnings never fail the exit code; every other severity does.
@@ -3908,16 +4564,16 @@ var validateCommand = define({
3908
4564
  });
3909
4565
 
3910
4566
  // src/commands/verify.ts
3911
- var import_zod33 = require("zod");
4567
+ var import_zod34 = require("zod");
3912
4568
  var verifyCommand = define({
3913
4569
  name: "verify",
3914
4570
  tool: "kb_verify",
3915
4571
  usage: "verify <concept-id> --note <text>",
3916
4572
  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.",
3917
- input: import_zod33.z.object({
4573
+ input: import_zod34.z.object({
3918
4574
  bundlePath,
3919
4575
  conceptId,
3920
- note: import_zod33.z.string().refine((s) => s.trim().length > 0, {
4576
+ note: import_zod34.z.string().refine((s) => s.trim().length > 0, {
3921
4577
  message: "note must say what the check found"
3922
4578
  })
3923
4579
  }),
@@ -3937,15 +4593,15 @@ var verifyCommand = define({
3937
4593
  });
3938
4594
 
3939
4595
  // src/commands/write.ts
3940
- var import_zod34 = require("zod");
4596
+ var import_zod35 = require("zod");
3941
4597
  var writeCommand = define({
3942
4598
  name: "write",
3943
4599
  tool: "kb_write",
3944
4600
  usage: "write <type> < record.json",
3945
4601
  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.",
3946
- input: import_zod34.z.object({
4602
+ input: import_zod35.z.object({
3947
4603
  bundlePath,
3948
- type: import_zod34.z.enum(KB_RECORD_TYPES),
4604
+ type: import_zod35.z.enum(KB_RECORD_TYPES),
3949
4605
  input: composeInputSchema
3950
4606
  }),
3951
4607
  fromArgv: async (argv, path, stdin) => ({
@@ -3969,13 +4625,13 @@ var writeCommand = define({
3969
4625
  });
3970
4626
 
3971
4627
  // src/commands/write-decision.ts
3972
- var import_zod35 = require("zod");
4628
+ var import_zod36 = require("zod");
3973
4629
  var writeDecisionCommand = define({
3974
4630
  name: "write-decision",
3975
4631
  tool: "kb_write_decision",
3976
4632
  usage: "write-decision < decision.json",
3977
4633
  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.",
3978
- input: import_zod35.z.object({ bundlePath, input: decisionInputSchema }),
4634
+ input: import_zod36.z.object({ bundlePath, input: decisionInputSchema }),
3979
4635
  fromArgv: async (_argv, path, stdin) => ({
3980
4636
  bundlePath: path,
3981
4637
  input: JSON.parse(await stdin())
@@ -4031,8 +4687,8 @@ var KB_COMMANDS_BY_NAME = new Map(
4031
4687
  );
4032
4688
 
4033
4689
  // src/kb-store.ts
4034
- var import_promises7 = require("fs/promises");
4035
- var import_node_path8 = require("path");
4690
+ var import_promises9 = require("fs/promises");
4691
+ var import_node_path11 = require("path");
4036
4692
 
4037
4693
  // src/markdown.ts
4038
4694
  var import_gray_matter = __toESM(require("gray-matter"), 1);
@@ -4060,15 +4716,15 @@ function parseMarkdownWithFrontmatter(text, schema) {
4060
4716
  }
4061
4717
 
4062
4718
  // src/kb-stamp.ts
4063
- var import_node_crypto2 = require("crypto");
4064
- function sha256(contents) {
4065
- return (0, import_node_crypto2.createHash)("sha256").update(contents).digest("hex");
4719
+ var import_node_crypto4 = require("crypto");
4720
+ function sha2563(contents) {
4721
+ return (0, import_node_crypto4.createHash)("sha256").update(contents).digest("hex");
4066
4722
  }
4067
4723
  function bundleStamp(records, superseded) {
4068
4724
  const entries = [
4069
4725
  ...records.map((hit) => ({
4070
4726
  conceptId: hit.record.conceptId,
4071
- digest: `current:${sha256(
4727
+ digest: `current:${sha2563(
4072
4728
  stringifyMarkdownWithFrontmatter(
4073
4729
  hit.record.body,
4074
4730
  hit.record.frontmatter
@@ -4077,11 +4733,11 @@ function bundleStamp(records, superseded) {
4077
4733
  })),
4078
4734
  ...superseded.map((entry) => ({
4079
4735
  conceptId: entry.conceptId,
4080
- digest: `superseded:${sha256(JSON.stringify(entry))}`
4736
+ digest: `superseded:${sha2563(JSON.stringify(entry))}`
4081
4737
  }))
4082
4738
  ].sort((a, b) => a.conceptId < b.conceptId ? -1 : 1);
4083
4739
  return {
4084
- digest: sha256(
4740
+ digest: sha2563(
4085
4741
  entries.map((entry) => `${entry.conceptId}:${entry.digest}`).join("\n")
4086
4742
  ),
4087
4743
  records: entries
@@ -4092,8 +4748,8 @@ function bundleDigest(records, superseded) {
4092
4748
  }
4093
4749
 
4094
4750
  // src/search-index.ts
4095
- var import_promises6 = require("fs/promises");
4096
- var import_node_path7 = require("path");
4751
+ var import_promises8 = require("fs/promises");
4752
+ var import_node_path10 = require("path");
4097
4753
  var SEARCH_INDEX_FILE = ".index.sqlite";
4098
4754
  var COLLECTION = "kb";
4099
4755
  async function searchBase(bundlePath2, query, options = {}) {
@@ -4102,7 +4758,7 @@ async function searchBase(bundlePath2, query, options = {}) {
4102
4758
  let store = null;
4103
4759
  try {
4104
4760
  store = await qmd.createStore({
4105
- dbPath: (0, import_node_path7.join)(bundlePath2, SEARCH_INDEX_FILE),
4761
+ dbPath: (0, import_node_path10.join)(bundlePath2, SEARCH_INDEX_FILE),
4106
4762
  config: {
4107
4763
  collections: {
4108
4764
  [COLLECTION]: {
@@ -4137,7 +4793,7 @@ async function searchBase(bundlePath2, query, options = {}) {
4137
4793
  }
4138
4794
  }
4139
4795
  async function isStale(bundlePath2) {
4140
- const indexAt = await (0, import_promises6.stat)((0, import_node_path7.join)(bundlePath2, SEARCH_INDEX_FILE)).then((s) => s.mtimeMs).catch(() => 0);
4796
+ const indexAt = await (0, import_promises8.stat)((0, import_node_path10.join)(bundlePath2, SEARCH_INDEX_FILE)).then((s) => s.mtimeMs).catch(() => 0);
4141
4797
  if (!indexAt) return true;
4142
4798
  const { readdir: readdir2 } = await import("fs/promises");
4143
4799
  const names = (await readdir2(bundlePath2).catch(() => [])).filter(
@@ -4146,7 +4802,7 @@ async function isStale(bundlePath2) {
4146
4802
  let stale = false;
4147
4803
  await mapLimit(names, DEFAULT_IO_CONCURRENCY, async (name) => {
4148
4804
  if (stale) return;
4149
- const at = await (0, import_promises6.stat)((0, import_node_path7.join)(bundlePath2, name)).then((s) => s.mtimeMs).catch(() => 0);
4805
+ const at = await (0, import_promises8.stat)((0, import_node_path10.join)(bundlePath2, name)).then((s) => s.mtimeMs).catch(() => 0);
4150
4806
  if (at > indexAt) stale = true;
4151
4807
  });
4152
4808
  return stale;
@@ -4260,8 +4916,8 @@ function byRank(left, right) {
4260
4916
  ) || left.record.conceptId.localeCompare(right.record.conceptId);
4261
4917
  }
4262
4918
  function typeRank(record) {
4263
- const index = TYPE_PRIORITY.indexOf(record.frontmatter.type);
4264
- return index === -1 ? TYPE_PRIORITY.length : index;
4919
+ const index2 = TYPE_PRIORITY.indexOf(record.frontmatter.type);
4920
+ return index2 === -1 ? TYPE_PRIORITY.length : index2;
4265
4921
  }
4266
4922
 
4267
4923
  // src/kb-links/inbound.ts
@@ -4424,7 +5080,7 @@ function appendUnionMergeLine(contents) {
4424
5080
  }
4425
5081
 
4426
5082
  // src/kb-store.ts
4427
- var KB_DIR = (0, import_node_path8.join)(".strauss", "kb");
5083
+ var KB_DIR = (0, import_node_path11.join)(".strauss", "kb");
4428
5084
  var STORE_OWNED = /* @__PURE__ */ new Set([INDEX_FILE, LOG_FILE, SEARCH_INDEX_FILE]);
4429
5085
  var DEFAULT_LOAD_BUDGET = 25e3;
4430
5086
  var KbStore = class {
@@ -4455,7 +5111,7 @@ var KbStore = class {
4455
5111
  const conceptId2 = `${input.type}.${input.slug}`;
4456
5112
  const root = this.root(bundlePath2);
4457
5113
  const target = this.recordPath(bundlePath2, conceptId2);
4458
- await (0, import_promises7.mkdir)(root, { recursive: true });
5114
+ await (0, import_promises9.mkdir)(root, { recursive: true });
4459
5115
  await this.publish(
4460
5116
  target,
4461
5117
  stringifyMarkdownWithFrontmatter(input.body, frontmatter),
@@ -4494,7 +5150,7 @@ var KbStore = class {
4494
5150
  const target = this.recordPath(bundlePath2, conceptId2);
4495
5151
  let raw;
4496
5152
  try {
4497
- raw = await (0, import_promises7.readFile)(target, "utf8");
5153
+ raw = await (0, import_promises9.readFile)(target, "utf8");
4498
5154
  } catch {
4499
5155
  return null;
4500
5156
  }
@@ -4511,7 +5167,7 @@ var KbStore = class {
4511
5167
  const root = this.root(bundlePath2);
4512
5168
  let names;
4513
5169
  try {
4514
- names = await (0, import_promises7.readdir)(root);
5170
+ names = await (0, import_promises9.readdir)(root);
4515
5171
  } catch {
4516
5172
  return [];
4517
5173
  }
@@ -4519,7 +5175,7 @@ var KbStore = class {
4519
5175
  const records = await mapLimit(
4520
5176
  wanted,
4521
5177
  DEFAULT_IO_CONCURRENCY,
4522
- async ({ name, conceptId: conceptId2 }) => this.parse(conceptId2, await (0, import_promises7.readFile)((0, import_node_path8.join)(root, name), "utf8"))
5178
+ async ({ name, conceptId: conceptId2 }) => this.parse(conceptId2, await (0, import_promises9.readFile)((0, import_node_path11.join)(root, name), "utf8"))
4523
5179
  );
4524
5180
  return records.filter((record) => record !== null);
4525
5181
  }
@@ -4676,7 +5332,7 @@ ${answer}
4676
5332
  if (found.length) return found;
4677
5333
  }
4678
5334
  const lowered = needle.toLowerCase();
4679
- return bundle.filter((record) => matches(record, lowered));
5335
+ return bundle.filter((record) => matches2(record, lowered));
4680
5336
  }
4681
5337
  /**
4682
5338
  * Anchor drift over the records about to be handed back. Like the search
@@ -4846,11 +5502,11 @@ ${answer}
4846
5502
  async readIndex(bundlePath2) {
4847
5503
  const root = this.root(bundlePath2);
4848
5504
  const expected = renderIndex(await this.list(bundlePath2));
4849
- const stored = await (0, import_promises7.readFile)((0, import_node_path8.join)(root, INDEX_FILE), "utf8").catch(
5505
+ const stored = await (0, import_promises9.readFile)((0, import_node_path11.join)(root, INDEX_FILE), "utf8").catch(
4850
5506
  () => null
4851
5507
  );
4852
5508
  if (indexIsStale(stored, expected)) {
4853
- await this.publish((0, import_node_path8.join)(root, INDEX_FILE), expected, true, INDEX_FILE);
5509
+ await this.publish((0, import_node_path11.join)(root, INDEX_FILE), expected, true, INDEX_FILE);
4854
5510
  this.logger.info?.({
4855
5511
  operation: "kb.index.repair",
4856
5512
  bundlePath: root,
@@ -4867,8 +5523,8 @@ ${answer}
4867
5523
  * knows which agent touched what. So a bad line is surfaced and left alone.
4868
5524
  */
4869
5525
  async readLog(bundlePath2) {
4870
- const raw = await (0, import_promises7.readFile)(
4871
- (0, import_node_path8.join)(this.root(bundlePath2), LOG_FILE),
5526
+ const raw = await (0, import_promises9.readFile)(
5527
+ (0, import_node_path11.join)(this.root(bundlePath2), LOG_FILE),
4872
5528
  "utf8"
4873
5529
  ).catch(() => "");
4874
5530
  const result = parseLog(raw);
@@ -4919,15 +5575,15 @@ ${answer}
4919
5575
  }
4920
5576
  async mutate(bundlePath2, conceptId2, change, entry, changeBody = (body) => body) {
4921
5577
  const target = this.recordPath(bundlePath2, conceptId2);
4922
- const before = await (0, import_promises7.readFile)(target, "utf8").catch(() => null);
5578
+ const before = await (0, import_promises9.readFile)(target, "utf8").catch(() => null);
4923
5579
  if (before === null) throw new KbRecordNotFoundError(conceptId2);
4924
5580
  const parsed = this.parse(conceptId2, before);
4925
5581
  if (!parsed) throw new KbRecordNotFoundError(conceptId2);
4926
5582
  const frontmatter = change(parsed.frontmatter);
4927
5583
  const body = changeBody(parsed.body);
4928
5584
  const contents = stringifyMarkdownWithFrontmatter(body, frontmatter);
4929
- const witness = await (0, import_promises7.readFile)(target, "utf8").catch(() => null);
4930
- if (witness === null || sha256(witness) !== sha256(before)) {
5585
+ const witness = await (0, import_promises9.readFile)(target, "utf8").catch(() => null);
5586
+ if (witness === null || sha2563(witness) !== sha2563(before)) {
4931
5587
  throw new KbWriteConflictError(conceptId2);
4932
5588
  }
4933
5589
  await this.publish(target, contents, true, conceptId2);
@@ -4952,20 +5608,20 @@ ${answer}
4952
5608
  */
4953
5609
  async publish(target, contents, overwrite, conceptId2) {
4954
5610
  const staging = `${target}.${process.pid}.tmp`;
4955
- await (0, import_promises7.writeFile)(staging, contents, "utf8");
5611
+ await (0, import_promises9.writeFile)(staging, contents, "utf8");
4956
5612
  try {
4957
5613
  if (overwrite) {
4958
- await (0, import_promises7.rename)(staging, target);
5614
+ await (0, import_promises9.rename)(staging, target);
4959
5615
  return;
4960
5616
  }
4961
- await (0, import_promises7.link)(staging, target);
5617
+ await (0, import_promises9.link)(staging, target);
4962
5618
  } catch (error) {
4963
5619
  if (error.code === "EEXIST") {
4964
5620
  throw new KbRecordAlreadyExistsError(conceptId2);
4965
5621
  }
4966
5622
  throw error;
4967
5623
  } finally {
4968
- await (0, import_promises7.unlink)(staging).catch(() => void 0);
5624
+ await (0, import_promises9.unlink)(staging).catch(() => void 0);
4969
5625
  }
4970
5626
  }
4971
5627
  /**
@@ -5009,18 +5665,18 @@ ${answer}
5009
5665
  * file must not fail the mutation it guards.
5010
5666
  */
5011
5667
  async ensureGitattributes(root) {
5012
- const target = (0, import_node_path8.join)(root, GITATTRIBUTES_FILE);
5668
+ const target = (0, import_node_path11.join)(root, GITATTRIBUTES_FILE);
5013
5669
  try {
5014
5670
  let existing;
5015
5671
  try {
5016
- existing = await (0, import_promises7.readFile)(target, "utf8");
5672
+ existing = await (0, import_promises9.readFile)(target, "utf8");
5017
5673
  } catch (error) {
5018
5674
  if (error.code !== "ENOENT") throw error;
5019
5675
  existing = null;
5020
5676
  }
5021
5677
  if (existing === null) {
5022
5678
  try {
5023
- await (0, import_promises7.writeFile)(target, appendUnionMergeLine(""), {
5679
+ await (0, import_promises9.writeFile)(target, appendUnionMergeLine(""), {
5024
5680
  encoding: "utf8",
5025
5681
  flag: "wx"
5026
5682
  });
@@ -5041,7 +5697,7 @@ ${answer}
5041
5697
  return;
5042
5698
  }
5043
5699
  if (!hasMergeDeclaration(existing)) {
5044
- await (0, import_promises7.appendFile)(target, appendUnionMergeLine(existing), "utf8");
5700
+ await (0, import_promises9.appendFile)(target, appendUnionMergeLine(existing), "utf8");
5045
5701
  this.logger.info?.({
5046
5702
  operation: "kb.gitattributes.ensure",
5047
5703
  bundlePath: root,
@@ -5060,7 +5716,7 @@ ${answer}
5060
5716
  async record(root, entry) {
5061
5717
  await this.ensureGitattributes(root);
5062
5718
  const line = renderLogEntry({ at: (/* @__PURE__ */ new Date()).toISOString(), ...entry });
5063
- await (0, import_promises7.appendFile)((0, import_node_path8.join)(root, LOG_FILE), line, "utf8").catch((error) => {
5719
+ await (0, import_promises9.appendFile)((0, import_node_path11.join)(root, LOG_FILE), line, "utf8").catch((error) => {
5064
5720
  this.logger.warn?.({
5065
5721
  operation: "kb.log.append",
5066
5722
  outcome: "failed",
@@ -5086,18 +5742,18 @@ ${answer}
5086
5742
  };
5087
5743
  }
5088
5744
  root(bundlePath2) {
5089
- return (0, import_node_path8.resolve)(bundlePath2);
5745
+ return (0, import_node_path11.resolve)(bundlePath2);
5090
5746
  }
5091
5747
  // Concept ids are `<type>.<slug>` and map to a single file directly under the
5092
5748
  // bundle root; anything carrying a separator would escape it.
5093
5749
  recordPath(bundlePath2, conceptId2) {
5094
- if (conceptId2.includes(import_node_path8.sep) || conceptId2.includes("/")) {
5750
+ if (conceptId2.includes(import_node_path11.sep) || conceptId2.includes("/")) {
5095
5751
  throw new KbInvalidConceptIdError(
5096
5752
  "concept id must not contain a path separator",
5097
5753
  { conceptId: conceptId2 }
5098
5754
  );
5099
5755
  }
5100
- return (0, import_node_path8.join)(this.root(bundlePath2), `${conceptId2}.md`);
5756
+ return (0, import_node_path11.join)(this.root(bundlePath2), `${conceptId2}.md`);
5101
5757
  }
5102
5758
  };
5103
5759
  function estimateTokens(record) {
@@ -5124,7 +5780,7 @@ function stub(hit) {
5124
5780
  at: hit.record.frontmatter.generated?.at ?? null
5125
5781
  };
5126
5782
  }
5127
- function matches(record, needle) {
5783
+ function matches2(record, needle) {
5128
5784
  const { title, description } = record.frontmatter;
5129
5785
  return [record.conceptId, title, description, record.body].some(
5130
5786
  (field) => field?.toLowerCase().includes(needle)
@@ -5137,7 +5793,7 @@ function normalizeActor(id) {
5137
5793
  }
5138
5794
 
5139
5795
  // src/version.ts
5140
- var VERSION = true ? "0.1.16" : "0.0.0-dev";
5796
+ var VERSION = true ? "0.1.17" : "0.0.0-dev";
5141
5797
 
5142
5798
  // src/mcp.ts
5143
5799
  function createKbMcpServer() {