@saasontools/strauss-kb 0.1.6 → 0.1.8

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
@@ -1056,14 +1056,460 @@ var contextCommand = define({
1056
1056
  }
1057
1057
  });
1058
1058
 
1059
- // src/commands/list.ts
1059
+ // src/commands/doctor.ts
1060
1060
  var import_zod8 = require("zod");
1061
+
1062
+ // src/kb-edges.ts
1063
+ var KB_EDGE_KINDS = [
1064
+ "body-link",
1065
+ "supersession",
1066
+ "anchor",
1067
+ "source"
1068
+ ];
1069
+ var BODY_LINK_TARGET = new RegExp(
1070
+ `\\]\\((${KB_CONCEPT_ID_PATTERN.source.replace(/^\^|\$$/g, "")})\\.md\\)`,
1071
+ "g"
1072
+ );
1073
+ function neighbours(from, bundle, kinds = KB_EDGE_KINDS) {
1074
+ const found = /* @__PURE__ */ new Map();
1075
+ for (const kind of kinds) {
1076
+ for (const record of edgeNeighbours(from, bundle, kind)) {
1077
+ const existing = found.get(record.conceptId);
1078
+ if (existing) {
1079
+ if (!existing.via.includes(kind)) existing.via.push(kind);
1080
+ continue;
1081
+ }
1082
+ found.set(record.conceptId, { record, via: [kind] });
1083
+ }
1084
+ }
1085
+ return [...found.values()];
1086
+ }
1087
+ function edgeNeighbours(from, bundle, kind) {
1088
+ switch (kind) {
1089
+ // A link whose target is not in the bundle is legal per compose.ts —
1090
+ // records are routinely written before the ones they point at exist — so
1091
+ // missing targets are skipped, never an error.
1092
+ case "body-link": {
1093
+ const targets = new Set(
1094
+ [...from.body.matchAll(BODY_LINK_TARGET)].map((match) => match[1])
1095
+ );
1096
+ if (!targets.size) return [];
1097
+ return bundle.filter(
1098
+ (candidate) => candidate.conceptId !== from.conceptId && targets.has(candidate.conceptId)
1099
+ );
1100
+ }
1101
+ // Both directions and both pointers: `supersede()` writes the pair, but a
1102
+ // hand-edit can leave one side behind, and a walk trusting one pointer
1103
+ // would miss a replacement the bundle openly declares.
1104
+ case "supersession":
1105
+ return bundle.filter(
1106
+ (candidate) => candidate.conceptId !== from.conceptId && (candidate.conceptId === from.frontmatter.strauss_superseded_by || from.frontmatter.strauss_supersedes?.includes(
1107
+ candidate.conceptId
1108
+ ) || candidate.frontmatter.strauss_superseded_by === from.conceptId || candidate.frontmatter.strauss_supersedes?.includes(from.conceptId))
1109
+ );
1110
+ // The edge that answers "why is this code shaped this way": every record
1111
+ // attached to the same file or symbol, whatever its standing.
1112
+ case "anchor": {
1113
+ const mine = from.frontmatter.strauss_anchors ?? [];
1114
+ if (!mine.length) return [];
1115
+ return bundle.filter(
1116
+ (candidate) => candidate.conceptId !== from.conceptId && (candidate.frontmatter.strauss_anchors ?? []).some(
1117
+ (theirs) => mine.some((ours) => anchorsTouch(ours, theirs))
1118
+ )
1119
+ );
1120
+ }
1121
+ case "source": {
1122
+ const mine = new Set((from.frontmatter.sources ?? []).map((s) => s.id));
1123
+ if (!mine.size) return [];
1124
+ return bundle.filter(
1125
+ (candidate) => candidate.conceptId !== from.conceptId && (candidate.frontmatter.sources ?? []).some(
1126
+ (source) => mine.has(source.id)
1127
+ )
1128
+ );
1129
+ }
1130
+ }
1131
+ }
1132
+ function anchorsTouch(left, right) {
1133
+ if (left.file !== right.file) return false;
1134
+ if (!left.symbol || !right.symbol) return true;
1135
+ return left.symbol === right.symbol;
1136
+ }
1137
+
1138
+ // src/validate.ts
1139
+ function validateBundle(records) {
1140
+ const byId = new Map(records.map((record) => [record.conceptId, record]));
1141
+ const problems = [];
1142
+ const report = (check, conceptId2, note) => problems.push({ check, conceptId: conceptId2, note });
1143
+ for (const record of records) {
1144
+ const { conceptId: conceptId2, frontmatter: fm } = record;
1145
+ if (!isKbRecordType(fm.type)) {
1146
+ report("type", conceptId2, `unrecognised type "${fm.type}"`);
1147
+ }
1148
+ if (fm.strauss_status === "superseded") {
1149
+ const by = fm.strauss_superseded_by;
1150
+ if (!by) {
1151
+ report("superseded_by", conceptId2, "superseded with no replacement");
1152
+ } else if (!byId.has(by)) {
1153
+ report("superseded_by", conceptId2, `replacement ${by} is missing`);
1154
+ } else if (!byId.get(by)?.frontmatter.strauss_supersedes?.includes(conceptId2)) {
1155
+ report("backlink", by, `does not list ${conceptId2} in supersedes`);
1156
+ }
1157
+ }
1158
+ for (const old of fm.strauss_supersedes ?? []) {
1159
+ const previous = byId.get(old);
1160
+ if (!previous) {
1161
+ report("supersedes", conceptId2, `target ${old} is missing`);
1162
+ } else if (previous.frontmatter.strauss_status !== "superseded") {
1163
+ report("supersedes", conceptId2, `${old} is not marked superseded`);
1164
+ }
1165
+ }
1166
+ if (fm.strauss_assumption && fm.sources?.length) {
1167
+ report("assumption", conceptId2, "marked an assumption but cites sources");
1168
+ }
1169
+ }
1170
+ return problems;
1171
+ }
1172
+
1173
+ // src/doctor.ts
1174
+ var DEFAULT_EXPIRING_DAYS = 30;
1175
+ var DEFAULT_UNVERIFIED_DAYS = 90;
1176
+ var DEFAULT_AGING_DAYS = 90;
1177
+ var CHECK_HEADLINES = {
1178
+ expired: "past its stale_after date",
1179
+ expiring: "stale_after falls within the window",
1180
+ unverified: "nobody has ever confirmed it, and it is old enough to matter",
1181
+ aging: "still open or still proposed long after it was written",
1182
+ orphaned: "no other record links to it",
1183
+ "broken-supersession": "the supersession pointers do not resolve",
1184
+ "superseded-but-cited": "a live record's body links to one that no longer holds"
1185
+ };
1186
+ var DAY_MS = 864e5;
1187
+ function doctor(bundle, options = {}) {
1188
+ const thresholds = {
1189
+ expiringDays: options.expiringDays ?? DEFAULT_EXPIRING_DAYS,
1190
+ unverifiedDays: options.unverifiedDays ?? DEFAULT_UNVERIFIED_DAYS,
1191
+ agingDays: options.agingDays ?? DEFAULT_AGING_DAYS
1192
+ };
1193
+ const now = options.now ?? /* @__PURE__ */ new Date();
1194
+ const adjudicated = adjudicate(bundle, bundle, now);
1195
+ const standings = new Map(
1196
+ adjudicated.map((hit) => [hit.record.conceptId, hit.standing])
1197
+ );
1198
+ const inForce = adjudicated.filter(
1199
+ (hit) => hit.standing !== "superseded" && hit.standing !== "rejected"
1200
+ );
1201
+ const groups = [
1202
+ group("expired", expired(inForce, now)),
1203
+ group("expiring", expiring(inForce, now, thresholds.expiringDays)),
1204
+ group("unverified", unverified(inForce, now, thresholds.unverifiedDays)),
1205
+ group("aging", aging(inForce, now, thresholds.agingDays)),
1206
+ group("orphaned", orphaned(bundle)),
1207
+ group("broken-supersession", brokenSupersession(bundle, adjudicated)),
1208
+ group("superseded-but-cited", supersededButCited(bundle, standings))
1209
+ ];
1210
+ const counts = Object.fromEntries(
1211
+ groups.map((entry) => [entry.check, entry.count])
1212
+ );
1213
+ const findingCount = groups.reduce((total, entry) => total + entry.count, 0);
1214
+ return {
1215
+ recordCount: bundle.length,
1216
+ thresholds,
1217
+ counts,
1218
+ groups,
1219
+ findingCount,
1220
+ healthy: findingCount === 0
1221
+ };
1222
+ }
1223
+ function group(check, findings) {
1224
+ return {
1225
+ check,
1226
+ headline: CHECK_HEADLINES[check],
1227
+ count: findings.length,
1228
+ findings
1229
+ };
1230
+ }
1231
+ function expired(hits, now) {
1232
+ const findings = [];
1233
+ for (const hit of hits) {
1234
+ const raw = hit.record.frontmatter.stale_after;
1235
+ if (!raw) continue;
1236
+ const at = Date.parse(raw);
1237
+ if (Number.isNaN(at)) {
1238
+ findings.push(
1239
+ finding(hit.record, `stale_after "${raw}" is not a readable date`)
1240
+ );
1241
+ continue;
1242
+ }
1243
+ if (at < now.getTime()) {
1244
+ findings.push(
1245
+ finding(
1246
+ hit.record,
1247
+ `stale since ${raw} (${daysBetween(at, now.getTime())} days ago)`
1248
+ )
1249
+ );
1250
+ }
1251
+ }
1252
+ return findings;
1253
+ }
1254
+ function expiring(hits, now, withinDays) {
1255
+ const horizon = now.getTime() + withinDays * DAY_MS;
1256
+ const findings = [];
1257
+ for (const hit of hits) {
1258
+ const raw = hit.record.frontmatter.stale_after;
1259
+ if (!raw) continue;
1260
+ const at = Date.parse(raw);
1261
+ if (Number.isNaN(at) || at < now.getTime() || at > horizon) continue;
1262
+ findings.push(
1263
+ finding(
1264
+ hit.record,
1265
+ `goes stale ${raw} (in ${daysBetween(now.getTime(), at)} days)`
1266
+ )
1267
+ );
1268
+ }
1269
+ return findings;
1270
+ }
1271
+ function unverified(hits, now, olderThanDays) {
1272
+ const findings = [];
1273
+ for (const hit of hits) {
1274
+ if (hit.record.frontmatter.verified?.length) continue;
1275
+ const age = ageInDays(hit.record, now);
1276
+ if (age === null || age <= olderThanDays) continue;
1277
+ findings.push(
1278
+ finding(hit.record, `never verified, written ${age} days ago`)
1279
+ );
1280
+ }
1281
+ return findings;
1282
+ }
1283
+ function aging(hits, now, olderThanDays) {
1284
+ const findings = [];
1285
+ for (const hit of hits) {
1286
+ const status = hit.record.frontmatter.strauss_status;
1287
+ if (status !== "open" && status !== "proposed") continue;
1288
+ const age = ageInDays(hit.record, now);
1289
+ if (age === null || age <= olderThanDays) continue;
1290
+ findings.push(
1291
+ finding(
1292
+ hit.record,
1293
+ status === "open" ? `open for ${age} days` : `proposed ${age} days ago and still unsettled`
1294
+ )
1295
+ );
1296
+ }
1297
+ return findings.sort(
1298
+ (left, right) => left.conceptId.localeCompare(right.conceptId)
1299
+ );
1300
+ }
1301
+ function orphaned(bundle) {
1302
+ const present = new Set(bundle.map((record) => record.conceptId));
1303
+ const referenced = /* @__PURE__ */ new Set();
1304
+ for (const record of bundle) {
1305
+ for (const neighbour of edgeNeighbours(record, bundle, "body-link")) {
1306
+ referenced.add(neighbour.conceptId);
1307
+ }
1308
+ for (const replaced of record.frontmatter.strauss_supersedes ?? []) {
1309
+ referenced.add(replaced);
1310
+ }
1311
+ const replacement = record.frontmatter.strauss_superseded_by;
1312
+ if (replacement && present.has(replacement)) {
1313
+ referenced.add(record.conceptId);
1314
+ }
1315
+ }
1316
+ return bundle.filter((record) => !referenced.has(record.conceptId)).map((record) => finding(record, "no other record links to it"));
1317
+ }
1318
+ var SUPERSESSION_CHECKS = /* @__PURE__ */ new Set([
1319
+ "superseded_by",
1320
+ "supersedes",
1321
+ "backlink"
1322
+ ]);
1323
+ function brokenSupersession(bundle, adjudicated) {
1324
+ const byId = new Map(bundle.map((record) => [record.conceptId, record]));
1325
+ const findings = [];
1326
+ const seen = /* @__PURE__ */ new Set();
1327
+ const add = (record, note) => {
1328
+ const key = `${record.conceptId}\0${note}`;
1329
+ if (seen.has(key)) return;
1330
+ seen.add(key);
1331
+ findings.push(finding(record, note));
1332
+ };
1333
+ for (const problem of validateBundle(bundle)) {
1334
+ if (!SUPERSESSION_CHECKS.has(problem.check)) continue;
1335
+ const record = byId.get(problem.conceptId);
1336
+ if (record) add(record, problem.note);
1337
+ }
1338
+ for (const record of bundle) {
1339
+ const replacement = record.frontmatter.strauss_superseded_by;
1340
+ if (!replacement) continue;
1341
+ if (!byId.has(replacement)) {
1342
+ add(record, `replacement ${replacement} is missing`);
1343
+ } else if (record.frontmatter.strauss_status !== "superseded") {
1344
+ add(
1345
+ record,
1346
+ `names ${replacement} as its replacement but is not marked superseded`
1347
+ );
1348
+ }
1349
+ }
1350
+ for (const hit of adjudicated) {
1351
+ for (const warning of hit.warnings) {
1352
+ if (warning.kind === "broken-chain") {
1353
+ add(hit.record, `replacement ${warning.missing} is missing`);
1354
+ } else if (warning.kind === "chain-cycle") {
1355
+ add(
1356
+ hit.record,
1357
+ `supersession chain cycles through ${warning.through.join(" \u2192 ")}`
1358
+ );
1359
+ } else if (warning.kind === "forked-chain") {
1360
+ add(
1361
+ hit.record,
1362
+ `two records claim to replace it: ${warning.heads.join(", ")}`
1363
+ );
1364
+ }
1365
+ }
1366
+ }
1367
+ return findings.sort(
1368
+ (left, right) => left.conceptId.localeCompare(right.conceptId)
1369
+ );
1370
+ }
1371
+ function supersededButCited(bundle, standings) {
1372
+ const byId = new Map(bundle.map((record) => [record.conceptId, record]));
1373
+ const findings = [];
1374
+ for (const record of bundle) {
1375
+ const standing = standings.get(record.conceptId);
1376
+ if (standing === "superseded" || standing === "rejected") continue;
1377
+ for (const target of edgeNeighbours(record, bundle, "body-link")) {
1378
+ const targetStanding = standings.get(target.conceptId);
1379
+ if (targetStanding !== "superseded" && targetStanding !== "rejected") {
1380
+ continue;
1381
+ }
1382
+ if (replaces(record, target)) continue;
1383
+ const replacement = target.frontmatter.strauss_superseded_by;
1384
+ findings.push(
1385
+ finding(
1386
+ record,
1387
+ `cites ${targetStanding} ${target.conceptId}${targetStanding === "superseded" && replacement && byId.has(replacement) ? ` \u2014 replaced by ${replacement}` : ""}`
1388
+ )
1389
+ );
1390
+ }
1391
+ }
1392
+ return findings;
1393
+ }
1394
+ function replaces(later, earlier) {
1395
+ return (later.frontmatter.strauss_supersedes ?? []).includes(earlier.conceptId) || earlier.frontmatter.strauss_superseded_by === later.conceptId;
1396
+ }
1397
+ function finding(record, note) {
1398
+ return {
1399
+ conceptId: record.conceptId,
1400
+ title: record.frontmatter.title ?? null,
1401
+ status: record.frontmatter.strauss_status,
1402
+ note
1403
+ };
1404
+ }
1405
+ function daysBetween(from, to) {
1406
+ return Math.max(0, Math.floor((to - from) / DAY_MS));
1407
+ }
1408
+ function ageInDays(record, now) {
1409
+ const at = record.frontmatter.generated?.at;
1410
+ if (!at) return null;
1411
+ const written = Date.parse(at);
1412
+ if (Number.isNaN(written)) return null;
1413
+ return daysBetween(written, now.getTime());
1414
+ }
1415
+
1416
+ // src/commands/doctor.ts
1417
+ var days = (what, fallback) => import_zod8.z.number().int().positive().optional().describe(`${what} Defaults to ${fallback}.`);
1418
+ var doctorCommand = define({
1419
+ name: "doctor",
1420
+ tool: "kb_doctor",
1421
+ usage: "doctor [--expiring-days N] [--unverified-days N] [--aging-days N] [--strict]",
1422
+ description: "A health sweep over a whole base: what the calendar has already retired, what nobody ever confirmed, what has been open or proposed long enough that the status is now the answer, and what the graph has dropped on the floor. Read-only \u2014 it never writes, never supersedes, and never re-dates anything; every finding names a record for a person to repair. Seven checks, grouped and counted: expired (past `stale_after`), expiring (inside the window), unverified (an empty `verified[]` on a record old enough to matter), aging (still `open` or `proposed`), orphaned (no other record links to it), broken supersession (a chain that does not resolve), and superseded-but-cited (a live record whose body links to a record that no longer holds). Every group is reported even when empty, because a check that found nothing and a check that never ran look identical in a report that only lists findings.\n\nThis is the question no reader thinks to ask, which is why it needs a command: decay is invisible from inside a single record \u2014 a stale one reads exactly like a live one, and a question nobody answered reads exactly like one nobody asked. Reach for it when picking up a base someone else kept, before trusting a base you have not touched in months, or on a schedule; kb_validate is the narrower neighbour, checking only whether pointers between records agree.",
1423
+ input: import_zod8.z.object({
1424
+ bundlePath,
1425
+ expiringDays: days(
1426
+ "How far ahead `expiring` looks, in days.",
1427
+ DEFAULT_EXPIRING_DAYS
1428
+ ),
1429
+ unverifiedDays: days(
1430
+ "How old an unconfirmed record must be before `unverified` reports it, in days.",
1431
+ DEFAULT_UNVERIFIED_DAYS
1432
+ ),
1433
+ agingDays: days(
1434
+ "How long a record may stay `open` or `proposed` before `aging` reports it, in days.",
1435
+ DEFAULT_AGING_DAYS
1436
+ ),
1437
+ strict: import_zod8.z.boolean().optional().describe(
1438
+ "Turn an expired record into a non-zero exit for the CLI. No effect on the report itself."
1439
+ )
1440
+ }),
1441
+ // Presence, not truthiness: `--expiring-days ""` is a caller who meant
1442
+ // something and mistyped it, and a falsy test would answer by quietly
1443
+ // sweeping at the default. Passed through as given, the schema rejects it
1444
+ // and says which field.
1445
+ fromArgv: (argv, path) => {
1446
+ const expiring2 = argvFlag(argv, "--expiring-days");
1447
+ const unverified2 = argvFlag(argv, "--unverified-days");
1448
+ const agingDays = argvFlag(argv, "--aging-days");
1449
+ return {
1450
+ bundlePath: path,
1451
+ ...expiring2 !== void 0 ? { expiringDays: Number(expiring2) } : {},
1452
+ ...unverified2 !== void 0 ? { unverifiedDays: Number(unverified2) } : {},
1453
+ ...agingDays !== void 0 ? { agingDays: Number(agingDays) } : {},
1454
+ ...argv.includes("--strict") ? { strict: true } : {}
1455
+ };
1456
+ },
1457
+ run: async ({ store, now }, { bundlePath: path, expiringDays, unverifiedDays, agingDays }) => {
1458
+ const checkedAt = now();
1459
+ const report = doctor(await store.list(path), {
1460
+ ...expiringDays !== void 0 ? { expiringDays } : {},
1461
+ ...unverifiedDays !== void 0 ? { unverifiedDays } : {},
1462
+ ...agingDays !== void 0 ? { agingDays } : {},
1463
+ now: new Date(checkedAt)
1464
+ });
1465
+ return { bundlePath: path, checkedAt, ...report };
1466
+ },
1467
+ render: (result) => render(result),
1468
+ // Only expiry, and only under --strict. The other six checks report debt a
1469
+ // reader decides about; an expired record is the base asserting something it
1470
+ // already said it would stop standing behind, which is the one finding a
1471
+ // pipeline can act on without a judgment call.
1472
+ failsWhen: (result, input) => input.strict === true && result.counts.expired > 0
1473
+ });
1474
+ function render(result) {
1475
+ const { thresholds } = result;
1476
+ const lines = [
1477
+ `# KB Doctor \u2014 ${result.bundlePath}`,
1478
+ `records: ${result.recordCount}`,
1479
+ `thresholds: expiring within ${thresholds.expiringDays}d, unverified over ${thresholds.unverifiedDays}d, aging over ${thresholds.agingDays}d`,
1480
+ `checked: ${result.checkedAt}`,
1481
+ ""
1482
+ ];
1483
+ const width = Math.max(...result.groups.map((group2) => group2.check.length));
1484
+ for (const group2 of result.groups) {
1485
+ lines.push(
1486
+ ` ${group2.check.padEnd(width)} ${String(group2.count).padStart(3)} ${group2.headline}`
1487
+ );
1488
+ }
1489
+ for (const group2 of result.groups) {
1490
+ if (!group2.count) continue;
1491
+ lines.push("", `## ${group2.check} (${group2.count})`);
1492
+ for (const found of group2.findings) {
1493
+ lines.push(
1494
+ `- ${found.conceptId}${found.title ? ` \u2014 ${found.title}` : ""}: ${found.note}`
1495
+ );
1496
+ }
1497
+ }
1498
+ lines.push(
1499
+ "",
1500
+ 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.`
1501
+ );
1502
+ return lines.join("\n");
1503
+ }
1504
+
1505
+ // src/commands/list.ts
1506
+ var import_zod9 = require("zod");
1061
1507
  var listCommand = define({
1062
1508
  name: "list",
1063
1509
  tool: "kb_list",
1064
1510
  usage: "list [type]",
1065
1511
  description: "Every record, optionally narrowed to one type. Use kb_query when you have a question; this is for enumerating.",
1066
- input: import_zod8.z.object({ bundlePath, type: import_zod8.z.enum(KB_RECORD_TYPES).optional() }),
1512
+ input: import_zod9.z.object({ bundlePath, type: import_zod9.z.enum(KB_RECORD_TYPES).optional() }),
1067
1513
  fromArgv: (argv, path) => ({ bundlePath: path, type: argv[1] }),
1068
1514
  run: async ({ store }, { bundlePath: path, type }) => (await store.list(path, type)).map((record) => ({
1069
1515
  conceptId: record.conceptId,
@@ -1075,17 +1521,17 @@ var listCommand = define({
1075
1521
  });
1076
1522
 
1077
1523
  // src/commands/load.ts
1078
- var import_zod9 = require("zod");
1524
+ var import_zod10 = require("zod");
1079
1525
  var loadCommand = define({
1080
1526
  name: "load",
1081
1527
  tool: "kb_load",
1082
1528
  usage: "load [type] [--budget N | --all]",
1083
1529
  description: "Load the whole knowledge base at once, each record with its standing. Prefer this over searching: these bases run to a few thousand tokens, and a reader holding all of it has perfect recall and knows why it is asking, which no ranker does. Superseded records arrive under `superseded` as name, replacement and date only \u2014 their bodies no longer hold, and reading one later in a long session is the mistake this prevents; pass the id to kb_trace when you need the history. Rejected and unresolved records arrive whole: what was turned down, and what is still open, is the part a diff cannot show you. Refuses with a count rather than truncating when the base is too large \u2014 a truncated base is indistinguishable from a complete one, and would have you conclude something was never decided from a slice you did not know was a slice. Call at the point of use, not once per session: a base loaded early is summarised away by compaction, so if the visible context holds no records from this base and the question at hand is one it might govern, load before answering \u2014 never conclude nothing was decided from a context with no KB content in it. This tool (with kb_query and kb_trace) is the only supported way to read a base; a raw file read bypasses supersession resolution and returns replaced records as if current.\n\nThat refusal is the default guardrail, meant for an agent that would otherwise burn its whole context on one call. `all` bypasses it and loads everything regardless of size: a deliberate operator with the budget to spend, not something to reach for automatically. It is mutually exclusive with `budgetTokens`. When the reader does not need everything, kb_query or a narrower `type` filter is the better fit than either.",
1084
- input: import_zod9.z.object({
1530
+ input: import_zod10.z.object({
1085
1531
  bundlePath,
1086
- type: import_zod9.z.enum(KB_RECORD_TYPES).optional(),
1087
- budgetTokens: import_zod9.z.number().int().positive().optional().describe("Approximate token ceiling. Defaults to 25000."),
1088
- all: import_zod9.z.boolean().optional().describe(
1532
+ type: import_zod10.z.enum(KB_RECORD_TYPES).optional(),
1533
+ budgetTokens: import_zod10.z.number().int().positive().optional().describe("Approximate token ceiling. Defaults to 25000."),
1534
+ all: import_zod10.z.boolean().optional().describe(
1089
1535
  "Load the entire base regardless of size. The deliberate-operator escape hatch; mutually exclusive with budgetTokens."
1090
1536
  )
1091
1537
  }).refine((value) => !(value.all && value.budgetTokens !== void 0), {
@@ -1123,25 +1569,25 @@ var loadCommand = define({
1123
1569
  });
1124
1570
 
1125
1571
  // src/commands/log.ts
1126
- var import_zod10 = require("zod");
1572
+ var import_zod11 = require("zod");
1127
1573
  var logCommand = define({
1128
1574
  name: "log",
1129
1575
  tool: "kb_log",
1130
1576
  usage: "log",
1131
1577
  description: "What touched what, and when. The only artifact here that cannot be reconstructed from the records, so malformed lines are reported rather than repaired.",
1132
- input: import_zod10.z.object({ bundlePath }),
1578
+ input: import_zod11.z.object({ bundlePath }),
1133
1579
  fromArgv: (_argv, path) => ({ bundlePath: path }),
1134
1580
  run: ({ store }, { bundlePath: path }) => store.readLog(path)
1135
1581
  });
1136
1582
 
1137
1583
  // src/commands/no-decision.ts
1138
- var import_zod11 = require("zod");
1584
+ var import_zod12 = require("zod");
1139
1585
  var noDecisionCommand = define({
1140
1586
  name: "no-decision",
1141
1587
  tool: "kb_no_decision",
1142
1588
  usage: "no-decision <reason...>",
1143
1589
  description: 'Claim in one sentence that there was nothing to decide. Gating on "did you write a decision?" rewards writing a junk one; gating on "did you answer?" does not, so silence has to be expressible. Idempotent \u2014 restating it is not a collision.',
1144
- input: import_zod11.z.object({ bundlePath, reason: import_zod11.z.string().min(1) }),
1590
+ input: import_zod12.z.object({ bundlePath, reason: import_zod12.z.string().min(1) }),
1145
1591
  fromArgv: (argv, path) => ({
1146
1592
  bundlePath: path,
1147
1593
  reason: argv.slice(1).join(" ").trim()
@@ -1157,23 +1603,123 @@ var noDecisionCommand = define({
1157
1603
  }
1158
1604
  });
1159
1605
 
1606
+ // src/commands/pack.ts
1607
+ var import_zod13 = require("zod");
1608
+ var packCommand = define({
1609
+ name: "pack",
1610
+ tool: "kb_pack",
1611
+ usage: "pack <conceptId> [--hops N] [--max-nodes N] [--budget N]",
1612
+ description: "The bounded neighbourhood around one record: everything within `hops` of the root, ranked and cut to `maxNodes`, with every cut record named under Excluded \u2014 a named gap is knowable, a silent one is not. Prefer this over kb_load when the base is too large to hold whole and the work centres on one record; prefer it over kb_query when the question needs the governed neighbourhood \u2014 what was settled and what binds near this record \u2014 rather than a lookup by wording. Superseded records arrive as name, replacement and date stubs exactly as kb_load emits them: their bodies no longer hold, and kb_trace has the history. Refuses outright rather than truncating when the pack would exceed its token budget \u2014 a partial pack is indistinguishable from a complete one \u2014 reporting the record count and every already-cut id so the caller can lower hops or maxNodes, or raise the budget. The header carries the bundle, root, budget and a timestamp; everything below the header is byte-identical across runs over an unchanged base, so two packs can be diffed and a changed byte means changed knowledge. This tool (with kb_load, kb_query and kb_trace) is the only supported way to read a base; a raw file read bypasses supersession resolution and returns replaced records as if current.",
1613
+ input: import_zod13.z.object({
1614
+ bundlePath,
1615
+ conceptId,
1616
+ hops: import_zod13.z.number().int().positive().optional().describe("How far from the root the walk may reach. Defaults to 2."),
1617
+ maxNodes: import_zod13.z.number().int().positive().optional().describe(
1618
+ "How many records the pack may hold, root included. Defaults to 20."
1619
+ ),
1620
+ budgetTokens: import_zod13.z.number().int().positive().optional().describe(
1621
+ "Approximate token ceiling over what is actually emitted. Defaults to 25000."
1622
+ )
1623
+ }),
1624
+ fromArgv: (argv, path) => {
1625
+ const hops = argvFlag(argv, "--hops");
1626
+ const maxNodes = argvFlag(argv, "--max-nodes");
1627
+ const budget = argvFlag(argv, "--budget");
1628
+ return {
1629
+ bundlePath: path,
1630
+ conceptId: argv[1],
1631
+ ...hops ? { hops: Number(hops) } : {},
1632
+ ...maxNodes ? { maxNodes: Number(maxNodes) } : {},
1633
+ ...budget ? { budgetTokens: Number(budget) } : {}
1634
+ };
1635
+ },
1636
+ run: async ({ store, now }, { bundlePath: path, conceptId: root, hops, maxNodes, budgetTokens }) => {
1637
+ const result = await store.pack(path, root, {
1638
+ ...hops !== void 0 ? { hops } : {},
1639
+ ...maxNodes !== void 0 ? { maxNodes } : {},
1640
+ ...budgetTokens !== void 0 ? { budgetTokens } : {}
1641
+ });
1642
+ return render2(result, path, now());
1643
+ }
1644
+ });
1645
+ function render2(result, bundle, at) {
1646
+ const lines = [
1647
+ `# KB Pack \u2014 ${result.root}`,
1648
+ `bundle: ${bundle}`,
1649
+ `budget: ~${result.tokensLoaded} of ${result.budgetTokens} tokens, ${result.recordCount} records`,
1650
+ `packed: ${at}`,
1651
+ "",
1652
+ `## Records (${result.records.length})`
1653
+ ];
1654
+ for (const record of result.records) {
1655
+ lines.push(
1656
+ "",
1657
+ `### ${record.conceptId}${record.title ? ` \u2014 ${record.title}` : ""} [${record.standing}]`
1658
+ );
1659
+ if (record.warnings.length) {
1660
+ lines.push(`warnings: ${record.warnings.map(warningLabel).join("; ")}`);
1661
+ }
1662
+ if (record.anchors.length) {
1663
+ lines.push(
1664
+ `anchors: ${record.anchors.map(
1665
+ (anchor) => anchor.symbol ? `${anchor.file}#${anchor.symbol}` : anchor.file
1666
+ ).join(", ")}`
1667
+ );
1668
+ }
1669
+ lines.push("", record.body.trimEnd());
1670
+ }
1671
+ if (result.superseded.length) {
1672
+ lines.push("", `## Superseded (${result.superseded.length})`);
1673
+ for (const entry of result.superseded) {
1674
+ lines.push(
1675
+ `- ${entry.conceptId} \u2192 ${entry.supersededBy.join(", ") || "(no surviving head)"}${entry.at ? ` (${entry.at})` : ""}`
1676
+ );
1677
+ }
1678
+ }
1679
+ if (result.excluded.length) {
1680
+ lines.push("", `## Excluded (${result.excluded.length})`);
1681
+ for (const cut of result.excluded) lines.push(`- ${cut}`);
1682
+ }
1683
+ return lines.join("\n");
1684
+ }
1685
+ function warningLabel(warning) {
1686
+ switch (warning.kind) {
1687
+ case "superseded":
1688
+ return `superseded by ${warning.by.join(", ")}`;
1689
+ case "unsettled":
1690
+ return `unsettled (${warning.status})`;
1691
+ case "broken-chain":
1692
+ return `broken chain \u2014 ${warning.missing} is not in the bundle`;
1693
+ case "chain-cycle":
1694
+ return `chain cycle through ${warning.through.join(" \u2192 ")}`;
1695
+ case "forked-chain":
1696
+ return `forked chain \u2014 heads ${warning.heads.join(", ")}`;
1697
+ case "stale":
1698
+ return `stale since ${warning.staleAfter}`;
1699
+ case "unresolved-question":
1700
+ return "unresolved question";
1701
+ default:
1702
+ return warning.kind;
1703
+ }
1704
+ }
1705
+
1160
1706
  // src/commands/pin.ts
