@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/mcp-main.cjs CHANGED
@@ -27,8 +27,8 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
27
27
  var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
28
28
  var import_stdio = require("@modelcontextprotocol/sdk/server/stdio.js");
29
29
 
30
- // src/commands.ts
31
- var import_zod6 = require("zod");
30
+ // src/decision-record.ts
31
+ var import_zod3 = require("zod");
32
32
 
33
33
  // src/compose.ts
34
34
  var import_zod2 = require("zod");
@@ -199,6 +199,16 @@ var composeInputSchema = import_zod2.z.object({
199
199
  sources: import_zod2.z.array(kbSourceSchema).optional(),
200
200
  /** No source exists, as a claim rather than a sentinel in `sources`. */
201
201
  assumption: import_zod2.z.boolean().optional(),
202
+ /**
203
+ * OKF `stale_after`: the absolute date this record stops being trusted.
204
+ * Anything the outside world can change — pricing, quotas, versions,
205
+ * reception counts — should carry one.
206
+ */
207
+ stale_after: import_zod2.z.string().regex(/^\d{4}-\d{2}-\d{2}$/, {
208
+ message: "stale_after must be YYYY-MM-DD"
209
+ }).refine((date) => !Number.isNaN(Date.parse(date)), {
210
+ message: "stale_after must be a real date"
211
+ }).optional(),
202
212
  verify: import_zod2.z.array(import_zod2.z.string().min(1)).optional(),
203
213
  tags: import_zod2.z.array(import_zod2.z.string().min(1)).optional(),
204
214
  /** Concept ids this record relates to; rendered as body links. */
@@ -231,6 +241,7 @@ function composeRecord(type, input, writtenBy, writtenAt) {
231
241
  verified: [],
232
242
  strauss_status: spec.initialStatus
233
243
  };
244
+ if (parsed.stale_after) frontmatter.stale_after = parsed.stale_after;
234
245
  if (parsed.anchors?.length) frontmatter.strauss_anchors = parsed.anchors;
235
246
  if (parsed.verify?.length) frontmatter.strauss_verify = parsed.verify;
236
247
  if (parsed.tags?.length) frontmatter.tags = parsed.tags;
@@ -267,7 +278,6 @@ ${text}`);
267
278
  }
268
279
 
269
280
  // src/decision-record.ts
270
- var import_zod3 = require("zod");
271
281
  var DECISION_TYPE = "decision";
272
282
  var NO_DECISION_SLUG = "none";
273
283
  var decisionInputSchema = composeInputSchema.omit({ sections: true }).extend({
@@ -305,458 +315,1349 @@ function composeNoDecisionRecord(reason, writtenBy, writtenAt) {
305
315
  );
306
316
  }
307
317
 
308
- // src/json-schema.ts
309
- var import_zod5 = require("zod");
318
+ // src/commands/answer.ts
319
+ var import_zod6 = require("zod");
310
320
 
311
- // src/kb-log.ts
321
+ // src/kb-pins/budgets.ts
322
+ function asBudgets(value) {
323
+ if (value === null || typeof value !== "object") return {};
324
+ const table = value;
325
+ const pick = (key, min) => {
326
+ const raw = table[key];
327
+ return typeof raw === "number" && Number.isInteger(raw) && raw >= min ? raw : void 0;
328
+ };
329
+ const budgetTokens = pick("budgetTokens", 1);
330
+ const fullUnderTokens = pick("fullUnderTokens", 0);
331
+ return {
332
+ ...budgetTokens ? { budgetTokens } : {},
333
+ ...fullUnderTokens !== void 0 ? { fullUnderTokens } : {}
334
+ };
335
+ }
336
+ function contextProfileBudgets(manifest, profile) {
337
+ const table = manifest.context;
338
+ if (table === null || typeof table !== "object") return {};
339
+ const entries = table;
340
+ return {
341
+ ...asBudgets(entries["default"]),
342
+ ...profile ? asBudgets(entries[profile]) : {}
343
+ };
344
+ }
345
+ function mergedContextBudgets(merged, profile) {
346
+ const layered = ["user", "local", "project"].map((layer) => {
347
+ const manifest = merged.manifests[layer];
348
+ return manifest ? contextProfileBudgets(manifest, profile) : {};
349
+ });
350
+ return { ...layered[0], ...layered[1], ...layered[2] };
351
+ }
352
+
353
+ // src/kb-pins/errors.ts
354
+ var KbPinsMalformedError = class extends Error {
355
+ constructor(file, cause) {
356
+ super(`pin manifest ${file} is not readable (${cause}) \u2014 fix or remove it`);
357
+ this.name = "KbPinsMalformedError";
358
+ }
359
+ };
360
+ var KbBaseFrozenError = class extends Error {
361
+ constructor(bundlePath2, layer) {
362
+ super(
363
+ `${bundlePath2} is frozen (read-only) by this workspace's ${layer} pin manifest \u2014 re-pin with --unfreeze, or unpin, to change it`
364
+ );
365
+ this.name = "KbBaseFrozenError";
366
+ }
367
+ };
368
+
369
+ // src/kb-pins/frozen.ts
370
+ var import_node_path3 = require("path");
371
+
372
+ // src/kb-pins/layers.ts
373
+ var import_promises = require("fs/promises");
374
+ var import_node_os = require("os");
375
+ var import_node_path2 = require("path");
376
+
377
+ // src/kb-pins/model.ts
378
+ var import_node_path = require("path");
312
379
  var import_zod4 = require("zod");
