@saasontools/strauss-kb 0.1.2 → 0.1.3

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/index.cjs CHANGED
@@ -31,6 +31,9 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
33
  BaseError: () => BaseError,
34
+ CONTEXT_BEGIN: () => CONTEXT_BEGIN,
35
+ CONTEXT_END: () => CONTEXT_END,
36
+ CONTEXT_PROFILES: () => CONTEXT_PROFILES,
34
37
  DECISION_TYPE: () => DECISION_TYPE,
35
38
  ErrorTypes: () => ErrorTypes,
36
39
  Fault: () => Fault,
@@ -44,21 +47,29 @@ __export(index_exports, {
44
47
  KB_RECORD_STATUSES: () => KB_RECORD_STATUSES,
45
48
  KB_RECORD_TYPES: () => KB_RECORD_TYPES,
46
49
  KB_SLUG_PATTERN: () => KB_SLUG_PATTERN,
50
+ KbBaseFrozenError: () => KbBaseFrozenError,
47
51
  KbInvalidConceptIdError: () => KbInvalidConceptIdError,
52
+ KbPinsMalformedError: () => KbPinsMalformedError,
48
53
  KbRecordAlreadyExistsError: () => KbRecordAlreadyExistsError,
49
54
  KbRecordNotFoundError: () => KbRecordNotFoundError,
50
55
  KbStore: () => KbStore,
51
56
  KbWriteConflictError: () => KbWriteConflictError,
52
57
  LOG_FILE: () => LOG_FILE,
53
58
  NO_DECISION_SLUG: () => NO_DECISION_SLUG,
59
+ PINS_FILE: () => PINS_FILE,
60
+ PINS_LOCAL_FILE: () => PINS_LOCAL_FILE,
61
+ PIN_LAYERS: () => PIN_LAYERS,
54
62
  RECORD_TYPES: () => RECORD_TYPES,
55
63
  SEARCH_INDEX_FILE: () => SEARCH_INDEX_FILE,
56
64
  TRACE_EDGES: () => TRACE_EDGES,
57
65
  adjudicate: () => adjudicate,
66
+ assertBaseNotFrozen: () => assertBaseNotFrozen,
67
+ buildContext: () => buildContext,
58
68
  composeDecisionRecord: () => composeDecisionRecord,
59
69
  composeInputSchema: () => composeInputSchema,
60
70
  composeNoDecisionRecord: () => composeNoDecisionRecord,
61
71
  composeRecord: () => composeRecord,
72
+ contextProfileBudgets: () => contextProfileBudgets,
62
73
  createKbMcpServer: () => createKbMcpServer,
63
74
  decisionInputSchema: () => decisionInputSchema,
64
75
  indexIsStale: () => indexIsStale,
@@ -71,21 +82,31 @@ __export(index_exports, {
71
82
  kbLogEntrySchema: () => kbLogEntrySchema,
72
83
  kbRecordFrontmatterSchema: () => kbRecordFrontmatterSchema,
73
84
  kbSourceSchema: () => kbSourceSchema,
85
+ listPins: () => listPins,
74
86
  loadQmd: () => loadQmd,
75
87
  matchToDiff: () => matchToDiff,
88
+ mergedContextBudgets: () => mergedContextBudgets,
76
89
  parseLog: () => parseLog,
77
90
  parseMarkdownWithFrontmatter: () => parseMarkdownWithFrontmatter,
91
+ pinBase: () => pinBase,
92
+ readMergedPins: () => readMergedPins,
93
+ readPinsLayer: () => readPinsLayer,
78
94
  renderIndex: () => renderIndex,
95
+ renderIndexLine: () => renderIndexLine,
79
96
  renderLogEntry: () => renderLogEntry,
80
97
  resolveHeads: () => resolveHeads,
81
98
  resolveHits: () => resolveHits,
99
+ resolvePinPath: () => resolvePinPath,
82
100
  runKbCli: () => runKbCli,
83
101
  runKbMcpServer: () => runKbMcpServer,
84
102
  searchBase: () => searchBase,
85
103
  selectDecisions: () => selectDecisions,
86
104
  splitMarkdownFrontmatter: () => splitMarkdownFrontmatter,
87
105
  stringifyMarkdownWithFrontmatter: () => stringifyMarkdownWithFrontmatter,
106
+ syncInstructions: () => syncInstructions,
107
+ toHookJson: () => toHookJson,
88
108
  trace: () => trace,
109
+ unpinBase: () => unpinBase,
89
110
  validateBundle: () => validateBundle
90
111
  });
91
112
  module.exports = __toCommonJS(index_exports);
@@ -303,18 +324,19 @@ var KbInvalidConceptIdError = class extends BaseError {
303
324
  var INDEX_FILE = "INDEX.md";
304
325
  var HEADING = "# KB Index";
305
326
  function renderIndex(records) {
306
- const lines = [...records].sort((left, right) => left.conceptId.localeCompare(right.conceptId)).map((record) => {
307
- const { frontmatter: fm } = record;
308
- const parts = [fm.type, fm.strauss_status];
309
- if (fm.tags?.length) parts.push(`tags: ${fm.tags.join(", ")}`);
310
- if (fm.description) parts.push(fm.description);
311
- return `- [${fm.title ?? record.conceptId}](${record.conceptId}.md) \u2014 ${parts.join(" \xB7 ")}`;
312
- });
327
+ const lines = [...records].sort((left, right) => left.conceptId.localeCompare(right.conceptId)).map(renderIndexLine);
313
328
  return `${HEADING}
314
329
 
315
330
  ${lines.join("\n")}
316
331
  `;
317
332
  }
333
+ function renderIndexLine(record) {
334
+ const { frontmatter: fm } = record;
335
+ const parts = [fm.type, fm.strauss_status];
336
+ if (fm.tags?.length) parts.push(`tags: ${fm.tags.join(", ")}`);
337
+ if (fm.description) parts.push(fm.description);
338
+ return `- [${fm.title ?? record.conceptId}](${record.conceptId}.md) \u2014 ${parts.join(" \xB7 ")}`;
339
+ }
318
340
  function indexIsStale(stored, expected) {
319
341
  return stored !== expected;
320
342
  }
@@ -828,19 +850,19 @@ ${answer}
828
850
  const adjudicated = adjudicate(wanted, bundle);
829
851
  const records = adjudicated.filter((hit) => hit.standing !== "superseded");
830
852
  const superseded = adjudicated.filter((hit) => hit.standing === "superseded").map(stub);
831
- const approxTokens = records.reduce((total, hit) => total + estimateTokens(hit.record), 0) + superseded.reduce((total, entry) => total + estimateStubTokens(entry), 0);
832
- if (approxTokens > budgetTokens) {
853
+ const approxTokens2 = records.reduce((total, hit) => total + estimateTokens(hit.record), 0) + superseded.reduce((total, entry) => total + estimateStubTokens(entry), 0);
854
+ if (approxTokens2 > budgetTokens) {
833
855
  return {
834
856
  loaded: false,
835
857
  recordCount: wanted.length,
836
- approxTokens,
858
+ approxTokens: approxTokens2,
837
859
  budgetTokens
838
860
  };
839
861
  }
840
862
  return {
841
863
  loaded: true,
842
864
  recordCount: wanted.length,
843
- approxTokens,
865
+ approxTokens: approxTokens2,
844
866
  budgetTokens,
845
867
  records,
846
868
  superseded
@@ -1096,6 +1118,16 @@ var composeInputSchema = import_zod3.z.object({
1096
1118
  sources: import_zod3.z.array(kbSourceSchema).optional(),
1097
1119
  /** No source exists, as a claim rather than a sentinel in `sources`. */
1098
1120
  assumption: import_zod3.z.boolean().optional(),
1121
+ /**
1122
+ * OKF `stale_after`: the absolute date this record stops being trusted.
1123
+ * Anything the outside world can change — pricing, quotas, versions,
1124
+ * reception counts — should carry one.
1125
+ */
1126
+ stale_after: import_zod3.z.string().regex(/^\d{4}-\d{2}-\d{2}$/, {
1127
+ message: "stale_after must be YYYY-MM-DD"
1128
+ }).refine((date) => !Number.isNaN(Date.parse(date)), {
1129
+ message: "stale_after must be a real date"
1130
+ }).optional(),
1099
1131
  verify: import_zod3.z.array(import_zod3.z.string().min(1)).optional(),
1100
1132
  tags: import_zod3.z.array(import_zod3.z.string().min(1)).optional(),
1101
1133
  /** Concept ids this record relates to; rendered as body links. */
@@ -1128,6 +1160,7 @@ function composeRecord(type, input, writtenBy, writtenAt) {
1128
1160
  verified: [],
1129
1161
  strauss_status: spec.initialStatus
1130
1162
  };
1163
+ if (parsed.stale_after) frontmatter.stale_after = parsed.stale_after;
1131
1164
  if (parsed.anchors?.length) frontmatter.strauss_anchors = parsed.anchors;
1132
1165
  if (parsed.verify?.length) frontmatter.strauss_verify = parsed.verify;
1133
1166
  if (parsed.tags?.length) frontmatter.tags = parsed.tags;
@@ -1163,15 +1196,545 @@ ${text}`);
1163
1196
  };
1164
1197
  }
1165
1198
 
1166
- // src/json-schema.ts
1199
+ // src/kb-pins/budgets.ts
1200
+ function asBudgets(value) {
1201
+ if (value === null || typeof value !== "object") return {};
1202
+ const table = value;
1203
+ const pick = (key2, min) => {
1204
+ const raw = table[key2];
1205
+ return typeof raw === "number" && Number.isInteger(raw) && raw >= min ? raw : void 0;
1206
+ };
1207
+ const budgetTokens = pick("budgetTokens", 1);
1208
+ const fullUnderTokens = pick("fullUnderTokens", 0);
1209
+ return {
1210
+ ...budgetTokens ? { budgetTokens } : {},
1211
+ ...fullUnderTokens !== void 0 ? { fullUnderTokens } : {}
1212
+ };
1213
+ }
1214
+ function contextProfileBudgets(manifest, profile) {
1215
+ const table = manifest.context;
1216
+ if (table === null || typeof table !== "object") return {};
1217
+ const entries = table;
1218
+ return {
1219
+ ...asBudgets(entries["default"]),
1220
+ ...profile ? asBudgets(entries[profile]) : {}
1221
+ };
1222
+ }
1223
+ function mergedContextBudgets(merged, profile) {
1224
+ const layered = ["user", "local", "project"].map((layer) => {
1225
+ const manifest = merged.manifests[layer];
1226
+ return manifest ? contextProfileBudgets(manifest, profile) : {};
1227
+ });
1228
+ return { ...layered[0], ...layered[1], ...layered[2] };
1229
+ }
1230
+
1231
+ // src/kb-pins/errors.ts
1232
+ var KbPinsMalformedError = class extends Error {
1233
+ constructor(file, cause) {
1234
+ super(`pin manifest ${file} is not readable (${cause}) \u2014 fix or remove it`);
1235
+ this.name = "KbPinsMalformedError";
1236
+ }
1237
+ };
1238
+ var KbBaseFrozenError = class extends Error {
1239
+ constructor(bundlePath2, layer) {
1240
+ super(
1241
+ `${bundlePath2} is frozen (read-only) by this workspace's ${layer} pin manifest \u2014 re-pin with --unfreeze, or unpin, to change it`
1242
+ );
1243
+ this.name = "KbBaseFrozenError";
1244
+ }
1245
+ };
1246
+
1247
+ // src/kb-pins/frozen.ts
1248
+ var import_node_path5 = require("path");
1249
+
1250
+ // src/kb-pins/layers.ts
1251
+ var import_promises3 = require("fs/promises");
1252
+ var import_node_os = require("os");
1253
+ var import_node_path4 = require("path");
1254
+
1255
+ // src/kb-pins/model.ts
1256
+ var import_node_path3 = require("path");
1167
1257
  var import_zod4 = require("zod");
1258
+ var PINS_FILE = (0, import_node_path3.join)(".strauss", "kb-pins.json");
1259
+ var PINS_LOCAL_FILE = (0, import_node_path3.join)(".strauss", "kb-pins.local.json");
1260
+ var PIN_LAYERS = ["project", "local", "user"];
1261
+ var pinSchema = import_zod4.z.object({
1262
+ /** Relative to the manifest's root, so the file is committable. */
1263
+ path: import_zod4.z.string().min(1),
1264
+ pinnedAt: import_zod4.z.string().min(1).optional(),
1265
+ /**
1266
+ * How `context` renders this base. `full` preloads the whole base into
1267
+ * the block regardless of the full-under threshold — for a base whose
1268
+ * contents should simply be present, the way an ADR base should be —
1269
+ * still answering to the block budget, with an index fallback that says
1270
+ * so when it cannot fit. `index` never upgrades, whatever the threshold.
1271
+ * Absent: the profile's full-under threshold decides. Invalid values
1272
+ * degrade to absent rather than failing the manifest.
1273
+ */
1274
+ mode: import_zod4.z.enum(["full", "index"]).optional().catch(void 0),
1275
+ /**
1276
+ * Context profiles this pin surfaces in (e.g. only at session-start,
1277
+ * not per turn). Absent: every profile. A run without a profile sees
1278
+ * every pin. A base that only matters to one skill is better loaded by
1279
+ * that skill at point of use than pinned at all — pins are what every
1280
+ * session should see.
1281
+ */
1282
+ profiles: import_zod4.z.array(import_zod4.z.string()).optional().catch(void 0),
1283
+ /**
1284
+ * The base is concluded — a finished piece of research, a frozen ADR
1285
+ * set. Write commands against it refuse while this workspace holds the
1286
+ * pin, and `context` labels it read-only. Workspace policy, not base
1287
+ * state: the base itself stays copyable and writable elsewhere.
1288
+ */
1289
+ frozen: import_zod4.z.boolean().optional().catch(void 0)
1290
+ }).passthrough();
1291
+ var pinsManifestSchema = import_zod4.z.object({
1292
+ pins: import_zod4.z.array(pinSchema).default([]),
1293
+ /**
1294
+ * Per-repo budgets for the `context` command, keyed by profile —
1295
+ * `"session-start"`, `"compact"`, `"turn"`, or `"default"` for all of
1296
+ * them. Deliberately untyped here: a typo'd budget must degrade to the
1297
+ * built-in default, not make the whole manifest unreadable and silence
1298
+ * the index at every session start. `contextProfileBudgets` does the
1299
+ * tolerant read.
1300
+ */
1301
+ context: import_zod4.z.unknown().optional()
1302
+ }).passthrough();
1303
+
1304
+ // src/kb-pins/layers.ts
1305
+ function userRoot() {
1306
+ return process.env.STRAUSS_KB_USER_ROOT || (0, import_node_os.homedir)();
1307
+ }
1308
+ function layerRoot(workspaceDir, layer) {
1309
+ return layer === "user" ? userRoot() : (0, import_node_path4.resolve)(workspaceDir);
1310
+ }
1311
+ function layerFile(workspaceDir, layer) {
1312
+ return (0, import_node_path4.join)(
1313
+ layerRoot(workspaceDir, layer),
1314
+ layer === "local" ? PINS_LOCAL_FILE : PINS_FILE
1315
+ );
1316
+ }
1317
+ async function readPinsLayer(workspaceDir, layer) {
1318
+ const file = layerFile(workspaceDir, layer);
1319
+ let raw;
1320
+ try {
1321
+ raw = await (0, import_promises3.readFile)(file, "utf8");
1322
+ } catch {
1323
+ return { pins: [] };
1324
+ }
1325
+ let parsed;
1326
+ try {
1327
+ parsed = JSON.parse(raw);
1328
+ } catch (error) {
1329
+ throw new KbPinsMalformedError(
1330
+ file,
1331
+ error instanceof Error ? error.message : "invalid JSON"
1332
+ );
1333
+ }
1334
+ const manifest = pinsManifestSchema.safeParse(parsed);
1335
+ if (!manifest.success) {
1336
+ throw new KbPinsMalformedError(
1337
+ file,
1338
+ manifest.error.issues[0]?.message ?? "invalid shape"
1339
+ );
1340
+ }
1341
+ return manifest.data;
1342
+ }
1343
+ async function writePinsLayer(workspaceDir, layer, manifest) {
1344
+ const file = layerFile(workspaceDir, layer);
1345
+ await (0, import_promises3.mkdir)((0, import_node_path4.dirname)(file), { recursive: true });
1346
+ await (0, import_promises3.writeFile)(file, `${JSON.stringify(manifest, null, 2)}
1347
+ `, "utf8");
1348
+ }
1349
+ function resolvePinPath(rootDir, path) {
1350
+ 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));
1351
+ }
1352
+ function storablePath(rootDir, bundlePath2) {
1353
+ const rel = (0, import_node_path4.relative)((0, import_node_path4.resolve)(rootDir), (0, import_node_path4.resolve)(bundlePath2));
1354
+ return (rel === "" ? "." : rel).split(import_node_path4.sep).join("/");
1355
+ }
1356
+ async function readMergedPins(workspaceDir) {
1357
+ const manifests = {};
1358
+ const pins = [];
1359
+ const seen = /* @__PURE__ */ new Set();
1360
+ for (const layer of PIN_LAYERS) {
1361
+ let manifest;
1362
+ try {
1363
+ manifest = await readPinsLayer(workspaceDir, layer);
1364
+ } catch {
1365
+ continue;
1366
+ }
1367
+ manifests[layer] = manifest;
1368
+ const root = layerRoot(workspaceDir, layer);
1369
+ for (const entry of manifest.pins) {
1370
+ const absolutePath = resolvePinPath(root, entry.path);
1371
+ if (seen.has(absolutePath)) continue;
1372
+ seen.add(absolutePath);
1373
+ pins.push({ ...entry, layer, absolutePath });
1374
+ }
1375
+ }
1376
+ return { pins, manifests };
1377
+ }
1378
+
1379
+ // src/kb-pins/frozen.ts
1380
+ async function assertBaseNotFrozen(workspaceDir, bundlePath2) {
1381
+ const merged = await readMergedPins(workspaceDir);
1382
+ const absolute = (0, import_node_path5.resolve)(bundlePath2);
1383
+ const pin = merged.pins.find((entry) => entry.absolutePath === absolute);
1384
+ if (pin?.frozen === true) {
1385
+ throw new KbBaseFrozenError(pin.path, pin.layer);
1386
+ }
1387
+ }
1388
+
1389
+ // src/kb-pins/list.ts
1390
+ async function listPins(store, workspaceDir) {
1391
+ const merged = await readMergedPins(workspaceDir);
1392
+ return Promise.all(
1393
+ merged.pins.map(async (entry) => {
1394
+ const records = await store.list(entry.absolutePath);
1395
+ return {
1396
+ path: entry.path,
1397
+ layer: entry.layer,
1398
+ pinnedAt: entry.pinnedAt ?? null,
1399
+ absolutePath: entry.absolutePath,
1400
+ valid: records.length > 0,
1401
+ recordCount: records.length,
1402
+ mode: entry.mode ?? null,
1403
+ profiles: entry.profiles ?? null,
1404
+ frozen: entry.frozen === true
1405
+ };
1406
+ })
1407
+ );
1408
+ }
1409
+
1410
+ // src/kb-pins/pin.ts
1411
+ async function pinBase(store, workspaceDir, bundlePath2, at, options = {}) {
1412
+ const layer = options.layer ?? "project";
1413
+ const root = layerRoot(workspaceDir, layer);
1414
+ const manifest = await readPinsLayer(workspaceDir, layer);
1415
+ const absolute = resolvePinPath(root, storablePath(root, bundlePath2));
1416
+ const existing = manifest.pins.find(
1417
+ (entry2) => resolvePinPath(root, entry2.path) === absolute
1418
+ );
1419
+ const records = await store.list(absolute);
1420
+ const warning = records.length === 0 ? `no records found at ${absolute} \u2014 pinned anyway; bases are routinely pinned before they are populated` : void 0;
1421
+ const fields = {
1422
+ ...options.mode ? { mode: options.mode } : {},
1423
+ ...options.profiles?.length ? { profiles: options.profiles } : {},
1424
+ ...options.frozen !== void 0 ? { frozen: options.frozen } : {}
1425
+ };
1426
+ if (existing) {
1427
+ const updated = { ...existing, ...fields };
1428
+ if (Object.keys(fields).length) {
1429
+ await writePinsLayer(workspaceDir, layer, {
1430
+ ...manifest,
1431
+ pins: manifest.pins.map(
1432
+ (entry2) => entry2 === existing ? updated : entry2
1433
+ )
1434
+ });
1435
+ }
1436
+ return {
1437
+ path: existing.path,
1438
+ layer,
1439
+ pinnedAt: existing.pinnedAt ?? at,
1440
+ alreadyPinned: true,
1441
+ ...updated.mode ? { mode: updated.mode } : {},
1442
+ ...updated.profiles ? { profiles: updated.profiles } : {},
1443
+ ...updated.frozen !== void 0 ? { frozen: updated.frozen } : {},
1444
+ ...warning ? { warning } : {}
1445
+ };
1446
+ }
1447
+ const entry = {
1448
+ path: storablePath(root, bundlePath2),
1449
+ pinnedAt: at,
1450
+ ...fields
1451
+ };
1452
+ await writePinsLayer(workspaceDir, layer, {
1453
+ ...manifest,
1454
+ pins: [...manifest.pins, entry]
1455
+ });
1456
+ return {
1457
+ path: entry.path,
1458
+ layer,
1459
+ pinnedAt: at,
1460
+ alreadyPinned: false,
1461
+ ...fields,
1462
+ ...warning ? { warning } : {}
1463
+ };
1464
+ }
1465
+
1466
+ // src/kb-pins/unpin.ts
1467
+ var import_node_path6 = require("path");
1468
+ async function unpinBase(workspaceDir, bundlePath2) {
1469
+ const layers = [];
1470
+ for (const layer of PIN_LAYERS) {
1471
+ const root = layerRoot(workspaceDir, layer);
1472
+ let manifest;
1473
+ try {
1474
+ manifest = await readPinsLayer(workspaceDir, layer);
1475
+ } catch {
1476
+ continue;
1477
+ }
1478
+ const absolute = resolvePinPath(root, storablePath(root, bundlePath2));
1479
+ const kept = manifest.pins.filter(
1480
+ (entry) => resolvePinPath(root, entry.path) !== absolute
1481
+ );
1482
+ if (kept.length !== manifest.pins.length) {
1483
+ await writePinsLayer(workspaceDir, layer, { ...manifest, pins: kept });
1484
+ layers.push(layer);
1485
+ }
1486
+ }
1487
+ return {
1488
+ path: storablePath((0, import_node_path6.resolve)(workspaceDir), bundlePath2),
1489
+ removed: layers.length > 0,
1490
+ layers
1491
+ };
1492
+ }
1493
+
1494
+ // src/kb-context.ts
1495
+ var import_promises4 = require("fs/promises");
1496
+ var HEADING2 = "## Knowledge bases (pinned)";
1497
+ var DEFAULT_CONTEXT_BUDGET = 4e3;
1498
+ var CONTEXT_PROFILES = {
1499
+ "session-start": { fullUnderTokens: 1500 },
1500
+ compact: { budgetTokens: 2500 },
1501
+ turn: { budgetTokens: 2500 }
1502
+ };
1503
+ function approxTokens(text) {
1504
+ return Math.ceil(text.length / 4);
1505
+ }
1506
+ function preamble() {
1507
+ return [
1508
+ HEADING2,
1509
+ "",
1510
+ "What follows is an index of this workspace's pinned knowledge bases \u2014",
1511
+ "concept ids, titles and standing only. The record bodies are NOT in this",
1512
+ "context.",
1513
+ "",
1514
+ "Consult records only through the strauss-kb MCP tools: `kb_load` (the",
1515
+ "preferred first call), `kb_query`, and `kb_trace`, passing the",
1516
+ "`bundlePath` listed with each base. Do not read record files directly:",
1517
+ "a raw file read bypasses supersession resolution, and a superseded or",
1518
+ "rejected record file reads exactly like a current one \u2014 only the store",
1519
+ "resolves chains and standing.",
1520
+ "",
1521
+ "KB content loaded earlier in a long session may have been compacted",
1522
+ "away. Before answering a question one of these bases governs, load it",
1523
+ "again at the point of use \u2014 reloading a small base costs a few thousand",
1524
+ "tokens."
1525
+ ].join("\n");
1526
+ }
1527
+ async function renderBase(store, path, absolutePath, fullUnderTokens, pinMode, budgetTokens) {
1528
+ const bundle = await store.list(absolutePath);
1529
+ if (bundle.length === 0) {
1530
+ return {
1531
+ path,
1532
+ absolutePath,
1533
+ mode: "empty",
1534
+ body: "No readable records yet \u2014 pinned ahead of being populated."
1535
+ };
1536
+ }
1537
+ const fullCap = pinMode === "full" ? budgetTokens : pinMode === "index" ? 0 : fullUnderTokens;
1538
+ let degradedFrom;
1539
+ if (fullCap > 0) {
1540
+ const full = await store.load(absolutePath, {
1541
+ budgetTokens: fullCap
1542
+ });
1543
+ if (!full.loaded && pinMode === "full") {
1544
+ degradedFrom = { approxTokens: full.approxTokens };
1545
+ }
1546
+ if (full.loaded) {
1547
+ const records = full.records.map(
1548
+ (hit) => [
1549
+ `#### ${hit.record.conceptId} \u2014 ${hit.record.frontmatter.title ?? "(untitled)"} (${hit.standing})`,
1550
+ "",
1551
+ hit.record.body.trim()
1552
+ ].join("\n")
1553
+ );
1554
+ const superseded2 = full.superseded.map(
1555
+ (entry) => `- \`${entry.conceptId}\` \u2192 superseded by ${entry.supersededBy.map((id) => `\`${id}\``).join(", ") || "(missing replacement)"}`
1556
+ );
1557
+ return {
1558
+ path,
1559
+ absolutePath,
1560
+ mode: "full",
1561
+ body: [
1562
+ ...records,
1563
+ ...superseded2.length ? [
1564
+ "#### Superseded (bodies withheld \u2014 kb_trace reaches them)",
1565
+ ...superseded2
1566
+ ] : []
1567
+ ].join("\n\n")
1568
+ };
1569
+ }
1570
+ }
1571
+ const adjudicated = adjudicate(bundle, bundle);
1572
+ const lines = adjudicated.filter((hit) => hit.standing !== "superseded").map((hit) => renderIndexLine(hit.record));
1573
+ const superseded = adjudicated.filter((hit) => hit.standing === "superseded").map(
1574
+ (hit) => `- \`${hit.record.conceptId}\` \u2192 superseded by ${hit.heads.map((head) => `\`${head.conceptId}\``).join(", ") || "(missing replacement)"}`
1575
+ );
1576
+ return {
1577
+ path,
1578
+ absolutePath,
1579
+ mode: "index",
1580
+ body: [...lines, ...superseded].join("\n"),
1581
+ ...degradedFrom ? { degradedFrom } : {}
1582
+ };
1583
+ }
1584
+ async function buildContext(store, workspaceDir, options = {}) {
1585
+ const builtin = options.profile ? CONTEXT_PROFILES[options.profile] ?? {} : {};
1586
+ let budgetTokens = options.budgetTokens ?? builtin.budgetTokens ?? DEFAULT_CONTEXT_BUDGET;
1587
+ let fullUnderTokens = options.fullUnderTokens ?? builtin.fullUnderTokens ?? 0;
1588
+ const merged = await readMergedPins(workspaceDir);
1589
+ const fromManifest = mergedContextBudgets(merged, options.profile);
1590
+ budgetTokens = options.budgetTokens ?? fromManifest.budgetTokens ?? builtin.budgetTokens ?? DEFAULT_CONTEXT_BUDGET;
1591
+ fullUnderTokens = options.fullUnderTokens ?? fromManifest.fullUnderTokens ?? builtin.fullUnderTokens ?? 0;
1592
+ const pins = merged.pins.filter(
1593
+ (pin) => !pin.profiles?.length || !options.profile || pin.profiles.includes(options.profile)
1594
+ );
1595
+ if (pins.length === 0) {
1596
+ return {
1597
+ block: "",
1598
+ refused: false,
1599
+ approxTokens: 0,
1600
+ budgetTokens,
1601
+ bases: []
1602
+ };
1603
+ }
1604
+ const sections = await Promise.all(
1605
+ pins.map(async (pin) => ({
1606
+ section: await renderBase(
1607
+ store,
1608
+ pin.path,
1609
+ pin.absolutePath,
1610
+ fullUnderTokens,
1611
+ pin.mode,
1612
+ budgetTokens
1613
+ ),
1614
+ frozen: pin.frozen === true
1615
+ }))
1616
+ );
1617
+ const modeLabel = {
1618
+ index: "index only \u2014 record bodies are not here",
1619
+ full: "full records \u2014 this base arrives whole",
1620
+ empty: "empty"
1621
+ };
1622
+ for (const { section } of sections) {
1623
+ if (section.degradedFrom) {
1624
+ options.warn?.({
1625
+ operation: "kb.context.full-pin-degraded",
1626
+ path: section.path,
1627
+ approxTokens: section.degradedFrom.approxTokens,
1628
+ budgetTokens
1629
+ });
1630
+ }
1631
+ }
1632
+ const rendered = sections.map(({ section, frozen }) => {
1633
+ const label = section.degradedFrom ? `index only \u2014 pinned \`mode: full\`, but its ~${section.degradedFrom.approxTokens} tokens exceed this block's ${budgetTokens}-token budget; kb_load it directly (load's budget is separate), or raise this profile's budget` : modeLabel[section.mode];
1634
+ return [
1635
+ `### ${section.path} (${label}${frozen ? " \xB7 frozen, read-only" : ""})`,
1636
+ "",
1637
+ `bundlePath: \`${section.absolutePath}\``,
1638
+ "",
1639
+ section.body
1640
+ ].join("\n");
1641
+ });
1642
+ const block = [preamble(), "", rendered.join("\n\n"), ""].join("\n");
1643
+ const bases = sections.map(({ section }) => ({
1644
+ path: section.path,
1645
+ absolutePath: section.absolutePath,
1646
+ approxTokens: approxTokens(section.body)
1647
+ }));
1648
+ const total = approxTokens(block);
1649
+ if (total > budgetTokens) {
1650
+ options.warn?.({
1651
+ operation: "kb.context.refused",
1652
+ approxTokens: total,
1653
+ budgetTokens,
1654
+ bases: bases.map((base) => base.path)
1655
+ });
1656
+ const refusal = [
1657
+ HEADING2,
1658
+ "",
1659
+ `The pinned index runs to ~${total} tokens, past the ${budgetTokens}-token`,
1660
+ "budget, and was not emitted \u2014 a truncated index is indistinguishable",
1661
+ "from a complete one. The pinned bases:",
1662
+ "",
1663
+ ...bases.map(
1664
+ (base) => `- ${base.path} \u2014 ~${base.approxTokens} tokens (bundlePath: \`${base.absolutePath}\`)`
1665
+ ),
1666
+ "",
1667
+ "For the question at hand, read what you need now \u2014 `kb_load` a base",
1668
+ "(its own budget is separate), or `kb_index` for one base's shape.",
1669
+ "",
1670
+ "To bring this block back under budget, in order of preference:",
1671
+ "- supersede or resolve stale records \u2014 the base shrinks, the knowledge keeps",
1672
+ "- force a large base to index lines: `strauss-kb pin <path> --mode index`",
1673
+ "- scope a pin to the profiles that need it: `strauss-kb pin <path> --profiles session-start`",
1674
+ "- raise this profile's budget under `context` in .strauss/kb-pins.json",
1675
+ "- unpin what no session actually needs",
1676
+ ""
1677
+ ].join("\n");
1678
+ return {
1679
+ block: refusal,
1680
+ refused: true,
1681
+ approxTokens: total,
1682
+ budgetTokens,
1683
+ bases
1684
+ };
1685
+ }
1686
+ return { block, refused: false, approxTokens: total, budgetTokens, bases };
1687
+ }
1688
+ function toHookJson(block, event) {
1689
+ return JSON.stringify({
1690
+ hookSpecificOutput: {
1691
+ hookEventName: event,
1692
+ additionalContext: block
1693
+ }
1694
+ });
1695
+ }
1696
+ var CONTEXT_BEGIN = "<!-- strauss-kb:begin -->";
1697
+ var CONTEXT_END = "<!-- strauss-kb:end -->";
1698
+ async function syncInstructions(file, block) {
1699
+ const existing = await (0, import_promises4.readFile)(file, "utf8").catch(() => null);
1700
+ const region = block ? `${CONTEXT_BEGIN}
1701
+ ${block.trim()}
1702
+ ${CONTEXT_END}` : null;
1703
+ if (existing === null) {
1704
+ if (!region) return { file, action: "unchanged" };
1705
+ await (0, import_promises4.writeFile)(file, `${region}
1706
+ `, "utf8");
1707
+ return { file, action: "created" };
1708
+ }
1709
+ const begin = existing.indexOf(CONTEXT_BEGIN);
1710
+ const end = existing.indexOf(CONTEXT_END);
1711
+ if (begin !== -1 && end !== -1 && end >= begin) {
1712
+ const before = existing.slice(0, begin);
1713
+ const after = existing.slice(end + CONTEXT_END.length);
1714
+ const next = region ? `${before}${region}${after}` : `${before.replace(/\n+$/, "\n")}${after.replace(/^\n+/, "\n")}`;
1715
+ if (next === existing) return { file, action: "unchanged" };
1716
+ await (0, import_promises4.writeFile)(file, next, "utf8");
1717
+ return { file, action: region ? "replaced" : "removed" };
1718
+ }
1719
+ if (!region) return { file, action: "unchanged" };
1720
+ await (0, import_promises4.writeFile)(
1721
+ file,
1722
+ `${existing.replace(/\n*$/, "\n\n")}${region}
1723
+ `,
1724
+ "utf8"
1725
+ );
1726
+ return { file, action: "appended" };
1727
+ }
1728
+
1729
+ // src/json-schema.ts
1730
+ var import_zod5 = require("zod");
1168
1731
  function kbJsonSchemas() {
1169
1732
  return {
1170
- recordFrontmatter: import_zod4.z.toJSONSchema(kbRecordFrontmatterSchema, {
1733
+ recordFrontmatter: import_zod5.z.toJSONSchema(kbRecordFrontmatterSchema, {
1171
1734
  io: "input"
1172
1735
  }),
1173
- composeInput: import_zod4.z.toJSONSchema(composeInputSchema, { io: "input" }),
1174
- logEntry: import_zod4.z.toJSONSchema(kbLogEntrySchema, { io: "input" })
1736
+ composeInput: import_zod5.z.toJSONSchema(composeInputSchema, { io: "input" }),
1737
+ logEntry: import_zod5.z.toJSONSchema(kbLogEntrySchema, { io: "input" })
1175
1738
  };
1176
1739
  }
1177
1740
 
@@ -1291,12 +1854,12 @@ function validateBundle(records) {
1291
1854
  }
1292
1855
 
1293
1856
  // src/decision-record.ts
1294
- var import_zod5 = require("zod");
1857
+ var import_zod6 = require("zod");
1295
1858
  var DECISION_TYPE = "decision";
1296
1859
  var NO_DECISION_SLUG = "none";
1297
1860
  var decisionInputSchema = composeInputSchema.omit({ sections: true }).extend({
1298
- alternative: import_zod5.z.string().min(1).optional(),
1299
- impact: import_zod5.z.string().min(1).optional()
1861
+ alternative: import_zod6.z.string().min(1).optional(),
1862
+ impact: import_zod6.z.string().min(1).optional()
1300
1863
  }).strict();
1301
1864
  function composeDecisionRecord(input, writtenBy, writtenAt) {
1302
1865
  const { alternative, impact, ...rest } = input;
@@ -1337,300 +1900,537 @@ function selectDecisions(records) {
1337
1900
  );
1338
1901
  }
1339
1902
 
1340
- // src/commands.ts
1341
- var import_zod6 = require("zod");
1342
- var bundlePath = import_zod6.z.string().min(1).describe("Absolute path to the knowledge base directory.");
1343
- var conceptId = import_zod6.z.string().min(1).describe("e.g. decision.cursor-v2");
1903
+ // src/commands/answer.ts
1904
+ var import_zod8 = require("zod");
1905
+
1906
+ // src/commands/model.ts
1907
+ var import_zod7 = require("zod");
1908
+ var bundlePath = import_zod7.z.string().min(1).describe("Absolute path to the knowledge base directory.");
1909
+ var conceptId = import_zod7.z.string().min(1).describe("e.g. decision.cursor-v2");
1344
1910
  function define(command) {
1345
1911
  return command;
1346
1912
  }
1347
- var KB_COMMANDS = [
1348
- define({
1349
- name: "write",
1350
- tool: "kb_write",
1351
- usage: "write <type> < record.json",
1352
- description: [
1353
- "Write one record. Search first \u2014 the same knowledge filed twice under different slugs is how a base rots, and a duplicate concept id is rejected rather than overwritten. Call kb_types for the sections each type accepts.",
1354
- "",
1355
- "Judgment the tool cannot enforce for you:",
1356
- "- An unsourced claim is an `assumption` record with assumption: true, never a `fact` with a vague source. The distinction is what lets a later reader separate what was established from what was guessed.",
1357
- "- When two records conflict, say so in a `risk`, an `open-question`, or a superseding `decision`. Quietly picking a winner destroys the disagreement, which is usually the useful part.",
1358
- "- Prefer a new record over overloading an existing one, and keep each short. A record nobody finishes reading is not durable memory.",
1359
- "- Records are never deleted; supersede instead, so the earlier reasoning stays inspectable."
1360
- ].join("\n"),
1361
- input: import_zod6.z.object({
1362
- bundlePath,
1363
- type: import_zod6.z.enum(KB_RECORD_TYPES),
1364
- input: composeInputSchema
1365
- }),
1366
- fromArgv: async (argv, path, stdin) => ({
1367
- bundlePath: path,
1368
- type: argv[1],
1369
- input: JSON.parse(await stdin())
1370
- }),
1371
- run: async ({ store, actor, now }, { bundlePath: path, type, input }) => {
1372
- const record = await store.write(
1373
- path,
1374
- composeRecord(type, input, actor, now()),
1375
- actor
1376
- );
1377
- return { conceptId: record.conceptId };
1378
- }
1913
+ function argvFlag(argv, name) {
1914
+ const at = argv.indexOf(name);
1915
+ return at !== -1 ? argv[at + 1] : void 0;
1916
+ }
1917
+
1918
+ // src/commands/answer.ts
1919
+ var answerCommand = define({
1920
+ name: "answer",
1921
+ tool: "kb_answer",
1922
+ usage: "answer <concept-id> <answer...>",
1923
+ description: "Resolve an open question: sets the status, stamps who answered and when, and appends an Answer section. If the answer overturns an assumption or a decision, that is a supersession \u2014 do it explicitly.",
1924
+ input: import_zod8.z.object({ bundlePath, conceptId, answer: import_zod8.z.string().min(1) }),
1925
+ fromArgv: (argv, path) => ({
1926
+ bundlePath: path,
1927
+ conceptId: argv[1],
1928
+ answer: argv.slice(2).join(" ").trim()
1379
1929
  }),
1380
- define({
1381
- name: "write-decision",
1382
- tool: "kb_write_decision",
1383
- usage: "write-decision < decision.json",
1384
- description: [
1385
- "Write a decision. Takes `alternative` and `impact` as fields rather than free sections, because what was rejected is the part a later reader cannot reconstruct from the code \u2014 a heading is too easy to leave empty.",
1386
- "",
1387
- "What belongs in one:",
1388
- '- Record a decision when a later reader would otherwise "simplify" the constraint away. If the diff already answers the question, there is nothing here to write.',
1389
- "- `alternative` is what you turned down and why, not a list of everything considered.",
1390
- "- A reference to material you read goes in `sources`; a reference to code goes in `anchors`; a reference to another record goes in `relatedConceptIds`."
1391
- ].join("\n"),
1392
- input: import_zod6.z.object({ bundlePath, input: decisionInputSchema }),
1393
- fromArgv: async (_argv, path, stdin) => ({
1394
- bundlePath: path,
1395
- input: JSON.parse(await stdin())
1396
- }),
1397
- run: async ({ store, actor, now }, { bundlePath: path, input }) => {
1398
- const record = await store.write(
1399
- path,
1400
- composeDecisionRecord(input, actor, now()),
1401
- actor
1402
- );
1403
- return { conceptId: record.conceptId };
1404
- }
1930
+ run: async ({ store, actor }, { bundlePath: path, conceptId: id, answer }) => {
1931
+ await assertBaseNotFrozen(process.cwd(), path);
1932
+ const record = await store.answer(path, id, answer, actor);
1933
+ return { conceptId: record.conceptId };
1934
+ }
1935
+ });
1936
+
1937
+ // src/commands/context.ts
1938
+ var import_zod9 = require("zod");
1939
+ var contextCommand = define({
1940
+ name: "context",
1941
+ tool: "kb_context",
1942
+ usage: "context [--profile NAME] [--budget N] [--full-under N] [--format json] [--event NAME]",
1943
+ description: "The pinned-base index block, for injection at every context birth \u2014 startup, clear, resume, and after compaction. An index, not the content: concept ids, titles and standing, with the bodies left behind kb_load at the point of use. Emits nothing when nothing is pinned. Refuses with the list of bases and their sizes rather than truncating past its budget. Budgets resolve most-specific-first: explicit flags, then the workspace manifests' `context` tables (per profile, over their `default`), then the built-in profile (session-start, compact, turn), then package defaults \u2014 so a repo tunes its own numbers in .strauss/kb-pins.json without touching hook commands. Like kb_schema and kb_types this takes no bundlePath \u2014 it reads the workspace pin manifests, because which bases a session should see is workspace state, not a property of one base.",
1944
+ input: import_zod9.z.object({
1945
+ budgetTokens: import_zod9.z.number().int().positive().optional().describe(
1946
+ "Ceiling on the whole emitted block; past it the command refuses with a list of bases rather than truncating. Defaults to 4000."
1947
+ ),
1948
+ fullUnderTokens: import_zod9.z.number().int().positive().optional().describe(
1949
+ "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."
1950
+ ),
1951
+ profile: import_zod9.z.string().optional().describe(
1952
+ "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."
1953
+ ),
1954
+ format: import_zod9.z.enum(["markdown", "json"]).optional().describe(
1955
+ "CLI envelope for hook protocols that require strict JSON on stdout. MCP callers omit this \u2014 the block itself is identical."
1956
+ ),
1957
+ event: import_zod9.z.string().optional().describe(
1958
+ "hookEventName stamped into the JSON envelope. Only meaningful with format=json."
1959
+ )
1405
1960
  }),
1406
- define({
1407
- name: "no-decision",
1408
- tool: "kb_no_decision",
1409
- usage: "no-decision <reason...>",
1410
- 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.',
1411
- input: import_zod6.z.object({ bundlePath, reason: import_zod6.z.string().min(1) }),
1412
- fromArgv: (argv, path) => ({
1413
- bundlePath: path,
1414
- reason: argv.slice(1).join(" ").trim()
1415
- }),
1416
- run: async ({ store, actor, now }, { bundlePath: path, reason }) => {
1417
- const record = await store.write(
1418
- path,
1419
- { ...composeNoDecisionRecord(reason, actor, now()), overwrite: true },
1420
- actor
1421
- );
1422
- return { conceptId: record.conceptId };
1423
- }
1961
+ fromArgv: (argv) => {
1962
+ const budget = argvFlag(argv, "--budget");
1963
+ const fullUnder = argvFlag(argv, "--full-under");
1964
+ const profile = argvFlag(argv, "--profile");
1965
+ const format = argvFlag(argv, "--format");
1966
+ const event = argvFlag(argv, "--event");
1967
+ return {
1968
+ ...budget ? { budgetTokens: Number(budget) } : {},
1969
+ ...fullUnder ? { fullUnderTokens: Number(fullUnder) } : {},
1970
+ ...profile ? { profile } : {},
1971
+ ...format ? { format } : {},
1972
+ ...event ? { event } : {}
1973
+ };
1974
+ },
1975
+ run: async ({ store }, { budgetTokens, fullUnderTokens, profile, format, event }) => {
1976
+ const result = await buildContext(store, process.cwd(), {
1977
+ ...budgetTokens ? { budgetTokens } : {},
1978
+ ...fullUnderTokens ? { fullUnderTokens } : {},
1979
+ ...profile ? { profile } : {},
1980
+ // Degradations — a full pin that could not fit, a refused block — go
1981
+ // to stderr as well as into the block itself: stderr is diagnostics on
1982
+ // both surfaces (hooks discard it, MCP logs it), so an operator can
1983
+ // see budget pressure without reading injected context.
1984
+ warn: (entry) => process.stderr.write(`${JSON.stringify(entry)}
1985
+ `)
1986
+ });
1987
+ if (!result.block) return "";
1988
+ return format === "json" ? toHookJson(result.block, event ?? "SessionStart") : result.block;
1989
+ }
1990
+ });
1991
+
1992
+ // src/commands/list.ts
1993
+ var import_zod10 = require("zod");
1994
+ var listCommand = define({
1995
+ name: "list",
1996
+ tool: "kb_list",
1997
+ usage: "list [type]",
1998
+ description: "Every record, optionally narrowed to one type. Use kb_query when you have a question; this is for enumerating.",
1999
+ input: import_zod10.z.object({ bundlePath, type: import_zod10.z.enum(KB_RECORD_TYPES).optional() }),
2000
+ fromArgv: (argv, path) => ({ bundlePath: path, type: argv[1] }),
2001
+ run: async ({ store }, { bundlePath: path, type }) => (await store.list(path, type)).map((record) => ({
2002
+ conceptId: record.conceptId,
2003
+ title: record.frontmatter.title ?? null,
2004
+ description: record.frontmatter.description ?? null,
2005
+ status: record.frontmatter.strauss_status,
2006
+ anchors: record.frontmatter.strauss_anchors ?? []
2007
+ }))
2008
+ });
2009
+
2010
+ // src/commands/load.ts
2011
+ var import_zod11 = require("zod");
2012
+ var loadCommand = define({
2013
+ name: "load",
2014
+ tool: "kb_load",
2015
+ usage: "load [type] [--budget N]",
2016
+ 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.",
2017
+ input: import_zod11.z.object({
2018
+ bundlePath,
2019
+ type: import_zod11.z.enum(KB_RECORD_TYPES).optional(),
2020
+ budgetTokens: import_zod11.z.number().int().positive().optional().describe("Approximate token ceiling. Defaults to 25000.")
1424
2021
  }),
1425
- define({
1426
- name: "status",
1427
- tool: "kb_status",
1428
- usage: "status <concept-id> <status>",
1429
- 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.",
1430
- input: import_zod6.z.object({
1431
- bundlePath,
1432
- conceptId,
1433
- status: import_zod6.z.enum(KB_RECORD_STATUSES)
1434
- }),
1435
- fromArgv: (argv, path) => ({
2022
+ fromArgv: (argv, path) => {
2023
+ const budget = argvFlag(argv, "--budget");
2024
+ return {
1436
2025
  bundlePath: path,
1437
- conceptId: argv[1],
1438
- status: argv[2]
1439
- }),
1440
- run: async ({ store, actor }, { bundlePath: path, conceptId: id, status }) => {
1441
- const record = await store.setStatus(path, id, status, actor);
1442
- return { conceptId: record.conceptId, status };
1443
- }
2026
+ ...argv[1] && argv[1] !== "--budget" ? { type: argv[1] } : {},
2027
+ ...budget ? { budgetTokens: Number(budget) } : {}
2028
+ };
2029
+ },
2030
+ run: async ({ store }, { bundlePath: path, type, budgetTokens }) => {
2031
+ const result = await store.load(path, {
2032
+ ...type ? { type } : {},
2033
+ ...budgetTokens ? { budgetTokens } : {}
2034
+ });
2035
+ if (!result.loaded) return result;
2036
+ return {
2037
+ ...result,
2038
+ records: result.records.map((hit) => ({
2039
+ conceptId: hit.record.conceptId,
2040
+ title: hit.record.frontmatter.title ?? null,
2041
+ standing: hit.standing,
2042
+ supersededBy: hit.heads.map((head) => head.conceptId),
2043
+ warnings: hit.warnings,
2044
+ anchors: hit.record.frontmatter.strauss_anchors ?? [],
2045
+ body: hit.record.body
2046
+ }))
2047
+ };
2048
+ }
2049
+ });
2050
+
2051
+ // src/commands/log.ts
2052
+ var import_zod12 = require("zod");
2053
+ var logCommand = define({
2054
+ name: "log",
2055
+ tool: "kb_log",
2056
+ usage: "log",
2057
+ 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.",
2058
+ input: import_zod12.z.object({ bundlePath }),
2059
+ fromArgv: (_argv, path) => ({ bundlePath: path }),
2060
+ run: ({ store }, { bundlePath: path }) => store.readLog(path)
2061
+ });
2062
+
2063
+ // src/commands/no-decision.ts
2064
+ var import_zod13 = require("zod");
2065
+ var noDecisionCommand = define({
2066
+ name: "no-decision",
2067
+ tool: "kb_no_decision",
2068
+ usage: "no-decision <reason...>",
2069
+ 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.',
2070
+ input: import_zod13.z.object({ bundlePath, reason: import_zod13.z.string().min(1) }),
2071
+ fromArgv: (argv, path) => ({
2072
+ bundlePath: path,
2073
+ reason: argv.slice(1).join(" ").trim()
1444
2074
  }),
1445
- define({
1446
- name: "supersede",
1447
- tool: "kb_supersede",
1448
- usage: "supersede <concept-id> <replacement-id>",
1449
- 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.",
1450
- input: import_zod6.z.object({ bundlePath, conceptId, replacementId: conceptId }),
1451
- fromArgv: (argv, path) => ({
1452
- bundlePath: path,
1453
- conceptId: argv[1],
1454
- replacementId: argv[2]
1455
- }),
1456
- run: async ({ store, actor }, { bundlePath: path, conceptId: id, replacementId }) => {
1457
- await store.supersede(path, id, replacementId, actor);
1458
- return { superseded: id, replacedBy: replacementId };
1459
- }
2075
+ run: async ({ store, actor, now }, { bundlePath: path, reason }) => {
2076
+ await assertBaseNotFrozen(process.cwd(), path);
2077
+ const record = await store.write(
2078
+ path,
2079
+ { ...composeNoDecisionRecord(reason, actor, now()), overwrite: true },
2080
+ actor
2081
+ );
2082
+ return { conceptId: record.conceptId };
2083
+ }
2084
+ });
2085
+
2086
+ // src/commands/pin.ts
2087
+ var import_zod14 = require("zod");
2088
+ var pinCommand = define({
2089
+ name: "pin",
2090
+ tool: "kb_pin",
2091
+ usage: "pin [bundle-path] [--mode full|index] [--profiles a,b] [--local|--user] [--frozen|--unfreeze]",
2092
+ 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.",
2093
+ input: import_zod14.z.object({
2094
+ bundlePath,
2095
+ mode: import_zod14.z.enum(["full", "index"]).optional().describe(
2096
+ "full: always emit this base's records whole (still under the block budget); index: never upgrade. Absent: the profile's full-under threshold decides."
2097
+ ),
2098
+ profiles: import_zod14.z.array(import_zod14.z.string()).optional().describe("Context profiles this pin surfaces in. Absent: all of them."),
2099
+ layer: import_zod14.z.enum(["project", "local", "user"]).optional().describe(
2100
+ "Which manifest to write: project (committed, default), local (personal, gitignored), user (~/.strauss, every workspace)."
2101
+ ),
2102
+ frozen: import_zod14.z.boolean().optional().describe(
2103
+ "true: the base is concluded \u2014 writes against it refuse while pinned. false: lift a freeze."
2104
+ )
1460
2105
  }),
1461
- define({
1462
- name: "answer",
1463
- tool: "kb_answer",
1464
- usage: "answer <concept-id> <answer...>",
1465
- description: "Resolve an open question: sets the status, stamps who answered and when, and appends an Answer section. If the answer overturns an assumption or a decision, that is a supersession \u2014 do it explicitly.",
1466
- input: import_zod6.z.object({ bundlePath, conceptId, answer: import_zod6.z.string().min(1) }),
1467
- fromArgv: (argv, path) => ({
1468
- bundlePath: path,
1469
- conceptId: argv[1],
1470
- answer: argv.slice(2).join(" ").trim()
1471
- }),
1472
- run: async ({ store, actor }, { bundlePath: path, conceptId: id, answer }) => {
1473
- const record = await store.answer(path, id, answer, actor);
1474
- return { conceptId: record.conceptId };
1475
- }
2106
+ fromArgv: (argv, path) => {
2107
+ const positional = argv[1] && !argv[1].startsWith("--") ? argv[1] : path;
2108
+ const mode = argvFlag(argv, "--mode");
2109
+ const profiles = argvFlag(argv, "--profiles");
2110
+ const layer = argv.includes("--user") ? "user" : argv.includes("--local") ? "local" : void 0;
2111
+ const frozen = argv.includes("--frozen") ? true : argv.includes("--unfreeze") ? false : void 0;
2112
+ return {
2113
+ bundlePath: positional,
2114
+ ...mode ? { mode } : {},
2115
+ ...profiles ? {
2116
+ profiles: profiles.split(",").map((p) => p.trim()).filter(Boolean)
2117
+ } : {},
2118
+ ...layer ? { layer } : {},
2119
+ ...frozen !== void 0 ? { frozen } : {}
2120
+ };
2121
+ },
2122
+ run: ({ store, now }, { bundlePath: path, mode, profiles, layer, frozen }) => pinBase(store, process.cwd(), path, now(), {
2123
+ ...mode ? { mode } : {},
2124
+ ...profiles ? { profiles } : {},
2125
+ ...layer ? { layer } : {},
2126
+ ...frozen !== void 0 ? { frozen } : {}
2127
+ })
2128
+ });
2129
+
2130
+ // src/commands/pins.ts
2131
+ var import_zod15 = require("zod");
2132
+ var pinsCommand = define({
2133
+ name: "pins",
2134
+ tool: "kb_pins",
2135
+ usage: "pins",
2136
+ 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.",
2137
+ input: import_zod15.z.object({}),
2138
+ fromArgv: () => ({}),
2139
+ run: ({ store }) => listPins(store, process.cwd())
2140
+ });
2141
+
2142
+ // src/commands/query.ts
2143
+ var import_zod16 = require("zod");
2144
+ var queryCommand = define({
2145
+ name: "query",
2146
+ tool: "kb_query",
2147
+ usage: "query <text...>",
2148
+ 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.",
2149
+ input: import_zod16.z.object({
2150
+ bundlePath,
2151
+ text: import_zod16.z.string().optional(),
2152
+ type: import_zod16.z.enum(KB_RECORD_TYPES).optional(),
2153
+ includeNonCurrent: import_zod16.z.boolean().optional()
1476
2154
  }),
1477
- define({
1478
- name: "load",
1479
- tool: "kb_load",
1480
- usage: "load [type] [--budget N]",
1481
- 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.",
1482
- input: import_zod6.z.object({
1483
- bundlePath,
1484
- type: import_zod6.z.enum(KB_RECORD_TYPES).optional(),
1485
- budgetTokens: import_zod6.z.number().int().positive().optional().describe("Approximate token ceiling. Defaults to 25000.")
1486
- }),
1487
- fromArgv: (argv, path) => {
1488
- const at = argv.indexOf("--budget");
1489
- return {
1490
- bundlePath: path,
1491
- ...argv[1] && argv[1] !== "--budget" ? { type: argv[1] } : {},
1492
- ...at !== -1 && argv[at + 1] ? { budgetTokens: Number(argv[at + 1]) } : {}
1493
- };
1494
- },
1495
- run: async ({ store }, { bundlePath: path, type, budgetTokens }) => {
1496
- const result = await store.load(path, {
1497
- ...type ? { type } : {},
1498
- ...budgetTokens ? { budgetTokens } : {}
1499
- });
1500
- if (!result.loaded) return result;
1501
- return {
1502
- ...result,
1503
- records: result.records.map((hit) => ({
1504
- conceptId: hit.record.conceptId,
1505
- title: hit.record.frontmatter.title ?? null,
1506
- standing: hit.standing,
1507
- supersededBy: hit.heads.map((head) => head.conceptId),
1508
- warnings: hit.warnings,
1509
- anchors: hit.record.frontmatter.strauss_anchors ?? [],
1510
- body: hit.record.body
1511
- }))
1512
- };
1513
- }
2155
+ fromArgv: (argv, path) => ({
2156
+ bundlePath: path,
2157
+ text: argv.slice(1).join(" ").trim(),
2158
+ includeNonCurrent: true
1514
2159
  }),
1515
- define({
1516
- name: "query",
1517
- tool: "kb_query",
1518
- usage: "query <text...>",
1519
- 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 this over reading record files directly \u2014 relevance and standing are different questions, and a bare match answers only the first.",
1520
- input: import_zod6.z.object({
1521
- bundlePath,
1522
- text: import_zod6.z.string().optional(),
1523
- type: import_zod6.z.enum(KB_RECORD_TYPES).optional(),
1524
- includeNonCurrent: import_zod6.z.boolean().optional()
1525
- }),
1526
- fromArgv: (argv, path) => ({
1527
- bundlePath: path,
1528
- text: argv.slice(1).join(" ").trim(),
1529
- includeNonCurrent: true
1530
- }),
1531
- run: async ({ store }, { bundlePath: path, text, type, includeNonCurrent }) => (await store.query(path, text ?? "", {
1532
- ...type ? { type } : {},
1533
- includeNonCurrent: includeNonCurrent === true
1534
- })).map((hit) => ({
1535
- conceptId: hit.record.conceptId,
1536
- title: hit.record.frontmatter.title ?? null,
1537
- description: hit.record.frontmatter.description ?? null,
1538
- standing: hit.standing,
1539
- supersededBy: hit.heads.map((head) => head.conceptId),
1540
- warnings: hit.warnings,
1541
- body: hit.record.body
1542
- }))
2160
+ run: async ({ store }, { bundlePath: path, text, type, includeNonCurrent }) => (await store.query(path, text ?? "", {
2161
+ ...type ? { type } : {},
2162
+ includeNonCurrent: includeNonCurrent === true
2163
+ })).map((hit) => ({
2164
+ conceptId: hit.record.conceptId,
2165
+ title: hit.record.frontmatter.title ?? null,
2166
+ description: hit.record.frontmatter.description ?? null,
2167
+ standing: hit.standing,
2168
+ supersededBy: hit.heads.map((head) => head.conceptId),
2169
+ warnings: hit.warnings,
2170
+ body: hit.record.body
2171
+ }))
2172
+ });
2173
+
2174
+ // src/commands/read-index.ts
2175
+ var import_zod17 = require("zod");
2176
+ var readIndexCommand = define({
2177
+ name: "index",
2178
+ tool: "kb_index",
2179
+ usage: "index",
2180
+ 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.",
2181
+ input: import_zod17.z.object({ bundlePath }),
2182
+ fromArgv: (_argv, path) => ({ bundlePath: path }),
2183
+ run: ({ store }, { bundlePath: path }) => store.readIndex(path)
2184
+ });
2185
+
2186
+ // src/commands/schema.ts
2187
+ var import_zod18 = require("zod");
2188
+ var schemaCommand = define({
2189
+ name: "schema",
2190
+ tool: "kb_schema",
2191
+ usage: "schema",
2192
+ 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.",
2193
+ input: import_zod18.z.object({}),
2194
+ fromArgv: () => ({}),
2195
+ run: () => Promise.resolve(kbJsonSchemas())
2196
+ });
2197
+
2198
+ // src/commands/status.ts
2199
+ var import_zod19 = require("zod");
2200
+ var statusCommand = define({
2201
+ name: "status",
2202
+ tool: "kb_status",
2203
+ usage: "status <concept-id> <status>",
2204
+ 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.",
2205
+ input: import_zod19.z.object({
2206
+ bundlePath,
2207
+ conceptId,
2208
+ status: import_zod19.z.enum(KB_RECORD_STATUSES)
1543
2209
  }),
1544
- define({
1545
- name: "trace",
1546
- tool: "kb_trace",
1547
- usage: "trace <concept-id> [edges...]",
1548
- 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".',
1549
- input: import_zod6.z.object({
1550
- bundlePath,
1551
- conceptId,
1552
- edges: import_zod6.z.array(import_zod6.z.enum(TRACE_EDGES)).optional(),
1553
- depth: import_zod6.z.number().int().positive().optional()
1554
- }),
1555
- fromArgv: (argv, path) => ({
1556
- bundlePath: path,
1557
- conceptId: argv[1],
1558
- edges: argv.slice(2).filter((edge) => TRACE_EDGES.includes(edge))
1559
- }),
1560
- run: async ({ store }, { bundlePath: path, conceptId: id, edges, depth }) => (await store.trace(path, id, {
1561
- ...edges?.length ? { edges } : {},
1562
- ...depth ? { depth } : {}
1563
- })).map((step) => ({
1564
- conceptId: step.record.conceptId,
1565
- at: step.record.frontmatter.generated?.at ?? null,
1566
- status: step.record.frontmatter.strauss_status,
1567
- title: step.record.frontmatter.title ?? null,
1568
- depth: step.depth,
1569
- via: step.via,
1570
- body: step.record.body
1571
- }))
2210
+ fromArgv: (argv, path) => ({
2211
+ bundlePath: path,
2212
+ conceptId: argv[1],
2213
+ status: argv[2]
1572
2214
  }),
1573
- define({
1574
- name: "list",
1575
- tool: "kb_list",
1576
- usage: "list [type]",
1577
- description: "Every record, optionally narrowed to one type. Use kb_query when you have a question; this is for enumerating.",
1578
- input: import_zod6.z.object({ bundlePath, type: import_zod6.z.enum(KB_RECORD_TYPES).optional() }),
1579
- fromArgv: (argv, path) => ({ bundlePath: path, type: argv[1] }),
1580
- run: async ({ store }, { bundlePath: path, type }) => (await store.list(path, type)).map((record) => ({
1581
- conceptId: record.conceptId,
1582
- title: record.frontmatter.title ?? null,
1583
- description: record.frontmatter.description ?? null,
1584
- status: record.frontmatter.strauss_status,
1585
- anchors: record.frontmatter.strauss_anchors ?? []
1586
- }))
2215
+ run: async ({ store, actor }, { bundlePath: path, conceptId: id, status }) => {
2216
+ await assertBaseNotFrozen(process.cwd(), path);
2217
+ const record = await store.setStatus(path, id, status, actor);
2218
+ return { conceptId: record.conceptId, status };
2219
+ }
2220
+ });
2221
+
2222
+ // src/commands/supersede.ts
2223
+ var import_zod20 = require("zod");
2224
+ var supersedeCommand = define({
2225
+ name: "supersede",
2226
+ tool: "kb_supersede",
2227
+ usage: "supersede <concept-id> <replacement-id>",
2228
+ 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.",
2229
+ input: import_zod20.z.object({ bundlePath, conceptId, replacementId: conceptId }),
2230
+ fromArgv: (argv, path) => ({
2231
+ bundlePath: path,
2232
+ conceptId: argv[1],
2233
+ replacementId: argv[2]
1587
2234
  }),
1588
- define({
1589
- name: "index",
1590
- tool: "kb_index",
1591
- usage: "index",
1592
- 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.",
1593
- input: import_zod6.z.object({ bundlePath }),
1594
- fromArgv: (_argv, path) => ({ bundlePath: path }),
1595
- run: ({ store }, { bundlePath: path }) => store.readIndex(path)
2235
+ run: async ({ store, actor }, { bundlePath: path, conceptId: id, replacementId }) => {
2236
+ await assertBaseNotFrozen(process.cwd(), path);
2237
+ await store.supersede(path, id, replacementId, actor);
2238
+ return { superseded: id, replacedBy: replacementId };
2239
+ }
2240
+ });
2241
+
2242
+ // src/commands/sync-instructions.ts
2243
+ var import_zod21 = require("zod");
2244
+ var syncInstructionsCommand = define({
2245
+ name: "sync-instructions",
2246
+ usage: "sync-instructions <file> [--profile NAME] [--budget N] [--full-under N]",
2247
+ 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.",
2248
+ input: import_zod21.z.object({
2249
+ file: import_zod21.z.string().min(1).describe("The instruction file to edit in place."),
2250
+ budgetTokens: import_zod21.z.number().int().positive().optional(),
2251
+ fullUnderTokens: import_zod21.z.number().int().positive().optional(),
2252
+ profile: import_zod21.z.string().optional()
1596
2253
  }),
1597
- define({
1598
- name: "log",
1599
- tool: "kb_log",
1600
- usage: "log",
1601
- 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.",
1602
- input: import_zod6.z.object({ bundlePath }),
1603
- fromArgv: (_argv, path) => ({ bundlePath: path }),
1604
- run: ({ store }, { bundlePath: path }) => store.readLog(path)
2254
+ fromArgv: (argv) => {
2255
+ const budget = argvFlag(argv, "--budget");
2256
+ const fullUnder = argvFlag(argv, "--full-under");
2257
+ const profile = argvFlag(argv, "--profile");
2258
+ return {
2259
+ file: argv[1],
2260
+ ...budget ? { budgetTokens: Number(budget) } : {},
2261
+ ...fullUnder ? { fullUnderTokens: Number(fullUnder) } : {},
2262
+ ...profile ? { profile } : {}
2263
+ };
2264
+ },
2265
+ run: async ({ store }, { file, budgetTokens, fullUnderTokens, profile }) => {
2266
+ const result = await buildContext(store, process.cwd(), {
2267
+ ...budgetTokens ? { budgetTokens } : {},
2268
+ ...fullUnderTokens ? { fullUnderTokens } : {},
2269
+ ...profile ? { profile } : {},
2270
+ warn: (entry) => process.stderr.write(`${JSON.stringify(entry)}
2271
+ `)
2272
+ });
2273
+ return syncInstructions(file, result.block);
2274
+ }
2275
+ });
2276
+
2277
+ // src/commands/trace.ts
2278
+ var import_zod22 = require("zod");
2279
+ var traceCommand = define({
2280
+ name: "trace",
2281
+ tool: "kb_trace",
2282
+ usage: "trace <concept-id> [edges...]",
2283
+ 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.',
2284
+ input: import_zod22.z.object({
2285
+ bundlePath,
2286
+ conceptId,
2287
+ edges: import_zod22.z.array(import_zod22.z.enum(TRACE_EDGES)).optional(),
2288
+ depth: import_zod22.z.number().int().positive().optional()
1605
2289
  }),
1606
- define({
1607
- name: "validate",
1608
- tool: "kb_validate",
1609
- usage: "validate",
1610
- 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.",
1611
- input: import_zod6.z.object({ bundlePath }),
1612
- fromArgv: (_argv, path) => ({ bundlePath: path }),
1613
- run: async ({ store }, { bundlePath: path }) => validateBundle(await store.list(path)),
1614
- failsWhen: (result) => Array.isArray(result) && result.length > 0
2290
+ fromArgv: (argv, path) => ({
2291
+ bundlePath: path,
2292
+ conceptId: argv[1],
2293
+ edges: argv.slice(2).filter((edge) => TRACE_EDGES.includes(edge))
1615
2294
  }),
1616
- define({
1617
- name: "schema",
1618
- tool: "kb_schema",
1619
- usage: "schema",
1620
- 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.",
1621
- input: import_zod6.z.object({}),
1622
- fromArgv: () => ({}),
1623
- run: () => Promise.resolve(kbJsonSchemas())
2295
+ run: async ({ store }, { bundlePath: path, conceptId: id, edges, depth }) => (await store.trace(path, id, {
2296
+ ...edges?.length ? { edges } : {},
2297
+ ...depth ? { depth } : {}
2298
+ })).map((step) => ({
2299
+ conceptId: step.record.conceptId,
2300
+ at: step.record.frontmatter.generated?.at ?? null,
2301
+ status: step.record.frontmatter.strauss_status,
2302
+ title: step.record.frontmatter.title ?? null,
2303
+ depth: step.depth,
2304
+ via: step.via,
2305
+ body: step.record.body
2306
+ }))
2307
+ });
2308
+
2309
+ // src/commands/types.ts
2310
+ var import_zod23 = require("zod");
2311
+ var typesCommand = define({
2312
+ name: "types",
2313
+ tool: "kb_types",
2314
+ usage: "types",
2315
+ 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.",
2316
+ input: import_zod23.z.object({}),
2317
+ fromArgv: () => ({}),
2318
+ run: () => Promise.resolve(RECORD_TYPES)
2319
+ });
2320
+
2321
+ // src/commands/unpin.ts
2322
+ var import_zod24 = require("zod");
2323
+ var unpinCommand = define({
2324
+ name: "unpin",
2325
+ tool: "kb_unpin",
2326
+ usage: "unpin [bundle-path]",
2327
+ 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.",
2328
+ input: import_zod24.z.object({ bundlePath }),
2329
+ fromArgv: (argv, path) => ({ bundlePath: argv[1] ?? path }),
2330
+ run: (_ctx, { bundlePath: path }) => unpinBase(process.cwd(), path)
2331
+ });
2332
+
2333
+ // src/commands/validate.ts
2334
+ var import_zod25 = require("zod");
2335
+ var validateCommand = define({
2336
+ name: "validate",
2337
+ tool: "kb_validate",
2338
+ usage: "validate",
2339
+ 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.",
2340
+ input: import_zod25.z.object({ bundlePath }),
2341
+ fromArgv: (_argv, path) => ({ bundlePath: path }),
2342
+ run: async ({ store }, { bundlePath: path }) => validateBundle(await store.list(path)),
2343
+ failsWhen: (result) => Array.isArray(result) && result.length > 0
2344
+ });
2345
+
2346
+ // src/commands/write.ts
2347
+ var import_zod26 = require("zod");
2348
+ var writeCommand = define({
2349
+ name: "write",
2350
+ tool: "kb_write",
2351
+ usage: "write <type> < record.json",
2352
+ description: [
2353
+ "Write one record. Search first \u2014 the same knowledge filed twice under different slugs is how a base rots, and a duplicate concept id is rejected rather than overwritten. Call kb_types for the sections each type accepts.",
2354
+ "",
2355
+ "Judgment the tool cannot enforce for you:",
2356
+ "- An unsourced claim is an `assumption` record with assumption: true, never a `fact` with a vague source. The distinction is what lets a later reader separate what was established from what was guessed.",
2357
+ "- When two records conflict, say so in a `risk`, an `open-question`, or a superseding `decision`. Quietly picking a winner destroys the disagreement, which is usually the useful part.",
2358
+ "- Prefer a new record over overloading an existing one, and keep each short. A record nobody finishes reading is not durable memory.",
2359
+ "- Records are never deleted; supersede instead, so the earlier reasoning stays inspectable."
2360
+ ].join("\n"),
2361
+ input: import_zod26.z.object({
2362
+ bundlePath,
2363
+ type: import_zod26.z.enum(KB_RECORD_TYPES),
2364
+ input: composeInputSchema
1624
2365
  }),
1625
- define({
1626
- name: "types",
1627
- tool: "kb_types",
1628
- usage: "types",
1629
- 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.",
1630
- input: import_zod6.z.object({}),
1631
- fromArgv: () => ({}),
1632
- run: () => Promise.resolve(RECORD_TYPES)
1633
- })
2366
+ fromArgv: async (argv, path, stdin) => ({
2367
+ bundlePath: path,
2368
+ type: argv[1],
2369
+ input: JSON.parse(await stdin())
2370
+ }),
2371
+ run: async ({ store, actor, now }, { bundlePath: path, type, input }) => {
2372
+ await assertBaseNotFrozen(process.cwd(), path);
2373
+ const record = await store.write(
2374
+ path,
2375
+ composeRecord(type, input, actor, now()),
2376
+ actor
2377
+ );
2378
+ return { conceptId: record.conceptId };
2379
+ }
2380
+ });
2381
+
2382
+ // src/commands/write-decision.ts
2383
+ var import_zod27 = require("zod");
2384
+ var writeDecisionCommand = define({
2385
+ name: "write-decision",
2386
+ tool: "kb_write_decision",
2387
+ usage: "write-decision < decision.json",
2388
+ description: [
2389
+ "Write a decision. Takes `alternative` and `impact` as fields rather than free sections, because what was rejected is the part a later reader cannot reconstruct from the code \u2014 a heading is too easy to leave empty.",
2390
+ "",
2391
+ "What belongs in one:",
2392
+ '- Record a decision when a later reader would otherwise "simplify" the constraint away. If the diff already answers the question, there is nothing here to write.',
2393
+ "- `alternative` is what you turned down and why, not a list of everything considered.",
2394
+ "- A reference to material you read goes in `sources`; a reference to code goes in `anchors`; a reference to another record goes in `relatedConceptIds`."
2395
+ ].join("\n"),
2396
+ input: import_zod27.z.object({ bundlePath, input: decisionInputSchema }),
2397
+ fromArgv: async (_argv, path, stdin) => ({
2398
+ bundlePath: path,
2399
+ input: JSON.parse(await stdin())
2400
+ }),
2401
+ run: async ({ store, actor, now }, { bundlePath: path, input }) => {
2402
+ await assertBaseNotFrozen(process.cwd(), path);
2403
+ const record = await store.write(
2404
+ path,
2405
+ composeDecisionRecord(input, actor, now()),
2406
+ actor
2407
+ );
2408
+ return { conceptId: record.conceptId };
2409
+ }
2410
+ });
2411
+
2412
+ // src/commands/index.ts
2413
+ var KB_COMMANDS = [
2414
+ writeCommand,
2415
+ writeDecisionCommand,
2416
+ noDecisionCommand,
2417
+ statusCommand,
2418
+ supersedeCommand,
2419
+ answerCommand,
2420
+ loadCommand,
2421
+ queryCommand,
2422
+ traceCommand,
2423
+ listCommand,
2424
+ readIndexCommand,
2425
+ logCommand,
2426
+ validateCommand,
2427
+ schemaCommand,
2428
+ pinCommand,
2429
+ unpinCommand,
2430
+ pinsCommand,
2431
+ contextCommand,
2432
+ syncInstructionsCommand,
2433
+ typesCommand
1634
2434
  ];
1635
2435
  var KB_COMMANDS_BY_NAME = new Map(
1636
2436
  KB_COMMANDS.map((command) => [command.name, command])
@@ -1651,6 +2451,7 @@ function createKbMcpServer() {
1651
2451
  now: () => (/* @__PURE__ */ new Date()).toISOString()
1652
2452
  };
1653
2453
  for (const command of KB_COMMANDS) {
2454
+ if (!command.tool) continue;
1654
2455
  server.registerTool(
1655
2456
  command.tool,
1656
2457
  { description: command.description, inputSchema: command.input.shape },
@@ -1674,7 +2475,7 @@ async function runKbMcpServer() {
1674
2475
  }
1675
2476
 
1676
2477
  // src/cli.ts
1677
- var import_node_path3 = require("path");
2478
+ var import_node_path7 = require("path");
1678
2479
  async function runKbCli(argv) {
1679
2480
  const { bundle, rest } = takeBundle(argv);
1680
2481
  const name = rest[0] ?? "";
@@ -1704,6 +2505,7 @@ async function runKbCli(argv) {
1704
2505
  parsed.data
1705
2506
  );
1706
2507
  if (command.failsWhen?.(result)) process.exitCode = 1;
2508
+ if (result === "") return;
1707
2509
  process.stdout.write(
1708
2510
  typeof result === "string" ? result.endsWith("\n") ? result : `${result}
1709
2511
  ` : `${JSON.stringify(result, null, 2)}
@@ -1713,18 +2515,18 @@ async function runKbCli(argv) {
1713
2515
  function takeBundle(argv) {
1714
2516
  const at = argv.indexOf("--bundle");
1715
2517
  if (at === -1) {
1716
- return { bundle: (0, import_node_path3.join)(process.cwd(), KB_DIR), rest: argv };
2518
+ return { bundle: (0, import_node_path7.join)(process.cwd(), KB_DIR), rest: argv };
1717
2519
  }
1718
2520
  const bundle = argv[at + 1];
1719
2521
  if (!bundle) die("--bundle requires a path");
1720
2522
  return { bundle, rest: [...argv.slice(0, at), ...argv.slice(at + 2)] };
1721
2523
  }
1722
2524
  function readStdin() {
1723
- return new Promise((resolve2, reject) => {
2525
+ return new Promise((resolve5, reject) => {
1724
2526
  let text = "";
1725
2527
  process.stdin.setEncoding("utf8");
1726
2528
  process.stdin.on("data", (chunk) => text += chunk);
1727
- process.stdin.on("end", () => resolve2(text));
2529
+ process.stdin.on("end", () => resolve5(text));
1728
2530
  process.stdin.on("error", reject);
1729
2531
  });
1730
2532
  }
@@ -1757,6 +2559,9 @@ function usage() {
1757
2559
  // Annotate the CommonJS export names for ESM import in node:
1758
2560
  0 && (module.exports = {
1759
2561
  BaseError,
2562
+ CONTEXT_BEGIN,
2563
+ CONTEXT_END,
2564
+ CONTEXT_PROFILES,
1760
2565
  DECISION_TYPE,
1761
2566
  ErrorTypes,
1762
2567
  Fault,
@@ -1770,21 +2575,29 @@ function usage() {
1770
2575
  KB_RECORD_STATUSES,
1771
2576
  KB_RECORD_TYPES,
1772
2577
  KB_SLUG_PATTERN,
2578
+ KbBaseFrozenError,
1773
2579
  KbInvalidConceptIdError,
2580
+ KbPinsMalformedError,
1774
2581
  KbRecordAlreadyExistsError,
1775
2582
  KbRecordNotFoundError,
1776
2583
  KbStore,
1777
2584
  KbWriteConflictError,
1778
2585
  LOG_FILE,
1779
2586
  NO_DECISION_SLUG,
2587
+ PINS_FILE,
2588
+ PINS_LOCAL_FILE,
2589
+ PIN_LAYERS,
1780
2590
  RECORD_TYPES,
1781
2591
  SEARCH_INDEX_FILE,
1782
2592
  TRACE_EDGES,
1783
2593
  adjudicate,
2594
+ assertBaseNotFrozen,
2595
+ buildContext,
1784
2596
  composeDecisionRecord,
1785
2597
  composeInputSchema,
1786
2598
  composeNoDecisionRecord,
1787
2599
  composeRecord,
2600
+ contextProfileBudgets,
1788
2601
  createKbMcpServer,
1789
2602
  decisionInputSchema,
1790
2603
  indexIsStale,
@@ -1797,21 +2610,31 @@ function usage() {
1797
2610
  kbLogEntrySchema,
1798
2611
  kbRecordFrontmatterSchema,
1799
2612
  kbSourceSchema,
2613
+ listPins,
1800
2614
  loadQmd,
1801
2615
  matchToDiff,
2616
+ mergedContextBudgets,
1802
2617
  parseLog,
1803
2618
  parseMarkdownWithFrontmatter,
2619
+ pinBase,
2620
+ readMergedPins,
2621
+ readPinsLayer,
1804
2622
  renderIndex,
2623
+ renderIndexLine,
1805
2624
  renderLogEntry,
1806
2625
  resolveHeads,
1807
2626
  resolveHits,
2627
+ resolvePinPath,
1808
2628
  runKbCli,
1809
2629
  runKbMcpServer,
1810
2630
  searchBase,
1811
2631
  selectDecisions,
1812
2632
  splitMarkdownFrontmatter,
1813
2633
  stringifyMarkdownWithFrontmatter,
2634
+ syncInstructions,
2635
+ toHookJson,
1814
2636
  trace,
2637
+ unpinBase,
1815
2638
  validateBundle
1816
2639
  });
1817
2640
  //# sourceMappingURL=index.cjs.map