1161
- var import_zod12 = require("zod");
1707
+ var import_zod14 = require("zod");
1162
1708
  var pinCommand = define({
1163
1709
  name: "pin",
1164
1710
  tool: "kb_pin",
1165
1711
  usage: "pin [bundle-path] [--mode full|index] [--profiles a,b] [--local|--user] [--frozen|--unfreeze]",
1166
1712
  description: "Pin a base into a workspace pin manifest, so `context` surfaces it at every context birth. Three layers, nearest wins: the committed project manifest (.strauss/kb-pins.json, the default), `--local` (.strauss/kb-pins.local.json, personal and gitignored), and `--user` (~/.strauss/kb-pins.json, every workspace). Idempotent \u2014 re-pinning changes nothing unless --mode, --profiles, or --frozen/--unfreeze are given, which update just those fields. `--mode full` preloads the whole base into the block regardless of the full-under threshold; `--mode index` never upgrades. `--profiles` scopes the pin to named context profiles. `--frozen` marks the base concluded: write commands against it refuse and `context` labels it read-only. A path with no records yet succeeds with a warning; bases are routinely pinned before they are populated. Pins are workspace state: the pinned base itself is never touched.",
1167
- input: import_zod12.z.object({
1713
+ input: import_zod14.z.object({
1168
1714
  bundlePath,
1169
- mode: import_zod12.z.enum(["full", "index"]).optional().describe(
1715
+ mode: import_zod14.z.enum(["full", "index"]).optional().describe(
1170
1716
  "full: always emit this base's records whole (still under the block budget); index: never upgrade. Absent: the profile's full-under threshold decides."
1171
1717
  ),
1172
- profiles: import_zod12.z.array(import_zod12.z.string()).optional().describe("Context profiles this pin surfaces in. Absent: all of them."),
1173
- layer: import_zod12.z.enum(["project", "local", "user"]).optional().describe(
1718
+ profiles: import_zod14.z.array(import_zod14.z.string()).optional().describe("Context profiles this pin surfaces in. Absent: all of them."),
1719
+ layer: import_zod14.z.enum(["project", "local", "user"]).optional().describe(
1174
1720
  "Which manifest to write: project (committed, default), local (personal, gitignored), user (~/.strauss, every workspace)."
1175
1721
  ),
1176
- frozen: import_zod12.z.boolean().optional().describe(
1722
+ frozen: import_zod14.z.boolean().optional().describe(
1177
1723
  "true: the base is concluded \u2014 writes against it refuse while pinned. false: lift a freeze."
1178
1724
  )
1179
1725
  }),
@@ -1202,29 +1748,29 @@ var pinCommand = define({
1202
1748
  });
1203
1749
 
1204
1750
  // src/commands/pins.ts
1205
- var import_zod13 = require("zod");
1751
+ var import_zod15 = require("zod");
1206
1752
  var pinsCommand = define({
1207
1753
  name: "pins",
1208
1754
  tool: "kb_pins",
1209
1755
  usage: "pins",
1210
1756
  description: "Every pinned base across the manifest layers, each with its layer and whether it currently resolves to readable records. Reads the workspace manifests rather than any one base, like kb_context.",
1211
- input: import_zod13.z.object({}),
1757
+ input: import_zod15.z.object({}),
1212
1758
  fromArgv: () => ({}),
1213
1759
  run: ({ store }) => listPins(store, process.cwd())
1214
1760
  });
1215
1761
 
1216
1762
  // src/commands/query.ts
1217
- var import_zod14 = require("zod");
1763
+ var import_zod16 = require("zod");
1218
1764
  var queryCommand = define({
1219
1765
  name: "query",
1220
1766
  tool: "kb_query",
1221
1767
  usage: "query <text...>",
1222
1768
  description: "Search and return each match with its standing. Results are flagged, never filtered: a superseded record comes back alongside whatever replaced it, and a rejected one is marked as something explicitly not adopted. Prefer kb_load when the base fits its budget: on this package's measurements, a reader holding the whole base answered eight of nine questions whose wording appears in no record, where embedding search answered four. Never read record files directly \u2014 this tool (with kb_load and kb_trace) is the only supported way to read a base; a file read bypasses supersession resolution and returns replaced records as if current.",
1223
- input: import_zod14.z.object({
1769
+ input: import_zod16.z.object({
1224
1770
  bundlePath,
1225
- text: import_zod14.z.string().optional(),
1226
- type: import_zod14.z.enum(KB_RECORD_TYPES).optional(),
1227
- includeNonCurrent: import_zod14.z.boolean().optional()
1771
+ text: import_zod16.z.string().optional(),
1772
+ type: import_zod16.z.enum(KB_RECORD_TYPES).optional(),
1773
+ includeNonCurrent: import_zod16.z.boolean().optional()
1228
1774
  }),
1229
1775
  fromArgv: (argv, path) => ({
1230
1776
  bundlePath: path,
@@ -1246,33 +1792,33 @@ var queryCommand = define({
1246
1792
  });
1247
1793
 
1248
1794
  // src/commands/read-index.ts
1249
- var import_zod15 = require("zod");
1795
+ var import_zod17 = require("zod");
1250
1796
  var readIndexCommand = define({
1251
1797
  name: "index",
1252
1798
  tool: "kb_index",
1253
1799
  usage: "index",
1254
1800
  description: "The index, rebuilt if it disagrees with the records. One call gives the whole shape of the base: title, type, status, and description per record. The cheap re-orientation call after compaction or deep in a long session \u2014 a few hundred tokens; call it (or kb_context, when bases are pinned) first, then kb_load or fetch by concept id.",
1255
- input: import_zod15.z.object({ bundlePath }),
1801
+ input: import_zod17.z.object({ bundlePath }),
1256
1802
  fromArgv: (_argv, path) => ({ bundlePath: path }),
1257
1803
  run: ({ store }, { bundlePath: path }) => store.readIndex(path)
1258
1804
  });
1259
1805
 
1260
1806
  // src/commands/schema.ts
1261
- var import_zod18 = require("zod");
1807
+ var import_zod20 = require("zod");
1262
1808
 
1263
1809
  // src/json-schema.ts
1264
- var import_zod17 = require("zod");
1810
+ var import_zod19 = require("zod");
1265
1811
 
1266
1812
  // src/kb-log.ts
1267
- var import_zod16 = require("zod");
1813
+ var import_zod18 = require("zod");
1268
1814
  var LOG_FILE = "log.jsonl";
1269
- var kbLogEntrySchema = import_zod16.z.object({
1270
- at: import_zod16.z.string().min(1),
1271
- by: import_zod16.z.string().min(1),
1272
- operation: import_zod16.z.string().min(1),
1273
- conceptId: import_zod16.z.string().min(1),
1815
+ var kbLogEntrySchema = import_zod18.z.object({
1816
+ at: import_zod18.z.string().min(1),
1817
+ by: import_zod18.z.string().min(1),
1818
+ operation: import_zod18.z.string().min(1),
1819
+ conceptId: import_zod18.z.string().min(1),
1274
1820
  /** Second concept id, where the operation relates two — supersession. */
1275
- target: import_zod16.z.string().min(1).optional()
1821
+ target: import_zod18.z.string().min(1).optional()
1276
1822
  }).strict();
1277
1823
  function renderLogEntry(entry) {
1278
1824
  return `${JSON.stringify(kbLogEntrySchema.parse(entry))}
@@ -1303,11 +1849,11 @@ function parseLog(raw) {
1303
1849
  // src/json-schema.ts
1304
1850
  function kbJsonSchemas() {
1305
1851
  return {
1306
- recordFrontmatter: import_zod17.z.toJSONSchema(kbRecordFrontmatterSchema, {
1852
+ recordFrontmatter: import_zod19.z.toJSONSchema(kbRecordFrontmatterSchema, {
1307
1853
  io: "input"
1308
1854
  }),
1309
- composeInput: import_zod17.z.toJSONSchema(composeInputSchema, { io: "input" }),
1310
- logEntry: import_zod17.z.toJSONSchema(kbLogEntrySchema, { io: "input" })
1855
+ composeInput: import_zod19.z.toJSONSchema(composeInputSchema, { io: "input" }),
1856
+ logEntry: import_zod19.z.toJSONSchema(kbLogEntrySchema, { io: "input" })
1311
1857
  };
1312
1858
  }
1313
1859
 
@@ -1317,22 +1863,22 @@ var schemaCommand = define({
1317
1863
  tool: "kb_schema",
1318
1864
  usage: "schema",
1319
1865
  description: "JSON Schema for the frontmatter, the write input, and log entries \u2014 generated from the code that enforces them, so it cannot drift from what a write will accept.",
1320
- input: import_zod18.z.object({}),
1866
+ input: import_zod20.z.object({}),
1321
1867
  fromArgv: () => ({}),
1322
1868
  run: () => Promise.resolve(kbJsonSchemas())
1323
1869
  });
1324
1870
 
1325
1871
  // src/commands/status.ts
1326
- var import_zod19 = require("zod");
1872
+ var import_zod21 = require("zod");
1327
1873
  var statusCommand = define({
1328
1874
  name: "status",
1329
1875
  tool: "kb_status",
1330
1876
  usage: "status <concept-id> <status>",
1331
1877
  description: "Move a record's status, leaving everything else alone. Uses a compare-and-swap, so a concurrent change fails loudly rather than being overwritten.",
1332
- input: import_zod19.z.object({
1878
+ input: import_zod21.z.object({
1333
1879
  bundlePath,
1334
1880
  conceptId,
1335
- status: import_zod19.z.enum(KB_RECORD_STATUSES)
1881
+ status: import_zod21.z.enum(KB_RECORD_STATUSES)
1336
1882
  }),
1337
1883
  fromArgv: (argv, path) => ({
1338
1884
  bundlePath: path,
@@ -1347,13 +1893,13 @@ var statusCommand = define({
1347
1893
  });
1348
1894
 
1349
1895
  // src/commands/supersede.ts
1350
- var import_zod20 = require("zod");
1896
+ var import_zod22 = require("zod");
1351
1897
  var supersedeCommand = define({
1352
1898
  name: "supersede",
1353
1899
  tool: "kb_supersede",
1354
1900
  usage: "supersede <concept-id> <replacement-id>",
1355
1901
  description: "Mark a record superseded by another, linking both directions. Use this rather than editing a record whose meaning changed \u2014 a record that quietly becomes something else invalidates every reference to it, and the earlier understanding is what a later trace needs.",
1356
- input: import_zod20.z.object({ bundlePath, conceptId, replacementId: conceptId }),
1902
+ input: import_zod22.z.object({ bundlePath, conceptId, replacementId: conceptId }),
1357
1903
  fromArgv: (argv, path) => ({
1358
1904
  bundlePath: path,
1359
1905
  conceptId: argv[1],
@@ -1367,16 +1913,16 @@ var supersedeCommand = define({
1367
1913
  });
1368
1914
 
1369
1915
  // src/commands/sync-instructions.ts
1370
- var import_zod21 = require("zod");
1916
+ var import_zod23 = require("zod");
1371
1917
  var syncInstructionsCommand = define({
1372
1918
  name: "sync-instructions",
1373
1919
  usage: "sync-instructions <file> [--profile NAME] [--budget N] [--full-under N]",
1374
1920
  description: "Idempotently plant the `context` block between sentinel comments in an instruction file (AGENTS.md, CLAUDE.md), creating the block when absent and leaving everything outside the sentinels alone. CLI-only: this is file plumbing for runtimes whose instruction files are re-read where their conversations are not, not an agent capability \u2014 the capability is kb_context.",
1375
- input: import_zod21.z.object({
1376
- file: import_zod21.z.string().min(1).describe("The instruction file to edit in place."),
1377
- budgetTokens: import_zod21.z.number().int().positive().optional(),
1378
- fullUnderTokens: import_zod21.z.number().int().positive().optional(),
1379
- profile: import_zod21.z.string().optional()
1921
+ input: import_zod23.z.object({
1922
+ file: import_zod23.z.string().min(1).describe("The instruction file to edit in place."),
1923
+ budgetTokens: import_zod23.z.number().int().positive().optional(),
1924
+ fullUnderTokens: import_zod23.z.number().int().positive().optional(),
1925
+ profile: import_zod23.z.string().optional()
1380
1926
  }),
1381
1927
  fromArgv: (argv) => {
1382
1928
  const budget = argvFlag(argv, "--budget");
@@ -1402,7 +1948,7 @@ var syncInstructionsCommand = define({
1402
1948
  });
1403
1949
 
1404
1950
  // src/commands/trace.ts
1405
- var import_zod22 = require("zod");
1951
+ var import_zod24 = require("zod");
1406
1952
 
1407
1953
  // src/trace.ts
1408
1954
  var TRACE_EDGES = ["supersession", "anchor", "source"];
@@ -1420,7 +1966,7 @@ function trace(seedId, bundle, options = {}) {
1420
1966
  const next = [];
1421
1967
  for (const from of frontier) {
1422
1968
  for (const edge of edges) {
1423
- for (const record of neighbours(from, bundle, edge)) {
1969
+ for (const record of edgeNeighbours(from, bundle, edge)) {
1424
1970
  const existing = reached.get(record.conceptId);
1425
1971
  if (existing) {
1426
1972
  if (existing.depth > 0 && !existing.via.includes(edge)) {
@@ -1437,41 +1983,6 @@ function trace(seedId, bundle, options = {}) {
1437
1983
  }
1438
1984
  return [...reached.values()].sort(byGeneratedAt);
1439
1985
  }
1440
- function neighbours(from, bundle, edge) {
1441
- switch (edge) {
1442
- case "supersession":
1443
- return bundle.filter(
1444
- (candidate) => candidate.conceptId !== from.conceptId && (candidate.conceptId === from.frontmatter.strauss_superseded_by || from.frontmatter.strauss_supersedes?.includes(
1445
- candidate.conceptId
1446
- ) || candidate.frontmatter.strauss_superseded_by === from.conceptId || candidate.frontmatter.strauss_supersedes?.includes(from.conceptId))
1447
- );
1448
- // The edge that answers "why is this code shaped this way": every record
1449
- // attached to the same file or symbol, whatever its standing.
1450
- case "anchor": {
1451
- const mine = from.frontmatter.strauss_anchors ?? [];
1452
- if (!mine.length) return [];
1453
- return bundle.filter(
1454
- (candidate) => candidate.conceptId !== from.conceptId && (candidate.frontmatter.strauss_anchors ?? []).some(
1455
- (theirs) => mine.some((ours) => anchorsTouch(ours, theirs))
1456
- )
1457
- );
1458
- }
1459
- case "source": {
1460
- const mine = new Set((from.frontmatter.sources ?? []).map((s) => s.id));
1461
- if (!mine.size) return [];
1462
- return bundle.filter(
1463
- (candidate) => candidate.conceptId !== from.conceptId && (candidate.frontmatter.sources ?? []).some(
1464
- (source) => mine.has(source.id)
1465
- )
1466
- );
1467
- }
1468
- }
1469
- }
1470
- function anchorsTouch(left, right) {
1471
- if (left.file !== right.file) return false;
1472
- if (!left.symbol || !right.symbol) return true;
1473
- return left.symbol === right.symbol;
1474
- }
1475
1986
  function byGeneratedAt(left, right) {
1476
1987
  const at = (step) => step.record.frontmatter.generated?.at ?? "";
1477
1988
  return at(left).localeCompare(at(right)) || left.depth - right.depth;
@@ -1483,11 +1994,11 @@ var traceCommand = define({
1483
1994
  tool: "kb_trace",
1484
1995
  usage: "trace <concept-id> [edges...]",
1485
1996
  description: 'How a position was arrived at, as a timeline ordered by when each record was written. Deliberately includes rejected, draft, and superseded records \u2014 in a history those are the content, not noise. Follows supersession, shared code anchors, and shared sources. Use when the question is "why is this the way it is" rather than "what do we hold now". This tool (with kb_load and kb_query) is the only supported way to read a base; a raw file read bypasses supersession resolution and returns replaced records as if current.',
1486
- input: import_zod22.z.object({
1997
+ input: import_zod24.z.object({
1487
1998
  bundlePath,
1488
1999
  conceptId,
1489
- edges: import_zod22.z.array(import_zod22.z.enum(TRACE_EDGES)).optional(),
1490
- depth: import_zod22.z.number().int().positive().optional()
2000
+ edges: import_zod24.z.array(import_zod24.z.enum(TRACE_EDGES)).optional(),
2001
+ depth: import_zod24.z.number().int().positive().optional()
1491
2002
  }),
1492
2003
  fromArgv: (argv, path) => ({
1493
2004
  bundlePath: path,
@@ -1509,90 +2020,53 @@ var traceCommand = define({
1509
2020
  });
1510
2021
 
1511
2022
  // src/commands/types.ts
1512
- var import_zod23 = require("zod");
2023
+ var import_zod25 = require("zod");
1513
2024
  var typesCommand = define({
1514
2025
  name: "types",
1515
2026
  tool: "kb_types",
1516
2027
  usage: "types",
1517
2028
  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.",
1518
- input: import_zod23.z.object({}),
2029
+ input: import_zod25.z.object({}),
1519
2030
  fromArgv: () => ({}),
1520
2031
  run: () => Promise.resolve(RECORD_TYPES)
1521
2032
  });
1522
2033
 
1523
2034
  // src/commands/unpin.ts
1524
- var import_zod24 = require("zod");
2035
+ var import_zod26 = require("zod");
1525
2036
  var unpinCommand = define({
1526
2037
  name: "unpin",
1527
2038
  tool: "kb_unpin",
1528
2039
  usage: "unpin [bundle-path]",
1529
2040
  description: "Remove a base from every pin manifest layer that holds it \u2014 project, local, and user \u2014 because unpinned means gone, not still injected from another file. Reports which layers were touched.",
1530
- input: import_zod24.z.object({ bundlePath }),
2041
+ input: import_zod26.z.object({ bundlePath }),
1531
2042
  fromArgv: (argv, path) => ({ bundlePath: argv[1] ?? path }),
1532
2043
  run: (_ctx, { bundlePath: path }) => unpinBase(process.cwd(), path)
1533
2044
  });
1534
2045
 
1535
2046
  // src/commands/validate.ts
1536
- var import_zod25 = require("zod");
1537
-
1538
- // src/validate.ts
1539
- function validateBundle(records) {
1540
- const byId = new Map(records.map((record) => [record.conceptId, record]));
1541
- const problems = [];
1542
- const report = (check, conceptId2, note) => problems.push({ check, conceptId: conceptId2, note });
1543
- for (const record of records) {
1544
- const { conceptId: conceptId2, frontmatter: fm } = record;
1545
- if (!isKbRecordType(fm.type)) {
1546
- report("type", conceptId2, `unrecognised type "${fm.type}"`);
1547
- }
1548
- if (fm.strauss_status === "superseded") {
1549
- const by = fm.strauss_superseded_by;
1550
- if (!by) {
1551
- report("superseded_by", conceptId2, "superseded with no replacement");
1552
- } else if (!byId.has(by)) {
1553
- report("superseded_by", conceptId2, `replacement ${by} is missing`);
1554
- } else if (!byId.get(by)?.frontmatter.strauss_supersedes?.includes(conceptId2)) {
1555
- report("backlink", by, `does not list ${conceptId2} in supersedes`);
1556
- }
1557
- }
1558
- for (const old of fm.strauss_supersedes ?? []) {
1559
- const previous = byId.get(old);
1560
- if (!previous) {
1561
- report("supersedes", conceptId2, `target ${old} is missing`);
1562
- } else if (previous.frontmatter.strauss_status !== "superseded") {
1563
- report("supersedes", conceptId2, `${old} is not marked superseded`);
1564
- }
1565
- }
1566
- if (fm.strauss_assumption && fm.sources?.length) {
1567
- report("assumption", conceptId2, "marked an assumption but cites sources");
1568
- }
1569
- }
1570
- return problems;
1571
- }
1572
-
1573
- // src/commands/validate.ts
2047
+ var import_zod27 = require("zod");
1574
2048
  var validateCommand = define({
1575
2049
  name: "validate",
1576
2050
  tool: "kb_validate",
1577
2051
  usage: "validate",
1578
2052
  description: "Check pointers no single record can see: supersession links that disagree between the two records, and assumptions that cite sources. Per-record shape is enforced on every read, so a problem here means someone edited a file by hand.",
1579
- input: import_zod25.z.object({ bundlePath }),
2053
+ input: import_zod27.z.object({ bundlePath }),
1580
2054
  fromArgv: (_argv, path) => ({ bundlePath: path }),
1581
2055
  run: async ({ store }, { bundlePath: path }) => validateBundle(await store.list(path)),
1582
2056
  failsWhen: (result) => Array.isArray(result) && result.length > 0
1583
2057
  });
1584
2058
 
1585
2059
  // src/commands/verify.ts
1586
- var import_zod26 = require("zod");
2060
+ var import_zod28 = require("zod");
1587
2061
  var verifyCommand = define({
1588
2062
  name: "verify",
1589
2063
  tool: "kb_verify",
1590
2064
  usage: "verify <concept-id> --note <text>",
1591
2065
  description: "Append one verified[] event \u2014 who checked the record, when, and what the check found. Appends only; prior events are never rewritten. A record's own generator is refused unless the actor is human: re-reading your own output is not an independent check.",
1592
- input: import_zod26.z.object({
2066
+ input: import_zod28.z.object({
1593
2067
  bundlePath,
1594
2068
  conceptId,
1595
- note: import_zod26.z.string().refine((s) => s.trim().length > 0, {
2069
+ note: import_zod28.z.string().refine((s) => s.trim().length > 0, {
1596
2070
  message: "note must say what the check found"
1597
2071
  })
1598
2072
  }),
@@ -1612,7 +2086,7 @@ var verifyCommand = define({
1612
2086
  });
1613
2087
 
1614
2088
  // src/commands/write.ts
1615
- var import_zod27 = require("zod");
2089
+ var import_zod29 = require("zod");
1616
2090
  var writeCommand = define({
1617
2091
  name: "write",
1618
2092
  tool: "kb_write",
@@ -1626,9 +2100,9 @@ var writeCommand = define({
1626
2100
  "- Prefer a new record over overloading an existing one, and keep each short. A record nobody finishes reading is not durable memory.",
1627
2101
  "- Records are never deleted; supersede instead, so the earlier reasoning stays inspectable."
1628
2102
  ].join("\n"),
1629
- input: import_zod27.z.object({
2103
+ input: import_zod29.z.object({
1630
2104
  bundlePath,
1631
- type: import_zod27.z.enum(KB_RECORD_TYPES),
2105
+ type: import_zod29.z.enum(KB_RECORD_TYPES),
1632
2106
  input: composeInputSchema
1633
2107
  }),
1634
2108
  fromArgv: async (argv, path, stdin) => ({
@@ -1652,7 +2126,7 @@ var writeCommand = define({
1652
2126
  });
1653
2127
 
1654
2128
  // src/commands/write-decision.ts
1655
- var import_zod28 = require("zod");
2129
+ var import_zod30 = require("zod");
1656
2130
  var writeDecisionCommand = define({
1657
2131
  name: "write-decision",
1658
2132
  tool: "kb_write_decision",
@@ -1665,7 +2139,7 @@ var writeDecisionCommand = define({
1665
2139
  "- `alternative` is what you turned down and why, not a list of everything considered.",
1666
2140
  "- A reference to material you read goes in `sources`; a reference to code goes in `anchors`; a reference to another record goes in `relatedConceptIds`."
1667
2141
  ].join("\n"),
1668
- input: import_zod28.z.object({ bundlePath, input: decisionInputSchema }),
2142
+ input: import_zod30.z.object({ bundlePath, input: decisionInputSchema }),
1669
2143
  fromArgv: async (_argv, path, stdin) => ({
1670
2144
  bundlePath: path,
1671
2145
  input: JSON.parse(await stdin())
@@ -1695,12 +2169,14 @@ var KB_COMMANDS = [
1695
2169
  answerCommand,
1696
2170
  verifyCommand,
1697
2171
  loadCommand,
2172
+ packCommand,
1698
2173
  queryCommand,
1699
2174
  traceCommand,
1700
2175
  listCommand,
1701
2176
  readIndexCommand,
1702
2177
  logCommand,
1703
2178
  validateCommand,
2179
+ doctorCommand,
1704
2180
  schemaCommand,
1705
2181
  pinCommand,
1706
2182
  unpinCommand,
@@ -1828,6 +2304,27 @@ var KbSelfVerificationError = class extends BaseError {
1828
2304
  actor;
1829
2305
  generatedBy;
1830
2306
  };
2307
+ var KbPackBudgetExceededError = class extends BaseError {
2308
+ constructor(recordCount, approxTokens2, budgetTokens, excluded) {
2309
+ super({
2310
+ message: `kb: a pack of ${recordCount} records is ~${approxTokens2} tokens against a budget of ${budgetTokens} \u2014 lower hops or maxNodes, or raise the budget`,
2311
+ errorType: "KbPackBudgetExceeded" /* KbPackBudgetExceeded */,
2312
+ code: 400,
2313
+ fault: "User" /* User */,
2314
+ retriable: false,
2315
+ reportToUser: true,
2316
+ details: { recordCount, approxTokens: approxTokens2, budgetTokens, excluded }
2317
+ });
2318
+ this.recordCount = recordCount;
2319
+ this.approxTokens = approxTokens2;
2320
+ this.budgetTokens = budgetTokens;
2321
+ this.excluded = excluded;
2322
+ }
2323
+ recordCount;
2324
+ approxTokens;
2325
+ budgetTokens;
2326
+ excluded;
2327
+ };
1831
2328
  var KbInvalidConceptIdError = class extends BaseError {
1832
2329
  constructor(message, details) {
1833
2330
  super({
@@ -1928,6 +2425,90 @@ async function loadQmd(logger) {
1928
2425
  }
1929
2426
  }
1930
2427
 
2428
+ // src/pack.ts
2429
+ var DEFAULT_PACK_HOPS = 2;
2430
+ var DEFAULT_PACK_MAX_NODES = 20;
2431
+ var TYPE_PRIORITY = [
2432
+ "decision",
2433
+ "constraint",
2434
+ "requirement",
2435
+ ...KB_RECORD_TYPES.filter(
2436
+ (type) => !["decision", "constraint", "requirement"].includes(type)
2437
+ )
2438
+ ];
2439
+ function pack(bundle, rootId, options = {}) {
2440
+ const hops = options.hops ?? DEFAULT_PACK_HOPS;
2441
+ const maxNodes = options.maxNodes ?? DEFAULT_PACK_MAX_NODES;
2442
+ const budgetTokens = options.budgetTokens ?? DEFAULT_LOAD_BUDGET;
2443
+ const byId = new Map(bundle.map((record) => [record.conceptId, record]));
2444
+ const root = byId.get(rootId);
2445
+ if (!root) throw new KbRecordNotFoundError(rootId);
2446
+ const reached = [{ record: root, depth: 0 }];
2447
+ const seen = /* @__PURE__ */ new Set([rootId]);
2448
+ let frontier = [root];
2449
+ for (let depth = 1; frontier.length; depth += 1) {
2450
+ const next = [];
2451
+ for (const from of frontier) {
2452
+ for (const { record } of neighbours(from, bundle)) {
2453
+ if (seen.has(record.conceptId)) continue;
2454
+ seen.add(record.conceptId);
2455
+ reached.push({ record, depth });
2456
+ next.push(record);
2457
+ }
2458
+ }
2459
+ frontier = next;
2460
+ }
2461
+ reached.sort(byRank);
2462
+ const within = reached.filter((entry) => entry.depth <= hops);
2463
+ const kept = within.slice(0, maxNodes);
2464
+ const excluded = [
2465
+ ...within.slice(maxNodes),
2466
+ ...reached.filter((entry) => entry.depth > hops)
2467
+ ].map((entry) => entry.record.conceptId).sort();
2468
+ const adjudicated = adjudicate(
2469
+ kept.map((entry) => entry.record),
2470
+ bundle
2471
+ );
2472
+ const superseded = adjudicated.filter((hit) => hit.standing === "superseded").map(stub);
2473
+ const whole = adjudicated.filter((hit) => hit.standing !== "superseded");
2474
+ const tokensLoaded = whole.reduce((total, hit) => total + estimateTokens(hit.record), 0) + superseded.reduce((total, entry) => total + estimateStubTokens(entry), 0);
2475
+ const recordCount = adjudicated.length;
2476
+ if (tokensLoaded > budgetTokens) {
2477
+ throw new KbPackBudgetExceededError(
2478
+ recordCount,
2479
+ tokensLoaded,
2480
+ budgetTokens,
2481
+ excluded
2482
+ );
2483
+ }
2484
+ return {
2485
+ root: rootId,
2486
+ records: whole.map((hit) => ({
2487
+ conceptId: hit.record.conceptId,
2488
+ title: hit.record.frontmatter.title ?? null,
2489
+ standing: hit.standing,
2490
+ supersededBy: hit.heads.map((head) => head.conceptId),
2491
+ warnings: hit.warnings,
2492
+ anchors: hit.record.frontmatter.strauss_anchors ?? [],
2493
+ body: hit.record.body
2494
+ })),
2495
+ superseded,
2496
+ excluded,
2497
+ recordCount,
2498
+ tokensLoaded,
2499
+ budgetTokens
2500
+ };
2501
+ }
2502
+ function byRank(left, right) {
2503
+ return left.depth - right.depth || typeRank(left.record) - typeRank(right.record) || (left.record.frontmatter.title ?? "").localeCompare(
2504
+ right.record.frontmatter.title ?? ""
2505
+ ) || left.record.conceptId.localeCompare(right.record.conceptId);
2506
+ }
2507
+ function typeRank(record) {
2508
+ const index = TYPE_PRIORITY.indexOf(record.frontmatter.type);
2509
+ return index === -1 ? TYPE_PRIORITY.length : index;
2510
+ }
2511
+
1931
2512
  // src/kb-store.ts
1932
2513
  var KB_DIR = (0, import_node_path6.join)(".strauss", "kb");
1933
2514
  var STORE_OWNED = /* @__PURE__ */ new Set([INDEX_FILE, LOG_FILE, SEARCH_INDEX_FILE]);
@@ -2217,6 +2798,10 @@ ${answer}
2217
2798
  async trace(bundlePath2, seedId, options = {}) {
2218
2799
  return trace(seedId, await this.list(bundlePath2), options);
2219
2800
  }
2801
+ /** A bounded neighbourhood around one record. See `pack.ts`. */
2802
+ async pack(bundlePath2, rootId, options = {}) {
2803
+ return pack(await this.list(bundlePath2), rootId, options);
2804
+ }
2220
2805
  /**
2221
2806
  * The stored index, rebuilt if it disagrees with the records.
2222
2807
  *
@@ -2423,9 +3008,12 @@ function digest(contents) {
2423
3008
  return (0, import_node_crypto.createHash)("sha256").update(contents).digest("hex");
2424
3009
  }
2425
3010
 
3011
+ // src/version.ts
3012
+ var VERSION = true ? "0.1.8" : "0.0.0-dev";
3013
+
2426
3014
  // src/mcp.ts
2427
3015
  function createKbMcpServer() {
2428
- const server = new import_mcp.McpServer({ name: "strauss-kb", version: "0.1.0" });
3016
+ const server = new import_mcp.McpServer({ name: "strauss-kb", version: VERSION });
2429
3017
  const store = new KbStore({
2430
3018
  warn: (entry) => process.stderr.write(`${JSON.stringify(entry)}
2431
3019
  `)