313
- var LOG_FILE = "log.jsonl";
314
- var kbLogEntrySchema = import_zod4.z.object({
315
- at: import_zod4.z.string().min(1),
316
- by: import_zod4.z.string().min(1),
317
- operation: import_zod4.z.string().min(1),
318
- conceptId: import_zod4.z.string().min(1),
319
- /** Second concept id, where the operation relates two — supersession. */
320
- target: import_zod4.z.string().min(1).optional()
321
- }).strict();
322
- function renderLogEntry(entry) {
323
- return `${JSON.stringify(kbLogEntrySchema.parse(entry))}
324
- `;
380
+ var PINS_FILE = (0, import_node_path.join)(".strauss", "kb-pins.json");
381
+ var PINS_LOCAL_FILE = (0, import_node_path.join)(".strauss", "kb-pins.local.json");
382
+ var PIN_LAYERS = ["project", "local", "user"];
383
+ var pinSchema = import_zod4.z.object({
384
+ /** Relative to the manifest's root, so the file is committable. */
385
+ path: import_zod4.z.string().min(1),
386
+ pinnedAt: import_zod4.z.string().min(1).optional(),
387
+ /**
388
+ * How `context` renders this base. `full` preloads the whole base into
389
+ * the block regardless of the full-under threshold — for a base whose
390
+ * contents should simply be present, the way an ADR base should be —
391
+ * still answering to the block budget, with an index fallback that says
392
+ * so when it cannot fit. `index` never upgrades, whatever the threshold.
393
+ * Absent: the profile's full-under threshold decides. Invalid values
394
+ * degrade to absent rather than failing the manifest.
395
+ */
396
+ mode: import_zod4.z.enum(["full", "index"]).optional().catch(void 0),
397
+ /**
398
+ * Context profiles this pin surfaces in (e.g. only at session-start,
399
+ * not per turn). Absent: every profile. A run without a profile sees
400
+ * every pin. A base that only matters to one skill is better loaded by
401
+ * that skill at point of use than pinned at all — pins are what every
402
+ * session should see.
403
+ */
404
+ profiles: import_zod4.z.array(import_zod4.z.string()).optional().catch(void 0),
405
+ /**
406
+ * The base is concluded — a finished piece of research, a frozen ADR
407
+ * set. Write commands against it refuse while this workspace holds the
408
+ * pin, and `context` labels it read-only. Workspace policy, not base
409
+ * state: the base itself stays copyable and writable elsewhere.
410
+ */
411
+ frozen: import_zod4.z.boolean().optional().catch(void 0)
412
+ }).passthrough();
413
+ var pinsManifestSchema = import_zod4.z.object({
414
+ pins: import_zod4.z.array(pinSchema).default([]),
415
+ /**
416
+ * Per-repo budgets for the `context` command, keyed by profile —
417
+ * `"session-start"`, `"compact"`, `"turn"`, or `"default"` for all of
418
+ * them. Deliberately untyped here: a typo'd budget must degrade to the
419
+ * built-in default, not make the whole manifest unreadable and silence
420
+ * the index at every session start. `contextProfileBudgets` does the
421
+ * tolerant read.
422
+ */
423
+ context: import_zod4.z.unknown().optional()
424
+ }).passthrough();
425
+
426
+ // src/kb-pins/layers.ts
427
+ function userRoot() {
428
+ return process.env.STRAUSS_KB_USER_ROOT || (0, import_node_os.homedir)();
325
429
  }
326
- function parseLog(raw) {
327
- const entries = [];
328
- const malformed = [];
329
- raw.split("\n").forEach((text, index) => {
330
- if (!text.trim()) return;
331
- let value;
430
+ function layerRoot(workspaceDir, layer) {
431
+ return layer === "user" ? userRoot() : (0, import_node_path2.resolve)(workspaceDir);
432
+ }
433
+ function layerFile(workspaceDir, layer) {
434
+ return (0, import_node_path2.join)(
435
+ layerRoot(workspaceDir, layer),
436
+ layer === "local" ? PINS_LOCAL_FILE : PINS_FILE
437
+ );
438
+ }
439
+ async function readPinsLayer(workspaceDir, layer) {
440
+ const file = layerFile(workspaceDir, layer);
441
+ let raw;
442
+ try {
443
+ raw = await (0, import_promises.readFile)(file, "utf8");
444
+ } catch {
445
+ return { pins: [] };
446
+ }
447
+ let parsed;
448
+ try {
449
+ parsed = JSON.parse(raw);
450
+ } catch (error) {
451
+ throw new KbPinsMalformedError(
452
+ file,
453
+ error instanceof Error ? error.message : "invalid JSON"
454
+ );
455
+ }
456
+ const manifest = pinsManifestSchema.safeParse(parsed);
457
+ if (!manifest.success) {
458
+ throw new KbPinsMalformedError(
459
+ file,
460
+ manifest.error.issues[0]?.message ?? "invalid shape"
461
+ );
462
+ }
463
+ return manifest.data;
464
+ }
465
+ async function writePinsLayer(workspaceDir, layer, manifest) {
466
+ const file = layerFile(workspaceDir, layer);
467
+ await (0, import_promises.mkdir)((0, import_node_path2.dirname)(file), { recursive: true });
468
+ await (0, import_promises.writeFile)(file, `${JSON.stringify(manifest, null, 2)}
469
+ `, "utf8");
470
+ }
471
+ function resolvePinPath(rootDir, path) {
472
+ return (0, import_node_path2.isAbsolute)(path) ? (0, import_node_path2.resolve)(path) : (0, import_node_path2.resolve)(rootDir, path.split("/").join(import_node_path2.sep));
473
+ }
474
+ function storablePath(rootDir, bundlePath2) {
475
+ const rel = (0, import_node_path2.relative)((0, import_node_path2.resolve)(rootDir), (0, import_node_path2.resolve)(bundlePath2));
476
+ return (rel === "" ? "." : rel).split(import_node_path2.sep).join("/");
477
+ }
478
+ async function readMergedPins(workspaceDir) {
479
+ const manifests = {};
480
+ const pins = [];
481
+ const seen = /* @__PURE__ */ new Set();
482
+ for (const layer of PIN_LAYERS) {
483
+ let manifest;
332
484
  try {
333
- value = JSON.parse(text);
485
+ manifest = await readPinsLayer(workspaceDir, layer);
334
486
  } catch {
335
- malformed.push({ line: index + 1, text });
336
- return;
487
+ continue;
337
488
  }
338
- const parsed = kbLogEntrySchema.safeParse(value);
339
- if (!parsed.success) {
340
- malformed.push({ line: index + 1, text });
341
- return;
489
+ manifests[layer] = manifest;
490
+ const root = layerRoot(workspaceDir, layer);
491
+ for (const entry of manifest.pins) {
492
+ const absolutePath = resolvePinPath(root, entry.path);
493
+ if (seen.has(absolutePath)) continue;
494
+ seen.add(absolutePath);
495
+ pins.push({ ...entry, layer, absolutePath });
342
496
  }
343
- entries.push(parsed.data);
344
- });
345
- return { entries, malformed };
497
+ }
498
+ return { pins, manifests };
346
499
  }
347
500
 
348
- // src/json-schema.ts
349
- function kbJsonSchemas() {
350
- return {
351
- recordFrontmatter: import_zod5.z.toJSONSchema(kbRecordFrontmatterSchema, {
352
- io: "input"
353
- }),
354
- composeInput: import_zod5.z.toJSONSchema(composeInputSchema, { io: "input" }),
355
- logEntry: import_zod5.z.toJSONSchema(kbLogEntrySchema, { io: "input" })
356
- };
501
+ // src/kb-pins/frozen.ts
502
+ async function assertBaseNotFrozen(workspaceDir, bundlePath2) {
503
+ const merged = await readMergedPins(workspaceDir);
504
+ const absolute = (0, import_node_path3.resolve)(bundlePath2);
505
+ const pin = merged.pins.find((entry) => entry.absolutePath === absolute);
506
+ if (pin?.frozen === true) {
507
+ throw new KbBaseFrozenError(pin.path, pin.layer);
508
+ }
357
509
  }
358
510
 
359
- // src/trace.ts
360
- var TRACE_EDGES = ["supersession", "anchor", "source"];
361
- function trace(seedId, bundle, options = {}) {
362
- const edges = options.edges?.length ? options.edges : TRACE_EDGES;
363
- const maxDepth = options.depth ?? 3;
364
- const byId = new Map(bundle.map((record) => [record.conceptId, record]));
365
- const seed = byId.get(seedId);
366
- if (!seed) return [];
367
- const reached = /* @__PURE__ */ new Map([
368
- [seedId, { record: seed, depth: 0, via: [] }]
369
- ]);
370
- let frontier = [seed];
371
- for (let depth = 1; depth <= maxDepth && frontier.length; depth += 1) {
372
- const next = [];
373
- for (const from of frontier) {
374
- for (const edge of edges) {
375
- for (const record of neighbours(from, bundle, edge)) {
376
- const existing = reached.get(record.conceptId);
377
- if (existing) {
378
- if (existing.depth > 0 && !existing.via.includes(edge)) {
379
- existing.via.push(edge);
380
- }
381
- continue;
382
- }
383
- reached.set(record.conceptId, { record, depth, via: [edge] });
384
- next.push(record);
385
- }
386
- }
387
- }
388
- frontier = next;
389
- }
390
- return [...reached.values()].sort(byGeneratedAt);
511
+ // src/kb-pins/list.ts
512
+ async function listPins(store, workspaceDir) {
513
+ const merged = await readMergedPins(workspaceDir);
514
+ return Promise.all(
515
+ merged.pins.map(async (entry) => {
516
+ const records = await store.list(entry.absolutePath);
517
+ return {
518
+ path: entry.path,
519
+ layer: entry.layer,
520
+ pinnedAt: entry.pinnedAt ?? null,
521
+ absolutePath: entry.absolutePath,
522
+ valid: records.length > 0,
523
+ recordCount: records.length,
524
+ mode: entry.mode ?? null,
525
+ profiles: entry.profiles ?? null,
526
+ frozen: entry.frozen === true
527
+ };
528
+ })
529
+ );
391
530
  }
392
- function neighbours(from, bundle, edge) {
393
- switch (edge) {
394
- case "supersession":
395
- return bundle.filter(
396
- (candidate) => candidate.conceptId !== from.conceptId && (candidate.conceptId === from.frontmatter.strauss_superseded_by || from.frontmatter.strauss_supersedes?.includes(
397
- candidate.conceptId
398
- ) || candidate.frontmatter.strauss_superseded_by === from.conceptId || candidate.frontmatter.strauss_supersedes?.includes(from.conceptId))
399
- );
400
- // The edge that answers "why is this code shaped this way": every record
401
- // attached to the same file or symbol, whatever its standing.
402
- case "anchor": {
403
- const mine = from.frontmatter.strauss_anchors ?? [];
404
- if (!mine.length) return [];
405
- return bundle.filter(
406
- (candidate) => candidate.conceptId !== from.conceptId && (candidate.frontmatter.strauss_anchors ?? []).some(
407
- (theirs) => mine.some((ours) => anchorsTouch(ours, theirs))
408
- )
409
- );
410
- }
411
- case "source": {
412
- const mine = new Set((from.frontmatter.sources ?? []).map((s) => s.id));
413
- if (!mine.size) return [];
414
- return bundle.filter(
415
- (candidate) => candidate.conceptId !== from.conceptId && (candidate.frontmatter.sources ?? []).some(
416
- (source) => mine.has(source.id)
531
+
532
+ // src/kb-pins/pin.ts
533
+ async function pinBase(store, workspaceDir, bundlePath2, at, options = {}) {
534
+ const layer = options.layer ?? "project";
535
+ const root = layerRoot(workspaceDir, layer);
536
+ const manifest = await readPinsLayer(workspaceDir, layer);
537
+ const absolute = resolvePinPath(root, storablePath(root, bundlePath2));
538
+ const existing = manifest.pins.find(
539
+ (entry2) => resolvePinPath(root, entry2.path) === absolute
540
+ );
541
+ const records = await store.list(absolute);
542
+ const warning = records.length === 0 ? `no records found at ${absolute} \u2014 pinned anyway; bases are routinely pinned before they are populated` : void 0;
543
+ const fields = {
544
+ ...options.mode ? { mode: options.mode } : {},
545
+ ...options.profiles?.length ? { profiles: options.profiles } : {},
546
+ ...options.frozen !== void 0 ? { frozen: options.frozen } : {}
547
+ };
548
+ if (existing) {
549
+ const updated = { ...existing, ...fields };
550
+ if (Object.keys(fields).length) {
551
+ await writePinsLayer(workspaceDir, layer, {
552
+ ...manifest,
553
+ pins: manifest.pins.map(
554
+ (entry2) => entry2 === existing ? updated : entry2
417
555
  )
418
- );
556
+ });
419
557
  }
558
+ return {
559
+ path: existing.path,
560
+ layer,
561
+ pinnedAt: existing.pinnedAt ?? at,
562
+ alreadyPinned: true,
563
+ ...updated.mode ? { mode: updated.mode } : {},
564
+ ...updated.profiles ? { profiles: updated.profiles } : {},
565
+ ...updated.frozen !== void 0 ? { frozen: updated.frozen } : {},
566
+ ...warning ? { warning } : {}
567
+ };
420
568
  }
421
- }
422
- function anchorsTouch(left, right) {
423
- if (left.file !== right.file) return false;
424
- if (!left.symbol || !right.symbol) return true;
425
- return left.symbol === right.symbol;
426
- }
427
- function byGeneratedAt(left, right) {
428
- const at = (step) => step.record.frontmatter.generated?.at ?? "";
429
- return at(left).localeCompare(at(right)) || left.depth - right.depth;
569
+ const entry = {
570
+ path: storablePath(root, bundlePath2),
571
+ pinnedAt: at,
572
+ ...fields
573
+ };
574
+ await writePinsLayer(workspaceDir, layer, {
575
+ ...manifest,
576
+ pins: [...manifest.pins, entry]
577
+ });
578
+ return {
579
+ path: entry.path,
580
+ layer,
581
+ pinnedAt: at,
582
+ alreadyPinned: false,
583
+ ...fields,
584
+ ...warning ? { warning } : {}
585
+ };
430
586
  }
431
587
 
432
- // src/validate.ts
433
- function validateBundle(records) {
434
- const byId = new Map(records.map((record) => [record.conceptId, record]));
435
- const problems = [];
436
- const report = (check, conceptId2, note) => problems.push({ check, conceptId: conceptId2, note });
437
- for (const record of records) {
438
- const { conceptId: conceptId2, frontmatter: fm } = record;
439
- if (!isKbRecordType(fm.type)) {
440
- report("type", conceptId2, `unrecognised type "${fm.type}"`);
441
- }
442
- if (fm.strauss_status === "superseded") {
443
- const by = fm.strauss_superseded_by;
444
- if (!by) {
445
- report("superseded_by", conceptId2, "superseded with no replacement");
446
- } else if (!byId.has(by)) {
447
- report("superseded_by", conceptId2, `replacement ${by} is missing`);
448
- } else if (!byId.get(by)?.frontmatter.strauss_supersedes?.includes(conceptId2)) {
449
- report("backlink", by, `does not list ${conceptId2} in supersedes`);
450
- }
451
- }
452
- for (const old of fm.strauss_supersedes ?? []) {
453
- const previous = byId.get(old);
454
- if (!previous) {
455
- report("supersedes", conceptId2, `target ${old} is missing`);
456
- } else if (previous.frontmatter.strauss_status !== "superseded") {
457
- report("supersedes", conceptId2, `${old} is not marked superseded`);
458
- }
588
+ // src/kb-pins/unpin.ts
589
+ var import_node_path4 = require("path");
590
+ async function unpinBase(workspaceDir, bundlePath2) {
591
+ const layers = [];
592
+ for (const layer of PIN_LAYERS) {
593
+ const root = layerRoot(workspaceDir, layer);
594
+ let manifest;
595
+ try {
596
+ manifest = await readPinsLayer(workspaceDir, layer);
597
+ } catch {
598
+ continue;
459
599
  }
460
- if (fm.strauss_assumption && fm.sources?.length) {
461
- report("assumption", conceptId2, "marked an assumption but cites sources");
600
+ const absolute = resolvePinPath(root, storablePath(root, bundlePath2));
601
+ const kept = manifest.pins.filter(
602
+ (entry) => resolvePinPath(root, entry.path) !== absolute
603
+ );
604
+ if (kept.length !== manifest.pins.length) {
605
+ await writePinsLayer(workspaceDir, layer, { ...manifest, pins: kept });
606
+ layers.push(layer);
462
607
  }
463
608
  }
464
- return problems;
609
+ return {
610
+ path: storablePath((0, import_node_path4.resolve)(workspaceDir), bundlePath2),
611
+ removed: layers.length > 0,
612
+ layers
613
+ };
465
614
  }
466
615
 
467
- // src/commands.ts
468
- var bundlePath = import_zod6.z.string().min(1).describe("Absolute path to the knowledge base directory.");
469
- var conceptId = import_zod6.z.string().min(1).describe("e.g. decision.cursor-v2");
616
+ // src/commands/model.ts
617
+ var import_zod5 = require("zod");
618
+ var bundlePath = import_zod5.z.string().min(1).describe("Absolute path to the knowledge base directory.");
619
+ var conceptId = import_zod5.z.string().min(1).describe("e.g. decision.cursor-v2");
470
620
  function define(command) {
471
621
  return command;
472
622
  }
473
- var KB_COMMANDS = [
474
- define({
475
- name: "write",
476
- tool: "kb_write",
477
- usage: "write <type> < record.json",
478
- description: [
479
- "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.",
480
- "",
481
- "Judgment the tool cannot enforce for you:",
482
- "- 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.",
483
- "- 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.",
484
- "- Prefer a new record over overloading an existing one, and keep each short. A record nobody finishes reading is not durable memory.",
485
- "- Records are never deleted; supersede instead, so the earlier reasoning stays inspectable."
486
- ].join("\n"),
487
- input: import_zod6.z.object({
488
- bundlePath,
489
- type: import_zod6.z.enum(KB_RECORD_TYPES),
490
- input: composeInputSchema
491
- }),
492
- fromArgv: async (argv, path, stdin) => ({
493
- bundlePath: path,
494
- type: argv[1],
495
- input: JSON.parse(await stdin())
496
- }),
497
- run: async ({ store, actor, now }, { bundlePath: path, type, input }) => {
498
- const record = await store.write(
499
- path,
500
- composeRecord(type, input, actor, now()),
501
- actor
502
- );
503
- return { conceptId: record.conceptId };
504
- }
505
- }),
506
- define({
507
- name: "write-decision",
508
- tool: "kb_write_decision",
509
- usage: "write-decision < decision.json",
510
- description: [
511
- "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.",
512
- "",
513
- "What belongs in one:",
514
- '- 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.',
515
- "- `alternative` is what you turned down and why, not a list of everything considered.",
516
- "- A reference to material you read goes in `sources`; a reference to code goes in `anchors`; a reference to another record goes in `relatedConceptIds`."
517
- ].join("\n"),
518
- input: import_zod6.z.object({ bundlePath, input: decisionInputSchema }),
519
- fromArgv: async (_argv, path, stdin) => ({
520
- bundlePath: path,
521
- input: JSON.parse(await stdin())
522
- }),
523
- run: async ({ store, actor, now }, { bundlePath: path, input }) => {
524
- const record = await store.write(
525
- path,
526
- composeDecisionRecord(input, actor, now()),
527
- actor
528
- );
529
- return { conceptId: record.conceptId };
530
- }
531
- }),
532
- define({
533
- name: "no-decision",
534
- tool: "kb_no_decision",
535
- usage: "no-decision <reason...>",
536
- 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.',
537
- input: import_zod6.z.object({ bundlePath, reason: import_zod6.z.string().min(1) }),
538
- fromArgv: (argv, path) => ({
539
- bundlePath: path,
540
- reason: argv.slice(1).join(" ").trim()
541
- }),
542
- run: async ({ store, actor, now }, { bundlePath: path, reason }) => {
543
- const record = await store.write(
544
- path,
545
- { ...composeNoDecisionRecord(reason, actor, now()), overwrite: true },
546
- actor
547
- );
548
- return { conceptId: record.conceptId };
549
- }
550
- }),
551
- define({
552
- name: "status",
553
- tool: "kb_status",
554
- usage: "status <concept-id> <status>",
555
- 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.",
556
- input: import_zod6.z.object({
557
- bundlePath,
558
- conceptId,
559
- status: import_zod6.z.enum(KB_RECORD_STATUSES)
560
- }),
561
- fromArgv: (argv, path) => ({
562
- bundlePath: path,
563
- conceptId: argv[1],
564
- status: argv[2]
565
- }),
566
- run: async ({ store, actor }, { bundlePath: path, conceptId: id, status }) => {
567
- const record = await store.setStatus(path, id, status, actor);
568
- return { conceptId: record.conceptId, status };
569
- }
570
- }),
571
- define({
572
- name: "supersede",
573
- tool: "kb_supersede",
574
- usage: "supersede <concept-id> <replacement-id>",
575
- 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.",
576
- input: import_zod6.z.object({ bundlePath, conceptId, replacementId: conceptId }),
577
- fromArgv: (argv, path) => ({
578
- bundlePath: path,
579
- conceptId: argv[1],
580
- replacementId: argv[2]
581
- }),
582
- run: async ({ store, actor }, { bundlePath: path, conceptId: id, replacementId }) => {
583
- await store.supersede(path, id, replacementId, actor);
584
- return { superseded: id, replacedBy: replacementId };
585
- }
586
- }),
587
- define({
588
- name: "answer",
589
- tool: "kb_answer",
590
- usage: "answer <concept-id> <answer...>",
591
- 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.",
592
- input: import_zod6.z.object({ bundlePath, conceptId, answer: import_zod6.z.string().min(1) }),
593
- fromArgv: (argv, path) => ({
594
- bundlePath: path,
595
- conceptId: argv[1],
596
- answer: argv.slice(2).join(" ").trim()
597
- }),
598
- run: async ({ store, actor }, { bundlePath: path, conceptId: id, answer }) => {
599
- const record = await store.answer(path, id, answer, actor);
600
- return { conceptId: record.conceptId };
601
- }
602
- }),
603
- define({
604
- name: "load",
605
- tool: "kb_load",
606
- usage: "load [type] [--budget N]",
607
- 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.",
608
- input: import_zod6.z.object({
609
- bundlePath,
610
- type: import_zod6.z.enum(KB_RECORD_TYPES).optional(),
611
- budgetTokens: import_zod6.z.number().int().positive().optional().describe("Approximate token ceiling. Defaults to 25000.")
612
- }),
613
- fromArgv: (argv, path) => {
614
- const at = argv.indexOf("--budget");
615
- return {
616
- bundlePath: path,
617
- ...argv[1] && argv[1] !== "--budget" ? { type: argv[1] } : {},
618
- ...at !== -1 && argv[at + 1] ? { budgetTokens: Number(argv[at + 1]) } : {}
619
- };
620
- },
621
- run: async ({ store }, { bundlePath: path, type, budgetTokens }) => {
622
- const result = await store.load(path, {
623
- ...type ? { type } : {},
624
- ...budgetTokens ? { budgetTokens } : {}
625
- });
626
- if (!result.loaded) return result;
627
- return {
628
- ...result,
629
- records: result.records.map((hit) => ({
630
- conceptId: hit.record.conceptId,
631
- title: hit.record.frontmatter.title ?? null,
632
- standing: hit.standing,
633
- supersededBy: hit.heads.map((head) => head.conceptId),
634
- warnings: hit.warnings,
635
- anchors: hit.record.frontmatter.strauss_anchors ?? [],
636
- body: hit.record.body
637
- }))
638
- };
639
- }
623
+ function argvFlag(argv, name) {
624
+ const at = argv.indexOf(name);
625
+ return at !== -1 ? argv[at + 1] : void 0;
626
+ }
627
+
628
+ // src/commands/answer.ts
629
+ var answerCommand = define({
630
+ name: "answer",
631
+ tool: "kb_answer",
632
+ usage: "answer <concept-id> <answer...>",
633
+ 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.",
634
+ input: import_zod6.z.object({ bundlePath, conceptId, answer: import_zod6.z.string().min(1) }),
635
+ fromArgv: (argv, path) => ({
636
+ bundlePath: path,
637
+ conceptId: argv[1],
638
+ answer: argv.slice(2).join(" ").trim()
640
639
  }),
641
- define({
642
- name: "query",
643
- tool: "kb_query",
644
- usage: "query <text...>",
645
- 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.",
646
- input: import_zod6.z.object({
647
- bundlePath,
648
- text: import_zod6.z.string().optional(),
649
- type: import_zod6.z.enum(KB_RECORD_TYPES).optional(),
650
- includeNonCurrent: import_zod6.z.boolean().optional()
651
- }),
652
- fromArgv: (argv, path) => ({
653
- bundlePath: path,
654
- text: argv.slice(1).join(" ").trim(),
655
- includeNonCurrent: true
656
- }),
657
- run: async ({ store }, { bundlePath: path, text, type, includeNonCurrent }) => (await store.query(path, text ?? "", {
658
- ...type ? { type } : {},
659
- includeNonCurrent: includeNonCurrent === true
660
- })).map((hit) => ({
661
- conceptId: hit.record.conceptId,
662
- title: hit.record.frontmatter.title ?? null,
663
- description: hit.record.frontmatter.description ?? null,
664
- standing: hit.standing,
665
- supersededBy: hit.heads.map((head) => head.conceptId),
666
- warnings: hit.warnings,
667
- body: hit.record.body
668
- }))
640
+ run: async ({ store, actor }, { bundlePath: path, conceptId: id, answer }) => {
641
+ await assertBaseNotFrozen(process.cwd(), path);
642
+ const record = await store.answer(path, id, answer, actor);
643
+ return { conceptId: record.conceptId };
644
+ }
645
+ });
646
+
647
+ // src/commands/context.ts
648
+ var import_zod7 = require("zod");
649
+
650
+ // src/kb-context.ts
651
+ var import_promises2 = require("fs/promises");
652
+
653
+ // src/adjudicate.ts
654
+ var STANDING = {
655
+ accepted: "current",
656
+ resolved: "current",
657
+ draft: "unsettled",
658
+ proposed: "unsettled",
659
+ open: "open",
660
+ rejected: "rejected",
661
+ superseded: "superseded"
662
+ };
663
+ function adjudicate(hits, bundle, now = /* @__PURE__ */ new Date()) {
664
+ const byId = new Map(bundle.map((record) => [record.conceptId, record]));
665
+ return hits.map((record) => {
666
+ const status = record.frontmatter.strauss_status;
667
+ const warnings = [];
668
+ let heads = [];
669
+ if (status === "superseded") {
670
+ const resolved = resolveHeads(record, byId);
671
+ heads = resolved.heads;
672
+ warnings.push(...resolved.warnings);
673
+ if (heads.length) {
674
+ warnings.push({
675
+ kind: "superseded",
676
+ by: heads.map((head) => head.conceptId)
677
+ });
678
+ }
679
+ } else if (status === "rejected") {
680
+ warnings.push({ kind: "rejected" });
681
+ } else if (status === "draft" || status === "proposed") {
682
+ warnings.push({ kind: "unsettled", status });
683
+ } else if (status === "open") {
684
+ warnings.push({ kind: "unresolved-question" });
685
+ }
686
+ const staleAfter = record.frontmatter.stale_after;
687
+ if (staleAfter && Date.parse(staleAfter) < now.getTime()) {
688
+ warnings.push({ kind: "stale", staleAfter });
689
+ }
690
+ if (!record.frontmatter.verified?.length) {
691
+ warnings.push({ kind: "unverified" });
692
+ }
693
+ return { record, standing: STANDING[status], heads, warnings };
694
+ });
695
+ }
696
+ function resolveHeads(from, byId) {
697
+ const warnings = [];
698
+ const heads = /* @__PURE__ */ new Map();
699
+ const seen = /* @__PURE__ */ new Set([from.conceptId]);
700
+ const queue = [from];
701
+ while (queue.length) {
702
+ const current = queue.shift();
703
+ const next = successors(current, byId);
704
+ for (const missing of next.missing) {
705
+ warnings.push({ kind: "broken-chain", missing });
706
+ }
707
+ if (!next.records.length) {
708
+ if (current.conceptId !== from.conceptId)
709
+ heads.set(current.conceptId, current);
710
+ continue;
711
+ }
712
+ for (const record of next.records) {
713
+ if (seen.has(record.conceptId)) {
714
+ warnings.push({ kind: "chain-cycle", through: [...seen] });
715
+ continue;
716
+ }
717
+ seen.add(record.conceptId);
718
+ queue.push(record);
719
+ }
720
+ }
721
+ if (heads.size > 1) {
722
+ warnings.push({ kind: "forked-chain", heads: [...heads.keys()] });
723
+ }
724
+ return { heads: [...heads.values()], warnings };
725
+ }
726
+ function successors(record, byId) {
727
+ const ids = /* @__PURE__ */ new Set();
728
+ const forward = record.frontmatter.strauss_superseded_by;
729
+ if (forward) ids.add(forward);
730
+ for (const [id, candidate] of byId) {
731
+ if (candidate.frontmatter.strauss_supersedes?.includes(record.conceptId)) {
732
+ ids.add(id);
733
+ }
734
+ }
735
+ const records = [];
736
+ const missing = [];
737
+ for (const id of ids) {
738
+ const found = byId.get(id);
739
+ if (found) records.push(found);
740
+ else missing.push(id);
741
+ }
742
+ return { records, missing };
743
+ }
744
+
745
+ // src/kb-index.ts
746
+ var INDEX_FILE = "INDEX.md";
747
+ var HEADING = "# KB Index";
748
+ function renderIndex(records) {
749
+ const lines = [...records].sort((left, right) => left.conceptId.localeCompare(right.conceptId)).map(renderIndexLine);
750
+ return `${HEADING}
751
+
752
+ ${lines.join("\n")}
753
+ `;
754
+ }
755
+ function renderIndexLine(record) {
756
+ const { frontmatter: fm } = record;
757
+ const parts = [fm.type, fm.strauss_status];
758
+ if (fm.tags?.length) parts.push(`tags: ${fm.tags.join(", ")}`);
759
+ if (fm.description) parts.push(fm.description);
760
+ return `- [${fm.title ?? record.conceptId}](${record.conceptId}.md) \u2014 ${parts.join(" \xB7 ")}`;
761
+ }
762
+ function indexIsStale(stored, expected) {
763
+ return stored !== expected;
764
+ }
765
+
766
+ // src/kb-context.ts
767
+ var HEADING2 = "## Knowledge bases (pinned)";
768
+ var DEFAULT_CONTEXT_BUDGET = 4e3;
769
+ var CONTEXT_PROFILES = {
770
+ "session-start": { fullUnderTokens: 1500 },
771
+ compact: { budgetTokens: 2500 },
772
+ turn: { budgetTokens: 2500 }
773
+ };
774
+ function approxTokens(text) {
775
+ return Math.ceil(text.length / 4);
776
+ }
777
+ function preamble() {
778
+ return [
779
+ HEADING2,
780
+ "",
781
+ "What follows is an index of this workspace's pinned knowledge bases \u2014",
782
+ "concept ids, titles and standing only. The record bodies are NOT in this",
783
+ "context.",
784
+ "",
785
+ "Consult records only through the strauss-kb MCP tools: `kb_load` (the",
786
+ "preferred first call), `kb_query`, and `kb_trace`, passing the",
787
+ "`bundlePath` listed with each base. Do not read record files directly:",
788
+ "a raw file read bypasses supersession resolution, and a superseded or",
789
+ "rejected record file reads exactly like a current one \u2014 only the store",
790
+ "resolves chains and standing.",
791
+ "",
792
+ "KB content loaded earlier in a long session may have been compacted",
793
+ "away. Before answering a question one of these bases governs, load it",
794
+ "again at the point of use \u2014 reloading a small base costs a few thousand",
795
+ "tokens."
796
+ ].join("\n");
797
+ }
798
+ async function renderBase(store, path, absolutePath, fullUnderTokens, pinMode, budgetTokens) {
799
+ const bundle = await store.list(absolutePath);
800
+ if (bundle.length === 0) {
801
+ return {
802
+ path,
803
+ absolutePath,
804
+ mode: "empty",
805
+ body: "No readable records yet \u2014 pinned ahead of being populated."
806
+ };
807
+ }
808
+ const fullCap = pinMode === "full" ? budgetTokens : pinMode === "index" ? 0 : fullUnderTokens;
809
+ let degradedFrom;
810
+ if (fullCap > 0) {
811
+ const full = await store.load(absolutePath, {
812
+ budgetTokens: fullCap
813
+ });
814
+ if (!full.loaded && pinMode === "full") {
815
+ degradedFrom = { approxTokens: full.approxTokens };
816
+ }
817
+ if (full.loaded) {
818
+ const records = full.records.map(
819
+ (hit) => [
820
+ `#### ${hit.record.conceptId} \u2014 ${hit.record.frontmatter.title ?? "(untitled)"} (${hit.standing})`,
821
+ "",
822
+ hit.record.body.trim()
823
+ ].join("\n")
824
+ );
825
+ const superseded2 = full.superseded.map(
826
+ (entry) => `- \`${entry.conceptId}\` \u2192 superseded by ${entry.supersededBy.map((id) => `\`${id}\``).join(", ") || "(missing replacement)"}`
827
+ );
828
+ return {
829
+ path,
830
+ absolutePath,
831
+ mode: "full",
832
+ body: [
833
+ ...records,
834
+ ...superseded2.length ? [
835
+ "#### Superseded (bodies withheld \u2014 kb_trace reaches them)",
836
+ ...superseded2
837
+ ] : []
838
+ ].join("\n\n")
839
+ };
840
+ }
841
+ }
842
+ const adjudicated = adjudicate(bundle, bundle);
843
+ const lines = adjudicated.filter((hit) => hit.standing !== "superseded").map((hit) => renderIndexLine(hit.record));
844
+ const superseded = adjudicated.filter((hit) => hit.standing === "superseded").map(
845
+ (hit) => `- \`${hit.record.conceptId}\` \u2192 superseded by ${hit.heads.map((head) => `\`${head.conceptId}\``).join(", ") || "(missing replacement)"}`
846
+ );
847
+ return {
848
+ path,
849
+ absolutePath,
850
+ mode: "index",
851
+ body: [...lines, ...superseded].join("\n"),
852
+ ...degradedFrom ? { degradedFrom } : {}
853
+ };
854
+ }
855
+ async function buildContext(store, workspaceDir, options = {}) {
856
+ const builtin = options.profile ? CONTEXT_PROFILES[options.profile] ?? {} : {};
857
+ let budgetTokens = options.budgetTokens ?? builtin.budgetTokens ?? DEFAULT_CONTEXT_BUDGET;
858
+ let fullUnderTokens = options.fullUnderTokens ?? builtin.fullUnderTokens ?? 0;
859
+ const merged = await readMergedPins(workspaceDir);
860
+ const fromManifest = mergedContextBudgets(merged, options.profile);
861
+ budgetTokens = options.budgetTokens ?? fromManifest.budgetTokens ?? builtin.budgetTokens ?? DEFAULT_CONTEXT_BUDGET;
862
+ fullUnderTokens = options.fullUnderTokens ?? fromManifest.fullUnderTokens ?? builtin.fullUnderTokens ?? 0;
863
+ const pins = merged.pins.filter(
864
+ (pin) => !pin.profiles?.length || !options.profile || pin.profiles.includes(options.profile)
865
+ );
866
+ if (pins.length === 0) {
867
+ return {
868
+ block: "",
869
+ refused: false,
870
+ approxTokens: 0,
871
+ budgetTokens,
872
+ bases: []
873
+ };
874
+ }
875
+ const sections = await Promise.all(
876
+ pins.map(async (pin) => ({
877
+ section: await renderBase(
878
+ store,
879
+ pin.path,
880
+ pin.absolutePath,
881
+ fullUnderTokens,
882
+ pin.mode,
883
+ budgetTokens
884
+ ),
885
+ frozen: pin.frozen === true
886
+ }))
887
+ );
888
+ const modeLabel = {
889
+ index: "index only \u2014 record bodies are not here",
890
+ full: "full records \u2014 this base arrives whole",
891
+ empty: "empty"
892
+ };
893
+ for (const { section } of sections) {
894
+ if (section.degradedFrom) {
895
+ options.warn?.({
896
+ operation: "kb.context.full-pin-degraded",
897
+ path: section.path,
898
+ approxTokens: section.degradedFrom.approxTokens,
899
+ budgetTokens
900
+ });
901
+ }
902
+ }
903
+ const rendered = sections.map(({ section, frozen }) => {
904
+ 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];
905
+ return [
906
+ `### ${section.path} (${label}${frozen ? " \xB7 frozen, read-only" : ""})`,
907
+ "",
908
+ `bundlePath: \`${section.absolutePath}\``,
909
+ "",
910
+ section.body
911
+ ].join("\n");
912
+ });
913
+ const block = [preamble(), "", rendered.join("\n\n"), ""].join("\n");
914
+ const bases = sections.map(({ section }) => ({
915
+ path: section.path,
916
+ absolutePath: section.absolutePath,
917
+ approxTokens: approxTokens(section.body)
918
+ }));
919
+ const total = approxTokens(block);
920
+ if (total > budgetTokens) {
921
+ options.warn?.({
922
+ operation: "kb.context.refused",
923
+ approxTokens: total,
924
+ budgetTokens,
925
+ bases: bases.map((base) => base.path)
926
+ });
927
+ const refusal = [
928
+ HEADING2,
929
+ "",
930
+ `The pinned index runs to ~${total} tokens, past the ${budgetTokens}-token`,
931
+ "budget, and was not emitted \u2014 a truncated index is indistinguishable",
932
+ "from a complete one. The pinned bases:",
933
+ "",
934
+ ...bases.map(
935
+ (base) => `- ${base.path} \u2014 ~${base.approxTokens} tokens (bundlePath: \`${base.absolutePath}\`)`
936
+ ),
937
+ "",
938
+ "For the question at hand, read what you need now \u2014 `kb_load` a base",
939
+ "(its own budget is separate), or `kb_index` for one base's shape.",
940
+ "",
941
+ "To bring this block back under budget, in order of preference:",
942
+ "- supersede or resolve stale records \u2014 the base shrinks, the knowledge keeps",
943
+ "- force a large base to index lines: `strauss-kb pin <path> --mode index`",
944
+ "- scope a pin to the profiles that need it: `strauss-kb pin <path> --profiles session-start`",
945
+ "- raise this profile's budget under `context` in .strauss/kb-pins.json",
946
+ "- unpin what no session actually needs",
947
+ ""
948
+ ].join("\n");
949
+ return {
950
+ block: refusal,
951
+ refused: true,
952
+ approxTokens: total,
953
+ budgetTokens,
954
+ bases
955
+ };
956
+ }
957
+ return { block, refused: false, approxTokens: total, budgetTokens, bases };
958
+ }
959
+ function toHookJson(block, event) {
960
+ return JSON.stringify({
961
+ hookSpecificOutput: {
962
+ hookEventName: event,
963
+ additionalContext: block
964
+ }
965
+ });
966
+ }
967
+ var CONTEXT_BEGIN = "<!-- strauss-kb:begin -->";
968
+ var CONTEXT_END = "<!-- strauss-kb:end -->";
969
+ async function syncInstructions(file, block) {
970
+ const existing = await (0, import_promises2.readFile)(file, "utf8").catch(() => null);
971
+ const region = block ? `${CONTEXT_BEGIN}
972
+ ${block.trim()}
973
+ ${CONTEXT_END}` : null;
974
+ if (existing === null) {
975
+ if (!region) return { file, action: "unchanged" };
976
+ await (0, import_promises2.writeFile)(file, `${region}
977
+ `, "utf8");
978
+ return { file, action: "created" };
979
+ }
980
+ const begin = existing.indexOf(CONTEXT_BEGIN);
981
+ const end = existing.indexOf(CONTEXT_END);
982
+ if (begin !== -1 && end !== -1 && end >= begin) {
983
+ const before = existing.slice(0, begin);
984
+ const after = existing.slice(end + CONTEXT_END.length);
985
+ const next = region ? `${before}${region}${after}` : `${before.replace(/\n+$/, "\n")}${after.replace(/^\n+/, "\n")}`;
986
+ if (next === existing) return { file, action: "unchanged" };
987
+ await (0, import_promises2.writeFile)(file, next, "utf8");
988
+ return { file, action: region ? "replaced" : "removed" };
989
+ }
990
+ if (!region) return { file, action: "unchanged" };
991
+ await (0, import_promises2.writeFile)(
992
+ file,
993
+ `${existing.replace(/\n*$/, "\n\n")}${region}
994
+ `,
995
+ "utf8"
996
+ );
997
+ return { file, action: "appended" };
998
+ }
999
+
1000
+ // src/commands/context.ts
1001
+ var contextCommand = define({
1002
+ name: "context",
1003
+ tool: "kb_context",
1004
+ usage: "context [--profile NAME] [--budget N] [--full-under N] [--format json] [--event NAME]",
1005
+ 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.",
1006
+ input: import_zod7.z.object({
1007
+ budgetTokens: import_zod7.z.number().int().positive().optional().describe(
1008
+ "Ceiling on the whole emitted block; past it the command refuses with a list of bases rather than truncating. Defaults to 4000."
1009
+ ),
1010
+ fullUnderTokens: import_zod7.z.number().int().positive().optional().describe(
1011
+ "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."
1012
+ ),
1013
+ profile: import_zod7.z.string().optional().describe(
1014
+ "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."
1015
+ ),
1016
+ format: import_zod7.z.enum(["markdown", "json"]).optional().describe(
1017
+ "CLI envelope for hook protocols that require strict JSON on stdout. MCP callers omit this \u2014 the block itself is identical."
1018
+ ),
1019
+ event: import_zod7.z.string().optional().describe(
1020
+ "hookEventName stamped into the JSON envelope. Only meaningful with format=json."
1021
+ )
669
1022
  }),
670
- define({
671
- name: "trace",
672
- tool: "kb_trace",
673
- usage: "trace <concept-id> [edges...]",
674
- 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".',
675
- input: import_zod6.z.object({
676
- bundlePath,
677
- conceptId,
678
- edges: import_zod6.z.array(import_zod6.z.enum(TRACE_EDGES)).optional(),
679
- depth: import_zod6.z.number().int().positive().optional()
680
- }),
681
- fromArgv: (argv, path) => ({
1023
+ fromArgv: (argv) => {
1024
+ const budget = argvFlag(argv, "--budget");
1025
+ const fullUnder = argvFlag(argv, "--full-under");
1026
+ const profile = argvFlag(argv, "--profile");
1027
+ const format = argvFlag(argv, "--format");
1028
+ const event = argvFlag(argv, "--event");
1029
+ return {
1030
+ ...budget ? { budgetTokens: Number(budget) } : {},
1031
+ ...fullUnder ? { fullUnderTokens: Number(fullUnder) } : {},
1032
+ ...profile ? { profile } : {},
1033
+ ...format ? { format } : {},
1034
+ ...event ? { event } : {}
1035
+ };
1036
+ },
1037
+ run: async ({ store }, { budgetTokens, fullUnderTokens, profile, format, event }) => {
1038
+ const result = await buildContext(store, process.cwd(), {
1039
+ ...budgetTokens ? { budgetTokens } : {},
1040
+ ...fullUnderTokens ? { fullUnderTokens } : {},
1041
+ ...profile ? { profile } : {},
1042
+ // Degradations — a full pin that could not fit, a refused block — go
1043
+ // to stderr as well as into the block itself: stderr is diagnostics on
1044
+ // both surfaces (hooks discard it, MCP logs it), so an operator can
1045
+ // see budget pressure without reading injected context.
1046
+ warn: (entry) => process.stderr.write(`${JSON.stringify(entry)}
1047
+ `)
1048
+ });
1049
+ if (!result.block) return "";
1050
+ return format === "json" ? toHookJson(result.block, event ?? "SessionStart") : result.block;
1051
+ }
1052
+ });
1053
+
1054
+ // src/commands/list.ts
1055
+ var import_zod8 = require("zod");
1056
+ var listCommand = define({
1057
+ name: "list",
1058
+ tool: "kb_list",
1059
+ usage: "list [type]",
1060
+ description: "Every record, optionally narrowed to one type. Use kb_query when you have a question; this is for enumerating.",
1061
+ input: import_zod8.z.object({ bundlePath, type: import_zod8.z.enum(KB_RECORD_TYPES).optional() }),
1062
+ fromArgv: (argv, path) => ({ bundlePath: path, type: argv[1] }),
1063
+ run: async ({ store }, { bundlePath: path, type }) => (await store.list(path, type)).map((record) => ({
1064
+ conceptId: record.conceptId,
1065
+ title: record.frontmatter.title ?? null,
1066
+ description: record.frontmatter.description ?? null,
1067
+ status: record.frontmatter.strauss_status,
1068
+ anchors: record.frontmatter.strauss_anchors ?? []
1069
+ }))
1070
+ });
1071
+
1072
+ // src/commands/load.ts
1073
+ var import_zod9 = require("zod");
1074
+ var loadCommand = define({
1075
+ name: "load",
1076
+ tool: "kb_load",
1077
+ usage: "load [type] [--budget N]",
1078
+ 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.",
1079
+ input: import_zod9.z.object({
1080
+ bundlePath,
1081
+ type: import_zod9.z.enum(KB_RECORD_TYPES).optional(),
1082
+ budgetTokens: import_zod9.z.number().int().positive().optional().describe("Approximate token ceiling. Defaults to 25000.")
1083
+ }),
1084
+ fromArgv: (argv, path) => {
1085
+ const budget = argvFlag(argv, "--budget");
1086
+ return {
682
1087
  bundlePath: path,
683
- conceptId: argv[1],
684
- edges: argv.slice(2).filter((edge) => TRACE_EDGES.includes(edge))
1088
+ ...argv[1] && argv[1] !== "--budget" ? { type: argv[1] } : {},
1089
+ ...budget ? { budgetTokens: Number(budget) } : {}
1090
+ };
1091
+ },
1092
+ run: async ({ store }, { bundlePath: path, type, budgetTokens }) => {
1093
+ const result = await store.load(path, {
1094
+ ...type ? { type } : {},
1095
+ ...budgetTokens ? { budgetTokens } : {}
1096
+ });
1097
+ if (!result.loaded) return result;
1098
+ return {
1099
+ ...result,
1100
+ records: result.records.map((hit) => ({
1101
+ conceptId: hit.record.conceptId,
1102
+ title: hit.record.frontmatter.title ?? null,
1103
+ standing: hit.standing,
1104
+ supersededBy: hit.heads.map((head) => head.conceptId),
1105
+ warnings: hit.warnings,
1106
+ anchors: hit.record.frontmatter.strauss_anchors ?? [],
1107
+ body: hit.record.body
1108
+ }))
1109
+ };
1110
+ }
1111
+ });
1112
+
1113
+ // src/commands/log.ts
1114
+ var import_zod10 = require("zod");
1115
+ var logCommand = define({
1116
+ name: "log",
1117
+ tool: "kb_log",
1118
+ usage: "log",
1119
+ 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.",
1120
+ input: import_zod10.z.object({ bundlePath }),
1121
+ fromArgv: (_argv, path) => ({ bundlePath: path }),
1122
+ run: ({ store }, { bundlePath: path }) => store.readLog(path)
1123
+ });
1124
+
1125
+ // src/commands/no-decision.ts
1126
+ var import_zod11 = require("zod");
1127
+ var noDecisionCommand = define({
1128
+ name: "no-decision",
1129
+ tool: "kb_no_decision",
1130
+ usage: "no-decision <reason...>",
1131
+ 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.',
1132
+ input: import_zod11.z.object({ bundlePath, reason: import_zod11.z.string().min(1) }),
1133
+ fromArgv: (argv, path) => ({
1134
+ bundlePath: path,
1135
+ reason: argv.slice(1).join(" ").trim()
1136
+ }),
1137
+ run: async ({ store, actor, now }, { bundlePath: path, reason }) => {
1138
+ await assertBaseNotFrozen(process.cwd(), path);
1139
+ const record = await store.write(
1140
+ path,
1141
+ { ...composeNoDecisionRecord(reason, actor, now()), overwrite: true },
1142
+ actor
1143
+ );
1144
+ return { conceptId: record.conceptId };
1145
+ }
1146
+ });
1147
+
1148
+ // src/commands/pin.ts
1149
+ var import_zod12 = require("zod");
1150
+ var pinCommand = define({
1151
+ name: "pin",
1152
+ tool: "kb_pin",
1153
+ usage: "pin [bundle-path] [--mode full|index] [--profiles a,b] [--local|--user] [--frozen|--unfreeze]",
1154
+ 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.",
1155
+ input: import_zod12.z.object({
1156
+ bundlePath,
1157
+ mode: import_zod12.z.enum(["full", "index"]).optional().describe(
1158
+ "full: always emit this base's records whole (still under the block budget); index: never upgrade. Absent: the profile's full-under threshold decides."
1159
+ ),
1160
+ profiles: import_zod12.z.array(import_zod12.z.string()).optional().describe("Context profiles this pin surfaces in. Absent: all of them."),
1161
+ layer: import_zod12.z.enum(["project", "local", "user"]).optional().describe(
1162
+ "Which manifest to write: project (committed, default), local (personal, gitignored), user (~/.strauss, every workspace)."
1163
+ ),
1164
+ frozen: import_zod12.z.boolean().optional().describe(
1165
+ "true: the base is concluded \u2014 writes against it refuse while pinned. false: lift a freeze."
1166
+ )
1167
+ }),
1168
+ fromArgv: (argv, path) => {
1169
+ const positional = argv[1] && !argv[1].startsWith("--") ? argv[1] : path;
1170
+ const mode = argvFlag(argv, "--mode");
1171
+ const profiles = argvFlag(argv, "--profiles");
1172
+ const layer = argv.includes("--user") ? "user" : argv.includes("--local") ? "local" : void 0;
1173
+ const frozen = argv.includes("--frozen") ? true : argv.includes("--unfreeze") ? false : void 0;
1174
+ return {
1175
+ bundlePath: positional,
1176
+ ...mode ? { mode } : {},
1177
+ ...profiles ? {
1178
+ profiles: profiles.split(",").map((p) => p.trim()).filter(Boolean)
1179
+ } : {},
1180
+ ...layer ? { layer } : {},
1181
+ ...frozen !== void 0 ? { frozen } : {}
1182
+ };
1183
+ },
1184
+ run: ({ store, now }, { bundlePath: path, mode, profiles, layer, frozen }) => pinBase(store, process.cwd(), path, now(), {
1185
+ ...mode ? { mode } : {},
1186
+ ...profiles ? { profiles } : {},
1187
+ ...layer ? { layer } : {},
1188
+ ...frozen !== void 0 ? { frozen } : {}
1189
+ })
1190
+ });
1191
+
1192
+ // src/commands/pins.ts
1193
+ var import_zod13 = require("zod");
1194
+ var pinsCommand = define({
1195
+ name: "pins",
1196
+ tool: "kb_pins",
1197
+ usage: "pins",
1198
+ 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.",
1199
+ input: import_zod13.z.object({}),
1200
+ fromArgv: () => ({}),
1201
+ run: ({ store }) => listPins(store, process.cwd())
1202
+ });
1203
+
1204
+ // src/commands/query.ts
1205
+ var import_zod14 = require("zod");
1206
+ var queryCommand = define({
1207
+ name: "query",
1208
+ tool: "kb_query",
1209
+ usage: "query <text...>",
1210
+ 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.",
1211
+ input: import_zod14.z.object({
1212
+ bundlePath,
1213
+ text: import_zod14.z.string().optional(),
1214
+ type: import_zod14.z.enum(KB_RECORD_TYPES).optional(),
1215
+ includeNonCurrent: import_zod14.z.boolean().optional()
1216
+ }),
1217
+ fromArgv: (argv, path) => ({
1218
+ bundlePath: path,
1219
+ text: argv.slice(1).join(" ").trim(),
1220
+ includeNonCurrent: true
1221
+ }),
1222
+ run: async ({ store }, { bundlePath: path, text, type, includeNonCurrent }) => (await store.query(path, text ?? "", {
1223
+ ...type ? { type } : {},
1224
+ includeNonCurrent: includeNonCurrent === true
1225
+ })).map((hit) => ({
1226
+ conceptId: hit.record.conceptId,
1227
+ title: hit.record.frontmatter.title ?? null,
1228
+ description: hit.record.frontmatter.description ?? null,
1229
+ standing: hit.standing,
1230
+ supersededBy: hit.heads.map((head) => head.conceptId),
1231
+ warnings: hit.warnings,
1232
+ body: hit.record.body
1233
+ }))
1234
+ });
1235
+
1236
+ // src/commands/read-index.ts
1237
+ var import_zod15 = require("zod");
1238
+ var readIndexCommand = define({
1239
+ name: "index",
1240
+ tool: "kb_index",
1241
+ usage: "index",
1242
+ 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.",
1243
+ input: import_zod15.z.object({ bundlePath }),
1244
+ fromArgv: (_argv, path) => ({ bundlePath: path }),
1245
+ run: ({ store }, { bundlePath: path }) => store.readIndex(path)
1246
+ });
1247
+
1248
+ // src/commands/schema.ts
1249
+ var import_zod18 = require("zod");
1250
+
1251
+ // src/json-schema.ts
1252
+ var import_zod17 = require("zod");
1253
+
1254
+ // src/kb-log.ts
1255
+ var import_zod16 = require("zod");
1256
+ var LOG_FILE = "log.jsonl";
1257
+ var kbLogEntrySchema = import_zod16.z.object({
1258
+ at: import_zod16.z.string().min(1),
1259
+ by: import_zod16.z.string().min(1),
1260
+ operation: import_zod16.z.string().min(1),
1261
+ conceptId: import_zod16.z.string().min(1),
1262
+ /** Second concept id, where the operation relates two — supersession. */
1263
+ target: import_zod16.z.string().min(1).optional()
1264
+ }).strict();
1265
+ function renderLogEntry(entry) {
1266
+ return `${JSON.stringify(kbLogEntrySchema.parse(entry))}
1267
+ `;
1268
+ }
1269
+ function parseLog(raw) {
1270
+ const entries = [];
1271
+ const malformed = [];
1272
+ raw.split("\n").forEach((text, index) => {
1273
+ if (!text.trim()) return;
1274
+ let value;
1275
+ try {
1276
+ value = JSON.parse(text);
1277
+ } catch {
1278
+ malformed.push({ line: index + 1, text });
1279
+ return;
1280
+ }
1281
+ const parsed = kbLogEntrySchema.safeParse(value);
1282
+ if (!parsed.success) {
1283
+ malformed.push({ line: index + 1, text });
1284
+ return;
1285
+ }
1286
+ entries.push(parsed.data);
1287
+ });
1288
+ return { entries, malformed };
1289
+ }
1290
+
1291
+ // src/json-schema.ts
1292
+ function kbJsonSchemas() {
1293
+ return {
1294
+ recordFrontmatter: import_zod17.z.toJSONSchema(kbRecordFrontmatterSchema, {
1295
+ io: "input"
685
1296
  }),
686
- run: async ({ store }, { bundlePath: path, conceptId: id, edges, depth }) => (await store.trace(path, id, {
687
- ...edges?.length ? { edges } : {},
688
- ...depth ? { depth } : {}
689
- })).map((step) => ({
690
- conceptId: step.record.conceptId,
691
- at: step.record.frontmatter.generated?.at ?? null,
692
- status: step.record.frontmatter.strauss_status,
693
- title: step.record.frontmatter.title ?? null,
694
- depth: step.depth,
695
- via: step.via,
696
- body: step.record.body
697
- }))
1297
+ composeInput: import_zod17.z.toJSONSchema(composeInputSchema, { io: "input" }),
1298
+ logEntry: import_zod17.z.toJSONSchema(kbLogEntrySchema, { io: "input" })
1299
+ };
1300
+ }
1301
+
1302
+ // src/commands/schema.ts
1303
+ var schemaCommand = define({
1304
+ name: "schema",
1305
+ tool: "kb_schema",
1306
+ usage: "schema",
1307
+ 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.",
1308
+ input: import_zod18.z.object({}),
1309
+ fromArgv: () => ({}),
1310
+ run: () => Promise.resolve(kbJsonSchemas())
1311
+ });
1312
+
1313
+ // src/commands/status.ts
1314
+ var import_zod19 = require("zod");
1315
+ var statusCommand = define({
1316
+ name: "status",
1317
+ tool: "kb_status",
1318
+ usage: "status <concept-id> <status>",
1319
+ 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.",
1320
+ input: import_zod19.z.object({
1321
+ bundlePath,
1322
+ conceptId,
1323
+ status: import_zod19.z.enum(KB_RECORD_STATUSES)
698
1324
  }),
699
- define({
700
- name: "list",
701
- tool: "kb_list",
702
- usage: "list [type]",
703
- description: "Every record, optionally narrowed to one type. Use kb_query when you have a question; this is for enumerating.",
704
- input: import_zod6.z.object({ bundlePath, type: import_zod6.z.enum(KB_RECORD_TYPES).optional() }),
705
- fromArgv: (argv, path) => ({ bundlePath: path, type: argv[1] }),
706
- run: async ({ store }, { bundlePath: path, type }) => (await store.list(path, type)).map((record) => ({
707
- conceptId: record.conceptId,
708
- title: record.frontmatter.title ?? null,
709
- description: record.frontmatter.description ?? null,
710
- status: record.frontmatter.strauss_status,
711
- anchors: record.frontmatter.strauss_anchors ?? []
712
- }))
1325
+ fromArgv: (argv, path) => ({
1326
+ bundlePath: path,
1327
+ conceptId: argv[1],
1328
+ status: argv[2]
713
1329
  }),
714
- define({
715
- name: "index",
716
- tool: "kb_index",
717
- usage: "index",
718
- 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.",
719
- input: import_zod6.z.object({ bundlePath }),
720
- fromArgv: (_argv, path) => ({ bundlePath: path }),
721
- run: ({ store }, { bundlePath: path }) => store.readIndex(path)
1330
+ run: async ({ store, actor }, { bundlePath: path, conceptId: id, status }) => {
1331
+ await assertBaseNotFrozen(process.cwd(), path);
1332
+ const record = await store.setStatus(path, id, status, actor);
1333
+ return { conceptId: record.conceptId, status };
1334
+ }
1335
+ });
1336
+
1337
+ // src/commands/supersede.ts
1338
+ var import_zod20 = require("zod");
1339
+ var supersedeCommand = define({
1340
+ name: "supersede",
1341
+ tool: "kb_supersede",
1342
+ usage: "supersede <concept-id> <replacement-id>",
1343
+ 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.",
1344
+ input: import_zod20.z.object({ bundlePath, conceptId, replacementId: conceptId }),
1345
+ fromArgv: (argv, path) => ({
1346
+ bundlePath: path,
1347
+ conceptId: argv[1],
1348
+ replacementId: argv[2]
722
1349
  }),
723
- define({
724
- name: "log",
725
- tool: "kb_log",
726
- usage: "log",
727
- 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.",
728
- input: import_zod6.z.object({ bundlePath }),
729
- fromArgv: (_argv, path) => ({ bundlePath: path }),
730
- run: ({ store }, { bundlePath: path }) => store.readLog(path)
1350
+ run: async ({ store, actor }, { bundlePath: path, conceptId: id, replacementId }) => {
1351
+ await assertBaseNotFrozen(process.cwd(), path);
1352
+ await store.supersede(path, id, replacementId, actor);
1353
+ return { superseded: id, replacedBy: replacementId };
1354
+ }
1355
+ });
1356
+
1357
+ // src/commands/sync-instructions.ts
1358
+ var import_zod21 = require("zod");
1359
+ var syncInstructionsCommand = define({
1360
+ name: "sync-instructions",
1361
+ usage: "sync-instructions <file> [--profile NAME] [--budget N] [--full-under N]",
1362
+ 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.",
1363
+ input: import_zod21.z.object({
1364
+ file: import_zod21.z.string().min(1).describe("The instruction file to edit in place."),
1365
+ budgetTokens: import_zod21.z.number().int().positive().optional(),
1366
+ fullUnderTokens: import_zod21.z.number().int().positive().optional(),
1367
+ profile: import_zod21.z.string().optional()
731
1368
  }),
732
- define({
733
- name: "validate",
734
- tool: "kb_validate",
735
- usage: "validate",
736
- 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.",
737
- input: import_zod6.z.object({ bundlePath }),
738
- fromArgv: (_argv, path) => ({ bundlePath: path }),
739
- run: async ({ store }, { bundlePath: path }) => validateBundle(await store.list(path)),
740
- failsWhen: (result) => Array.isArray(result) && result.length > 0
1369
+ fromArgv: (argv) => {
1370
+ const budget = argvFlag(argv, "--budget");
1371
+ const fullUnder = argvFlag(argv, "--full-under");
1372
+ const profile = argvFlag(argv, "--profile");
1373
+ return {
1374
+ file: argv[1],
1375
+ ...budget ? { budgetTokens: Number(budget) } : {},
1376
+ ...fullUnder ? { fullUnderTokens: Number(fullUnder) } : {},
1377
+ ...profile ? { profile } : {}
1378
+ };
1379
+ },
1380
+ run: async ({ store }, { file, budgetTokens, fullUnderTokens, profile }) => {
1381
+ const result = await buildContext(store, process.cwd(), {
1382
+ ...budgetTokens ? { budgetTokens } : {},
1383
+ ...fullUnderTokens ? { fullUnderTokens } : {},
1384
+ ...profile ? { profile } : {},
1385
+ warn: (entry) => process.stderr.write(`${JSON.stringify(entry)}
1386
+ `)
1387
+ });
1388
+ return syncInstructions(file, result.block);
1389
+ }
1390
+ });
1391
+
1392
+ // src/commands/trace.ts
1393
+ var import_zod22 = require("zod");
1394
+
1395
+ // src/trace.ts
1396
+ var TRACE_EDGES = ["supersession", "anchor", "source"];
1397
+ function trace(seedId, bundle, options = {}) {
1398
+ const edges = options.edges?.length ? options.edges : TRACE_EDGES;
1399
+ const maxDepth = options.depth ?? 3;
1400
+ const byId = new Map(bundle.map((record) => [record.conceptId, record]));
1401
+ const seed = byId.get(seedId);
1402
+ if (!seed) return [];
1403
+ const reached = /* @__PURE__ */ new Map([
1404
+ [seedId, { record: seed, depth: 0, via: [] }]
1405
+ ]);
1406
+ let frontier = [seed];
1407
+ for (let depth = 1; depth <= maxDepth && frontier.length; depth += 1) {
1408
+ const next = [];
1409
+ for (const from of frontier) {
1410
+ for (const edge of edges) {
1411
+ for (const record of neighbours(from, bundle, edge)) {
1412
+ const existing = reached.get(record.conceptId);
1413
+ if (existing) {
1414
+ if (existing.depth > 0 && !existing.via.includes(edge)) {
1415
+ existing.via.push(edge);
1416
+ }
1417
+ continue;
1418
+ }
1419
+ reached.set(record.conceptId, { record, depth, via: [edge] });
1420
+ next.push(record);
1421
+ }
1422
+ }
1423
+ }
1424
+ frontier = next;
1425
+ }
1426
+ return [...reached.values()].sort(byGeneratedAt);
1427
+ }
1428
+ function neighbours(from, bundle, edge) {
1429
+ switch (edge) {
1430
+ case "supersession":
1431
+ return bundle.filter(
1432
+ (candidate) => candidate.conceptId !== from.conceptId && (candidate.conceptId === from.frontmatter.strauss_superseded_by || from.frontmatter.strauss_supersedes?.includes(
1433
+ candidate.conceptId
1434
+ ) || candidate.frontmatter.strauss_superseded_by === from.conceptId || candidate.frontmatter.strauss_supersedes?.includes(from.conceptId))
1435
+ );
1436
+ // The edge that answers "why is this code shaped this way": every record
1437
+ // attached to the same file or symbol, whatever its standing.
1438
+ case "anchor": {
1439
+ const mine = from.frontmatter.strauss_anchors ?? [];
1440
+ if (!mine.length) return [];
1441
+ return bundle.filter(
1442
+ (candidate) => candidate.conceptId !== from.conceptId && (candidate.frontmatter.strauss_anchors ?? []).some(
1443
+ (theirs) => mine.some((ours) => anchorsTouch(ours, theirs))
1444
+ )
1445
+ );
1446
+ }
1447
+ case "source": {
1448
+ const mine = new Set((from.frontmatter.sources ?? []).map((s) => s.id));
1449
+ if (!mine.size) return [];
1450
+ return bundle.filter(
1451
+ (candidate) => candidate.conceptId !== from.conceptId && (candidate.frontmatter.sources ?? []).some(
1452
+ (source) => mine.has(source.id)
1453
+ )
1454
+ );
1455
+ }
1456
+ }
1457
+ }
1458
+ function anchorsTouch(left, right) {
1459
+ if (left.file !== right.file) return false;
1460
+ if (!left.symbol || !right.symbol) return true;
1461
+ return left.symbol === right.symbol;
1462
+ }
1463
+ function byGeneratedAt(left, right) {
1464
+ const at = (step) => step.record.frontmatter.generated?.at ?? "";
1465
+ return at(left).localeCompare(at(right)) || left.depth - right.depth;
1466
+ }
1467
+
1468
+ // src/commands/trace.ts
1469
+ var traceCommand = define({
1470
+ name: "trace",
1471
+ tool: "kb_trace",
1472
+ usage: "trace <concept-id> [edges...]",
1473
+ 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.',
1474
+ input: import_zod22.z.object({
1475
+ bundlePath,
1476
+ conceptId,
1477
+ edges: import_zod22.z.array(import_zod22.z.enum(TRACE_EDGES)).optional(),
1478
+ depth: import_zod22.z.number().int().positive().optional()
741
1479
  }),
742
- define({
743
- name: "schema",
744
- tool: "kb_schema",
745
- usage: "schema",
746
- 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.",
747
- input: import_zod6.z.object({}),
748
- fromArgv: () => ({}),
749
- run: () => Promise.resolve(kbJsonSchemas())
1480
+ fromArgv: (argv, path) => ({
1481
+ bundlePath: path,
1482
+ conceptId: argv[1],
1483
+ edges: argv.slice(2).filter((edge) => TRACE_EDGES.includes(edge))
750
1484
  }),
751
- define({
752
- name: "types",
753
- tool: "kb_types",
754
- usage: "types",
755
- 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.",
756
- input: import_zod6.z.object({}),
757
- fromArgv: () => ({}),
758
- run: () => Promise.resolve(RECORD_TYPES)
759
- })
1485
+ run: async ({ store }, { bundlePath: path, conceptId: id, edges, depth }) => (await store.trace(path, id, {
1486
+ ...edges?.length ? { edges } : {},
1487
+ ...depth ? { depth } : {}
1488
+ })).map((step) => ({
1489
+ conceptId: step.record.conceptId,
1490
+ at: step.record.frontmatter.generated?.at ?? null,
1491
+ status: step.record.frontmatter.strauss_status,
1492
+ title: step.record.frontmatter.title ?? null,
1493
+ depth: step.depth,
1494
+ via: step.via,
1495
+ body: step.record.body
1496
+ }))
1497
+ });
1498
+
1499
+ // src/commands/types.ts
1500
+ var import_zod23 = require("zod");
1501
+ var typesCommand = define({
1502
+ name: "types",
1503
+ tool: "kb_types",
1504
+ usage: "types",
1505
+ 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.",
1506
+ input: import_zod23.z.object({}),
1507
+ fromArgv: () => ({}),
1508
+ run: () => Promise.resolve(RECORD_TYPES)
1509
+ });
1510
+
1511
+ // src/commands/unpin.ts
1512
+ var import_zod24 = require("zod");
1513
+ var unpinCommand = define({
1514
+ name: "unpin",
1515
+ tool: "kb_unpin",
1516
+ usage: "unpin [bundle-path]",
1517
+ 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.",
1518
+ input: import_zod24.z.object({ bundlePath }),
1519
+ fromArgv: (argv, path) => ({ bundlePath: argv[1] ?? path }),
1520
+ run: (_ctx, { bundlePath: path }) => unpinBase(process.cwd(), path)
1521
+ });
1522
+
1523
+ // src/commands/validate.ts
1524
+ var import_zod25 = require("zod");
1525
+
1526
+ // src/validate.ts
1527
+ function validateBundle(records) {
1528
+ const byId = new Map(records.map((record) => [record.conceptId, record]));
1529
+ const problems = [];
1530
+ const report = (check, conceptId2, note) => problems.push({ check, conceptId: conceptId2, note });
1531
+ for (const record of records) {
1532
+ const { conceptId: conceptId2, frontmatter: fm } = record;
1533
+ if (!isKbRecordType(fm.type)) {
1534
+ report("type", conceptId2, `unrecognised type "${fm.type}"`);
1535
+ }
1536
+ if (fm.strauss_status === "superseded") {
1537
+ const by = fm.strauss_superseded_by;
1538
+ if (!by) {
1539
+ report("superseded_by", conceptId2, "superseded with no replacement");
1540
+ } else if (!byId.has(by)) {
1541
+ report("superseded_by", conceptId2, `replacement ${by} is missing`);
1542
+ } else if (!byId.get(by)?.frontmatter.strauss_supersedes?.includes(conceptId2)) {
1543
+ report("backlink", by, `does not list ${conceptId2} in supersedes`);
1544
+ }
1545
+ }
1546
+ for (const old of fm.strauss_supersedes ?? []) {
1547
+ const previous = byId.get(old);
1548
+ if (!previous) {
1549
+ report("supersedes", conceptId2, `target ${old} is missing`);
1550
+ } else if (previous.frontmatter.strauss_status !== "superseded") {
1551
+ report("supersedes", conceptId2, `${old} is not marked superseded`);
1552
+ }
1553
+ }
1554
+ if (fm.strauss_assumption && fm.sources?.length) {
1555
+ report("assumption", conceptId2, "marked an assumption but cites sources");
1556
+ }
1557
+ }
1558
+ return problems;
1559
+ }
1560
+
1561
+ // src/commands/validate.ts
1562
+ var validateCommand = define({
1563
+ name: "validate",
1564
+ tool: "kb_validate",
1565
+ usage: "validate",
1566
+ 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.",
1567
+ input: import_zod25.z.object({ bundlePath }),
1568
+ fromArgv: (_argv, path) => ({ bundlePath: path }),
1569
+ run: async ({ store }, { bundlePath: path }) => validateBundle(await store.list(path)),
1570
+ failsWhen: (result) => Array.isArray(result) && result.length > 0
1571
+ });
1572
+
1573
+ // src/commands/write.ts
1574
+ var import_zod26 = require("zod");
1575
+ var writeCommand = define({
1576
+ name: "write",
1577
+ tool: "kb_write",
1578
+ usage: "write <type> < record.json",
1579
+ description: [
1580
+ "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.",
1581
+ "",
1582
+ "Judgment the tool cannot enforce for you:",
1583
+ "- 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.",
1584
+ "- 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.",
1585
+ "- Prefer a new record over overloading an existing one, and keep each short. A record nobody finishes reading is not durable memory.",
1586
+ "- Records are never deleted; supersede instead, so the earlier reasoning stays inspectable."
1587
+ ].join("\n"),
1588
+ input: import_zod26.z.object({
1589
+ bundlePath,
1590
+ type: import_zod26.z.enum(KB_RECORD_TYPES),
1591
+ input: composeInputSchema
1592
+ }),
1593
+ fromArgv: async (argv, path, stdin) => ({
1594
+ bundlePath: path,
1595
+ type: argv[1],
1596
+ input: JSON.parse(await stdin())
1597
+ }),
1598
+ run: async ({ store, actor, now }, { bundlePath: path, type, input }) => {
1599
+ await assertBaseNotFrozen(process.cwd(), path);
1600
+ const record = await store.write(
1601
+ path,
1602
+ composeRecord(type, input, actor, now()),
1603
+ actor
1604
+ );
1605
+ return { conceptId: record.conceptId };
1606
+ }
1607
+ });
1608
+
1609
+ // src/commands/write-decision.ts
1610
+ var import_zod27 = require("zod");
1611
+ var writeDecisionCommand = define({
1612
+ name: "write-decision",
1613
+ tool: "kb_write_decision",
1614
+ usage: "write-decision < decision.json",
1615
+ description: [
1616
+ "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.",
1617
+ "",
1618
+ "What belongs in one:",
1619
+ '- 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.',
1620
+ "- `alternative` is what you turned down and why, not a list of everything considered.",
1621
+ "- A reference to material you read goes in `sources`; a reference to code goes in `anchors`; a reference to another record goes in `relatedConceptIds`."
1622
+ ].join("\n"),
1623
+ input: import_zod27.z.object({ bundlePath, input: decisionInputSchema }),
1624
+ fromArgv: async (_argv, path, stdin) => ({
1625
+ bundlePath: path,
1626
+ input: JSON.parse(await stdin())
1627
+ }),
1628
+ run: async ({ store, actor, now }, { bundlePath: path, input }) => {
1629
+ await assertBaseNotFrozen(process.cwd(), path);
1630
+ const record = await store.write(
1631
+ path,
1632
+ composeDecisionRecord(input, actor, now()),
1633
+ actor
1634
+ );
1635
+ return { conceptId: record.conceptId };
1636
+ }
1637
+ });
1638
+
1639
+ // src/commands/index.ts
1640
+ var KB_COMMANDS = [
1641
+ writeCommand,
1642
+ writeDecisionCommand,
1643
+ noDecisionCommand,
1644
+ statusCommand,
1645
+ supersedeCommand,
1646
+ answerCommand,
1647
+ loadCommand,
1648
+ queryCommand,
1649
+ traceCommand,
1650
+ listCommand,
1651
+ readIndexCommand,
1652
+ logCommand,
1653
+ validateCommand,
1654
+ schemaCommand,
1655
+ pinCommand,
1656
+ unpinCommand,
1657
+ pinsCommand,
1658
+ contextCommand,
1659
+ syncInstructionsCommand,
1660
+ typesCommand
760
1661
  ];
761
1662
  var KB_COMMANDS_BY_NAME = new Map(
762
1663
  KB_COMMANDS.map((command) => [command.name, command])
@@ -764,8 +1665,8 @@ var KB_COMMANDS_BY_NAME = new Map(
764
1665
 
765
1666
  // src/kb-store.ts
766
1667
  var import_node_crypto = require("crypto");
767
- var import_promises2 = require("fs/promises");
768
- var import_node_path2 = require("path");
1668
+ var import_promises4 = require("fs/promises");
1669
+ var import_node_path6 = require("path");
769
1670
 
770
1671
  // src/markdown.ts
771
1672
  var import_gray_matter = __toESM(require("gray-matter"), 1);
@@ -872,121 +1773,9 @@ var KbInvalidConceptIdError = class extends BaseError {
872
1773
  }
873
1774
  };
874
1775
 
875
- // src/kb-index.ts
876
- var INDEX_FILE = "INDEX.md";
877
- var HEADING = "# KB Index";
878
- function renderIndex(records) {
879
- const lines = [...records].sort((left, right) => left.conceptId.localeCompare(right.conceptId)).map((record) => {
880
- const { frontmatter: fm } = record;
881
- const parts = [fm.type, fm.strauss_status];
882
- if (fm.tags?.length) parts.push(`tags: ${fm.tags.join(", ")}`);
883
- if (fm.description) parts.push(fm.description);
884
- return `- [${fm.title ?? record.conceptId}](${record.conceptId}.md) \u2014 ${parts.join(" \xB7 ")}`;
885
- });
886
- return `${HEADING}
887
-
888
- ${lines.join("\n")}
889
- `;
890
- }
891
- function indexIsStale(stored, expected) {
892
- return stored !== expected;
893
- }
894
-
895
- // src/adjudicate.ts
896
- var STANDING = {
897
- accepted: "current",
898
- resolved: "current",
899
- draft: "unsettled",
900
- proposed: "unsettled",
901
- open: "open",
902
- rejected: "rejected",
903
- superseded: "superseded"
904
- };
905
- function adjudicate(hits, bundle, now = /* @__PURE__ */ new Date()) {
906
- const byId = new Map(bundle.map((record) => [record.conceptId, record]));
907
- return hits.map((record) => {
908
- const status = record.frontmatter.strauss_status;
909
- const warnings = [];
910
- let heads = [];
911
- if (status === "superseded") {
912
- const resolved = resolveHeads(record, byId);
913
- heads = resolved.heads;
914
- warnings.push(...resolved.warnings);
915
- if (heads.length) {
916
- warnings.push({
917
- kind: "superseded",
918
- by: heads.map((head) => head.conceptId)
919
- });
920
- }
921
- } else if (status === "rejected") {
922
- warnings.push({ kind: "rejected" });
923
- } else if (status === "draft" || status === "proposed") {
924
- warnings.push({ kind: "unsettled", status });
925
- } else if (status === "open") {
926
- warnings.push({ kind: "unresolved-question" });
927
- }
928
- const staleAfter = record.frontmatter.stale_after;
929
- if (staleAfter && Date.parse(staleAfter) < now.getTime()) {
930
- warnings.push({ kind: "stale", staleAfter });
931
- }
932
- if (!record.frontmatter.verified?.length) {
933
- warnings.push({ kind: "unverified" });
934
- }
935
- return { record, standing: STANDING[status], heads, warnings };
936
- });
937
- }
938
- function resolveHeads(from, byId) {
939
- const warnings = [];
940
- const heads = /* @__PURE__ */ new Map();
941
- const seen = /* @__PURE__ */ new Set([from.conceptId]);
942
- const queue = [from];
943
- while (queue.length) {
944
- const current = queue.shift();
945
- const next = successors(current, byId);
946
- for (const missing of next.missing) {
947
- warnings.push({ kind: "broken-chain", missing });
948
- }
949
- if (!next.records.length) {
950
- if (current.conceptId !== from.conceptId)
951
- heads.set(current.conceptId, current);
952
- continue;
953
- }
954
- for (const record of next.records) {
955
- if (seen.has(record.conceptId)) {
956
- warnings.push({ kind: "chain-cycle", through: [...seen] });
957
- continue;
958
- }
959
- seen.add(record.conceptId);
960
- queue.push(record);
961
- }
962
- }
963
- if (heads.size > 1) {
964
- warnings.push({ kind: "forked-chain", heads: [...heads.keys()] });
965
- }
966
- return { heads: [...heads.values()], warnings };
967
- }
968
- function successors(record, byId) {
969
- const ids = /* @__PURE__ */ new Set();
970
- const forward = record.frontmatter.strauss_superseded_by;
971
- if (forward) ids.add(forward);
972
- for (const [id, candidate] of byId) {
973
- if (candidate.frontmatter.strauss_supersedes?.includes(record.conceptId)) {
974
- ids.add(id);
975
- }
976
- }
977
- const records = [];
978
- const missing = [];
979
- for (const id of ids) {
980
- const found = byId.get(id);
981
- if (found) records.push(found);
982
- else missing.push(id);
983
- }
984
- return { records, missing };
985
- }
986
-
987
1776
  // src/search-index.ts
988
- var import_promises = require("fs/promises");
989
- var import_node_path = require("path");
1777
+ var import_promises3 = require("fs/promises");
1778
+ var import_node_path5 = require("path");
990
1779
  var SEARCH_INDEX_FILE = ".index.sqlite";
991
1780
  var COLLECTION = "kb";
992
1781
  async function searchBase(bundlePath2, query, options = {}) {
@@ -995,7 +1784,7 @@ async function searchBase(bundlePath2, query, options = {}) {
995
1784
  let store = null;
996
1785
  try {
997
1786
  store = await qmd.createStore({
998
- dbPath: (0, import_node_path.join)(bundlePath2, SEARCH_INDEX_FILE),
1787
+ dbPath: (0, import_node_path5.join)(bundlePath2, SEARCH_INDEX_FILE),
999
1788
  config: {
1000
1789
  collections: {
1001
1790
  [COLLECTION]: {
@@ -1030,13 +1819,13 @@ async function searchBase(bundlePath2, query, options = {}) {
1030
1819
  }
1031
1820
  }
1032
1821
  async function isStale(bundlePath2) {
1033
- const indexAt = await (0, import_promises.stat)((0, import_node_path.join)(bundlePath2, SEARCH_INDEX_FILE)).then((s) => s.mtimeMs).catch(() => 0);
1822
+ const indexAt = await (0, import_promises3.stat)((0, import_node_path5.join)(bundlePath2, SEARCH_INDEX_FILE)).then((s) => s.mtimeMs).catch(() => 0);
1034
1823
  if (!indexAt) return true;
1035
1824
  const { readdir: readdir2 } = await import("fs/promises");
1036
1825
  const names = await readdir2(bundlePath2).catch(() => []);
1037
1826
  for (const name of names) {
1038
1827
  if (!name.endsWith(".md") || name === INDEX_FILE) continue;
1039
- const at = await (0, import_promises.stat)((0, import_node_path.join)(bundlePath2, name)).then((s) => s.mtimeMs).catch(() => 0);
1828
+ const at = await (0, import_promises3.stat)((0, import_node_path5.join)(bundlePath2, name)).then((s) => s.mtimeMs).catch(() => 0);
1040
1829
  if (at > indexAt) return true;
1041
1830
  }
1042
1831
  return false;
@@ -1071,7 +1860,7 @@ async function loadQmd(logger) {
1071
1860
  }
1072
1861
 
1073
1862
  // src/kb-store.ts
1074
- var KB_DIR = (0, import_node_path2.join)(".strauss", "kb");
1863
+ var KB_DIR = (0, import_node_path6.join)(".strauss", "kb");
1075
1864
  var STORE_OWNED = /* @__PURE__ */ new Set([INDEX_FILE, LOG_FILE, SEARCH_INDEX_FILE]);
1076
1865
  var DEFAULT_LOAD_BUDGET = 25e3;
1077
1866
  var KbStore = class {
@@ -1102,7 +1891,7 @@ var KbStore = class {
1102
1891
  const conceptId2 = `${input.type}.${input.slug}`;
1103
1892
  const root = this.root(bundlePath2);
1104
1893
  const target = this.recordPath(bundlePath2, conceptId2);
1105
- await (0, import_promises2.mkdir)(root, { recursive: true });
1894
+ await (0, import_promises4.mkdir)(root, { recursive: true });
1106
1895
  await this.publish(
1107
1896
  target,
1108
1897
  stringifyMarkdownWithFrontmatter(input.body, frontmatter),
@@ -1127,7 +1916,7 @@ var KbStore = class {
1127
1916
  const target = this.recordPath(bundlePath2, conceptId2);
1128
1917
  let raw;
1129
1918
  try {
1130
- raw = await (0, import_promises2.readFile)(target, "utf8");
1919
+ raw = await (0, import_promises4.readFile)(target, "utf8");
1131
1920
  } catch {
1132
1921
  return null;
1133
1922
  }
@@ -1144,14 +1933,14 @@ var KbStore = class {
1144
1933
  const root = this.root(bundlePath2);
1145
1934
  let names;
1146
1935
  try {
1147
- names = await (0, import_promises2.readdir)(root);
1936
+ names = await (0, import_promises4.readdir)(root);
1148
1937
  } catch {
1149
1938
  return [];
1150
1939
  }
1151
1940
  const wanted = names.sort().filter((name) => name.endsWith(".md") && !STORE_OWNED.has(name)).map((name) => ({ name, conceptId: name.slice(0, -".md".length) })).filter(({ conceptId: conceptId2 }) => !type || conceptId2.startsWith(`${type}.`));
1152
1941
  const records = await Promise.all(
1153
1942
  wanted.map(
1154
- async ({ name, conceptId: conceptId2 }) => this.parse(conceptId2, await (0, import_promises2.readFile)((0, import_node_path2.join)(root, name), "utf8"))
1943
+ async ({ name, conceptId: conceptId2 }) => this.parse(conceptId2, await (0, import_promises4.readFile)((0, import_node_path6.join)(root, name), "utf8"))
1155
1944
  )
1156
1945
  );
1157
1946
  return records.filter((record) => record !== null);
@@ -1289,19 +2078,19 @@ ${answer}
1289
2078
  const adjudicated = adjudicate(wanted, bundle);
1290
2079
  const records = adjudicated.filter((hit) => hit.standing !== "superseded");
1291
2080
  const superseded = adjudicated.filter((hit) => hit.standing === "superseded").map(stub);
1292
- const approxTokens = records.reduce((total, hit) => total + estimateTokens(hit.record), 0) + superseded.reduce((total, entry) => total + estimateStubTokens(entry), 0);
1293
- if (approxTokens > budgetTokens) {
2081
+ const approxTokens2 = records.reduce((total, hit) => total + estimateTokens(hit.record), 0) + superseded.reduce((total, entry) => total + estimateStubTokens(entry), 0);
2082
+ if (approxTokens2 > budgetTokens) {
1294
2083
  return {
1295
2084
  loaded: false,
1296
2085
  recordCount: wanted.length,
1297
- approxTokens,
2086
+ approxTokens: approxTokens2,
1298
2087
  budgetTokens
1299
2088
  };
1300
2089
  }
1301
2090
  return {
1302
2091
  loaded: true,
1303
2092
  recordCount: wanted.length,
1304
- approxTokens,
2093
+ approxTokens: approxTokens2,
1305
2094
  budgetTokens,
1306
2095
  records,
1307
2096
  superseded
@@ -1321,11 +2110,11 @@ ${answer}
1321
2110
  async readIndex(bundlePath2) {
1322
2111
  const root = this.root(bundlePath2);
1323
2112
  const expected = renderIndex(await this.list(bundlePath2));
1324
- const stored = await (0, import_promises2.readFile)((0, import_node_path2.join)(root, INDEX_FILE), "utf8").catch(
2113
+ const stored = await (0, import_promises4.readFile)((0, import_node_path6.join)(root, INDEX_FILE), "utf8").catch(
1325
2114
  () => null
1326
2115
  );
1327
2116
  if (indexIsStale(stored, expected)) {
1328
- await this.publish((0, import_node_path2.join)(root, INDEX_FILE), expected, true, INDEX_FILE);
2117
+ await this.publish((0, import_node_path6.join)(root, INDEX_FILE), expected, true, INDEX_FILE);
1329
2118
  this.logger.info?.({
1330
2119
  operation: "kb.index.repair",
1331
2120
  bundlePath: root,
@@ -1342,8 +2131,8 @@ ${answer}
1342
2131
  * knows which agent touched what. So a bad line is surfaced and left alone.
1343
2132
  */
1344
2133
  async readLog(bundlePath2) {
1345
- const raw = await (0, import_promises2.readFile)(
1346
- (0, import_node_path2.join)(this.root(bundlePath2), LOG_FILE),
2134
+ const raw = await (0, import_promises4.readFile)(
2135
+ (0, import_node_path6.join)(this.root(bundlePath2), LOG_FILE),
1347
2136
  "utf8"
1348
2137
  ).catch(() => "");
1349
2138
  const result = parseLog(raw);
@@ -1358,14 +2147,14 @@ ${answer}
1358
2147
  }
1359
2148
  async mutate(bundlePath2, conceptId2, change, entry, changeBody = (body) => body) {
1360
2149
  const target = this.recordPath(bundlePath2, conceptId2);
1361
- const before = await (0, import_promises2.readFile)(target, "utf8").catch(() => null);
2150
+ const before = await (0, import_promises4.readFile)(target, "utf8").catch(() => null);
1362
2151
  if (before === null) throw new KbRecordNotFoundError(conceptId2);
1363
2152
  const parsed = this.parse(conceptId2, before);
1364
2153
  if (!parsed) throw new KbRecordNotFoundError(conceptId2);
1365
2154
  const frontmatter = change(parsed.frontmatter);
1366
2155
  const body = changeBody(parsed.body);
1367
2156
  const contents = stringifyMarkdownWithFrontmatter(body, frontmatter);
1368
- const witness = await (0, import_promises2.readFile)(target, "utf8").catch(() => null);
2157
+ const witness = await (0, import_promises4.readFile)(target, "utf8").catch(() => null);
1369
2158
  if (witness === null || digest(witness) !== digest(before)) {
1370
2159
  throw new KbWriteConflictError(conceptId2);
1371
2160
  }
@@ -1391,26 +2180,26 @@ ${answer}
1391
2180
  */
1392
2181
  async publish(target, contents, overwrite, conceptId2) {
1393
2182
  const staging = `${target}.${process.pid}.tmp`;
1394
- await (0, import_promises2.writeFile)(staging, contents, "utf8");
2183
+ await (0, import_promises4.writeFile)(staging, contents, "utf8");
1395
2184
  try {
1396
2185
  if (overwrite) {
1397
- await (0, import_promises2.rename)(staging, target);
2186
+ await (0, import_promises4.rename)(staging, target);
1398
2187
  return;
1399
2188
  }
1400
- await (0, import_promises2.link)(staging, target);
2189
+ await (0, import_promises4.link)(staging, target);
1401
2190
  } catch (error) {
1402
2191
  if (error.code === "EEXIST") {
1403
2192
  throw new KbRecordAlreadyExistsError(conceptId2);
1404
2193
  }
1405
2194
  throw error;
1406
2195
  } finally {
1407
- await (0, import_promises2.unlink)(staging).catch(() => void 0);
2196
+ await (0, import_promises4.unlink)(staging).catch(() => void 0);
1408
2197
  }
1409
2198
  }
1410
2199
  /** Appends one log line. Failing to log must not fail the mutation. */
1411
2200
  async record(root, entry) {
1412
2201
  const line = renderLogEntry({ at: (/* @__PURE__ */ new Date()).toISOString(), ...entry });
1413
- await (0, import_promises2.appendFile)((0, import_node_path2.join)(root, LOG_FILE), line, "utf8").catch((error) => {
2202
+ await (0, import_promises4.appendFile)((0, import_node_path6.join)(root, LOG_FILE), line, "utf8").catch((error) => {
1414
2203
  this.logger.warn?.({
1415
2204
  operation: "kb.log.append",
1416
2205
  outcome: "failed",
@@ -1436,18 +2225,18 @@ ${answer}
1436
2225
  };
1437
2226
  }
1438
2227
  root(bundlePath2) {
1439
- return (0, import_node_path2.resolve)(bundlePath2);
2228
+ return (0, import_node_path6.resolve)(bundlePath2);
1440
2229
  }
1441
2230
  // Concept ids are `<type>.<slug>` and map to a single file directly under the
1442
2231
  // bundle root; anything carrying a separator would escape it.
1443
2232
  recordPath(bundlePath2, conceptId2) {
1444
- if (conceptId2.includes(import_node_path2.sep) || conceptId2.includes("/")) {
2233
+ if (conceptId2.includes(import_node_path6.sep) || conceptId2.includes("/")) {
1445
2234
  throw new KbInvalidConceptIdError(
1446
2235
  "concept id must not contain a path separator",
1447
2236
  { conceptId: conceptId2 }
1448
2237
  );
1449
2238
  }
1450
- return (0, import_node_path2.join)(this.root(bundlePath2), `${conceptId2}.md`);
2239
+ return (0, import_node_path6.join)(this.root(bundlePath2), `${conceptId2}.md`);
1451
2240
  }
1452
2241
  };
1453
2242
  function estimateTokens(record) {
@@ -1489,6 +2278,7 @@ function createKbMcpServer() {
1489
2278
  now: () => (/* @__PURE__ */ new Date()).toISOString()
1490
2279
  };
1491
2280
  for (const command of KB_COMMANDS) {
2281
+ if (!command.tool) continue;
1492
2282
  server.registerTool(
1493
2283
  command.tool,
1494
2284
  { description: command.description, inputSchema: command.input.shape },