@saasontools/strauss-kb 0.1.2 → 0.1.4

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,12 +199,22 @@ 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. */
205
215
  relatedConceptIds: import_zod2.z.array(kbConceptIdSchema).optional(),
206
216
  /** Concept ids this record replaces. The store settles the backlinks. */
207
- supersedes: import_zod2.z.array(kbConceptIdSchema).optional(),
217
+ supersedes: import_zod2.z.array(kbConceptIdSchema).max(32).optional(),
208
218
  materiality: import_zod2.z.enum(KB_MATERIALITIES).optional(),
209
219
  confidence: import_zod2.z.enum(KB_CONFIDENCES).optional(),
210
220
  owner: import_zod2.z.string().min(1).optional()
@@ -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,19 +315,952 @@ function composeNoDecisionRecord(reason, writtenBy, writtenAt) {
305
315
  );
306
316
  }
307
317
 
318
+ // src/commands/answer.ts
319
+ var import_zod6 = require("zod");
320
+
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");
379
+ var import_zod4 = require("zod");
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)();
429
+ }
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;
484
+ try {
485
+ manifest = await readPinsLayer(workspaceDir, layer);
486
+ } catch {
487
+ continue;
488
+ }
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 });
496
+ }
497
+ }
498
+ return { pins, manifests };
499
+ }
500
+
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
+ }
509
+ }
510
+
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
+ );
530
+ }
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
555
+ )
556
+ });
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
+ };
568
+ }
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
+ };
586
+ }
587
+
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;
599
+ }
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);
607
+ }
608
+ }
609
+ return {
610
+ path: storablePath((0, import_node_path4.resolve)(workspaceDir), bundlePath2),
611
+ removed: layers.length > 0,
612
+ layers
613
+ };
614
+ }
615
+
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");
620
+ function define(command) {
621
+ return command;
622
+ }
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()
639
+ }),
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
+ )
1022
+ }),
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 {
1087
+ bundlePath: path,
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
+
308
1251
  // src/json-schema.ts
309
- var import_zod5 = require("zod");
1252
+ var import_zod17 = require("zod");
310
1253
 
311
1254
  // src/kb-log.ts
312
- var import_zod4 = require("zod");
1255
+ var import_zod16 = require("zod");
313
1256
  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),
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),
319
1262
  /** Second concept id, where the operation relates two — supersession. */
320
- target: import_zod4.z.string().min(1).optional()
1263
+ target: import_zod16.z.string().min(1).optional()
321
1264
  }).strict();
322
1265
  function renderLogEntry(entry) {
323
1266
  return `${JSON.stringify(kbLogEntrySchema.parse(entry))}
@@ -348,14 +1291,107 @@ function parseLog(raw) {
348
1291
  // src/json-schema.ts
349
1292
  function kbJsonSchemas() {
350
1293
  return {
351
- recordFrontmatter: import_zod5.z.toJSONSchema(kbRecordFrontmatterSchema, {
1294
+ recordFrontmatter: import_zod17.z.toJSONSchema(kbRecordFrontmatterSchema, {
352
1295
  io: "input"
353
1296
  }),
354
- composeInput: import_zod5.z.toJSONSchema(composeInputSchema, { io: "input" }),
355
- logEntry: import_zod5.z.toJSONSchema(kbLogEntrySchema, { io: "input" })
1297
+ composeInput: import_zod17.z.toJSONSchema(composeInputSchema, { io: "input" }),
1298
+ logEntry: import_zod17.z.toJSONSchema(kbLogEntrySchema, { io: "input" })
356
1299
  };
357
1300
  }
358
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)
1324
+ }),
1325
+ fromArgv: (argv, path) => ({
1326
+ bundlePath: path,
1327
+ conceptId: argv[1],
1328
+ status: argv[2]
1329
+ }),
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]
1349
+ }),
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()
1368
+ }),
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
+
359
1395
  // src/trace.ts
360
1396
  var TRACE_EDGES = ["supersession", "anchor", "source"];
361
1397
  function trace(seedId, bundle, options = {}) {
@@ -429,6 +1465,64 @@ function byGeneratedAt(left, right) {
429
1465
  return at(left).localeCompare(at(right)) || left.depth - right.depth;
430
1466
  }
431
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()
1479
+ }),
1480
+ fromArgv: (argv, path) => ({
1481
+ bundlePath: path,
1482
+ conceptId: argv[1],
1483
+ edges: argv.slice(2).filter((edge) => TRACE_EDGES.includes(edge))
1484
+ }),
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
+
432
1526
  // src/validate.ts
433
1527
  function validateBundle(records) {
434
1528
  const byId = new Map(records.map((record) => [record.conceptId, record]));
@@ -464,299 +1558,114 @@ function validateBundle(records) {
464
1558
  return problems;
465
1559
  }
466
1560
 
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");
470
- function define(command) {
471
- return command;
472
- }
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
- }
640
- }),
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
- }))
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
669
1592
  }),
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) => ({
682
- bundlePath: path,
683
- conceptId: argv[1],
684
- edges: argv.slice(2).filter((edge) => TRACE_EDGES.includes(edge))
685
- }),
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
- }))
1593
+ fromArgv: async (argv, path, stdin) => ({
1594
+ bundlePath: path,
1595
+ type: argv[1],
1596
+ input: JSON.parse(await stdin())
698
1597
  }),
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) => ({
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 {
707
1606
  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
- }))
713
- }),
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)
722
- }),
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)
731
- }),
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
741
- }),
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())
1607
+ action: record.action,
1608
+ supersededIds: record.supersededIds
1609
+ };
1610
+ }
1611
+ });
1612
+
1613
+ // src/commands/write-decision.ts
1614
+ var import_zod27 = require("zod");
1615
+ var writeDecisionCommand = define({
1616
+ name: "write-decision",
1617
+ tool: "kb_write_decision",
1618
+ usage: "write-decision < decision.json",
1619
+ description: [
1620
+ "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.",
1621
+ "",
1622
+ "What belongs in one:",
1623
+ '- 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.',
1624
+ "- `alternative` is what you turned down and why, not a list of everything considered.",
1625
+ "- A reference to material you read goes in `sources`; a reference to code goes in `anchors`; a reference to another record goes in `relatedConceptIds`."
1626
+ ].join("\n"),
1627
+ input: import_zod27.z.object({ bundlePath, input: decisionInputSchema }),
1628
+ fromArgv: async (_argv, path, stdin) => ({
1629
+ bundlePath: path,
1630
+ input: JSON.parse(await stdin())
750
1631
  }),
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
- })
1632
+ run: async ({ store, actor, now }, { bundlePath: path, input }) => {
1633
+ await assertBaseNotFrozen(process.cwd(), path);
1634
+ const record = await store.write(
1635
+ path,
1636
+ composeDecisionRecord(input, actor, now()),
1637
+ actor
1638
+ );
1639
+ return {
1640
+ conceptId: record.conceptId,
1641
+ action: record.action,
1642
+ supersededIds: record.supersededIds
1643
+ };
1644
+ }
1645
+ });
1646
+
1647
+ // src/commands/index.ts
1648
+ var KB_COMMANDS = [
1649
+ writeCommand,
1650
+ writeDecisionCommand,
1651
+ noDecisionCommand,
1652
+ statusCommand,
1653
+ supersedeCommand,
1654
+ answerCommand,
1655
+ loadCommand,
1656
+ queryCommand,
1657
+ traceCommand,
1658
+ listCommand,
1659
+ readIndexCommand,
1660
+ logCommand,
1661
+ validateCommand,
1662
+ schemaCommand,
1663
+ pinCommand,
1664
+ unpinCommand,
1665
+ pinsCommand,
1666
+ contextCommand,
1667
+ syncInstructionsCommand,
1668
+ typesCommand
760
1669
  ];
761
1670
  var KB_COMMANDS_BY_NAME = new Map(
762
1671
  KB_COMMANDS.map((command) => [command.name, command])
@@ -764,8 +1673,8 @@ var KB_COMMANDS_BY_NAME = new Map(
764
1673
 
765
1674
  // src/kb-store.ts
766
1675
  var import_node_crypto = require("crypto");
767
- var import_promises2 = require("fs/promises");
768
- var import_node_path2 = require("path");
1676
+ var import_promises4 = require("fs/promises");
1677
+ var import_node_path6 = require("path");
769
1678
 
770
1679
  // src/markdown.ts
771
1680
  var import_gray_matter = __toESM(require("gray-matter"), 1);
@@ -822,7 +1731,7 @@ var KbRecordAlreadyExistsError = class extends BaseError {
822
1731
  fault: "User" /* User */,
823
1732
  retriable: false,
824
1733
  reportToUser: true,
825
- details: { conceptId: conceptId2 }
1734
+ details: { conceptId: conceptId2, action: "refused" }
826
1735
  });
827
1736
  this.conceptId = conceptId2;
828
1737
  }
@@ -872,121 +1781,9 @@ var KbInvalidConceptIdError = class extends BaseError {
872
1781
  }
873
1782
  };
874
1783
 
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
1784
  // src/search-index.ts
988
- var import_promises = require("fs/promises");
989
- var import_node_path = require("path");
1785
+ var import_promises3 = require("fs/promises");
1786
+ var import_node_path5 = require("path");
990
1787
  var SEARCH_INDEX_FILE = ".index.sqlite";
991
1788
  var COLLECTION = "kb";
992
1789
  async function searchBase(bundlePath2, query, options = {}) {
@@ -995,7 +1792,7 @@ async function searchBase(bundlePath2, query, options = {}) {
995
1792
  let store = null;
996
1793
  try {
997
1794
  store = await qmd.createStore({
998
- dbPath: (0, import_node_path.join)(bundlePath2, SEARCH_INDEX_FILE),
1795
+ dbPath: (0, import_node_path5.join)(bundlePath2, SEARCH_INDEX_FILE),
999
1796
  config: {
1000
1797
  collections: {
1001
1798
  [COLLECTION]: {
@@ -1030,13 +1827,13 @@ async function searchBase(bundlePath2, query, options = {}) {
1030
1827
  }
1031
1828
  }
1032
1829
  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);
1830
+ const indexAt = await (0, import_promises3.stat)((0, import_node_path5.join)(bundlePath2, SEARCH_INDEX_FILE)).then((s) => s.mtimeMs).catch(() => 0);
1034
1831
  if (!indexAt) return true;
1035
1832
  const { readdir: readdir2 } = await import("fs/promises");
1036
1833
  const names = await readdir2(bundlePath2).catch(() => []);
1037
1834
  for (const name of names) {
1038
1835
  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);
1836
+ const at = await (0, import_promises3.stat)((0, import_node_path5.join)(bundlePath2, name)).then((s) => s.mtimeMs).catch(() => 0);
1040
1837
  if (at > indexAt) return true;
1041
1838
  }
1042
1839
  return false;
@@ -1071,7 +1868,7 @@ async function loadQmd(logger) {
1071
1868
  }
1072
1869
 
1073
1870
  // src/kb-store.ts
1074
- var KB_DIR = (0, import_node_path2.join)(".strauss", "kb");
1871
+ var KB_DIR = (0, import_node_path6.join)(".strauss", "kb");
1075
1872
  var STORE_OWNED = /* @__PURE__ */ new Set([INDEX_FILE, LOG_FILE, SEARCH_INDEX_FILE]);
1076
1873
  var DEFAULT_LOAD_BUDGET = 25e3;
1077
1874
  var KbStore = class {
@@ -1102,7 +1899,7 @@ var KbStore = class {
1102
1899
  const conceptId2 = `${input.type}.${input.slug}`;
1103
1900
  const root = this.root(bundlePath2);
1104
1901
  const target = this.recordPath(bundlePath2, conceptId2);
1105
- await (0, import_promises2.mkdir)(root, { recursive: true });
1902
+ await (0, import_promises4.mkdir)(root, { recursive: true });
1106
1903
  await this.publish(
1107
1904
  target,
1108
1905
  stringifyMarkdownWithFrontmatter(input.body, frontmatter),
@@ -1114,20 +1911,34 @@ var KbStore = class {
1114
1911
  conceptId: conceptId2,
1115
1912
  by: actor
1116
1913
  });
1914
+ const targets = new Set(frontmatter.strauss_supersedes ?? []);
1915
+ targets.delete(conceptId2);
1916
+ const supersededIds = [];
1917
+ for (const old of targets) {
1918
+ if (await this.markSupersededRetrying(bundlePath2, old, conceptId2, actor)) {
1919
+ supersededIds.push(old);
1920
+ }
1921
+ }
1117
1922
  this.logger.info?.({
1118
1923
  operation: "kb.write",
1119
1924
  bundlePath: root,
1120
1925
  conceptId: conceptId2,
1121
1926
  anchors: frontmatter.strauss_anchors?.length ?? 0
1122
1927
  });
1123
- return { conceptId: conceptId2, frontmatter, body: input.body };
1928
+ return {
1929
+ conceptId: conceptId2,
1930
+ frontmatter,
1931
+ body: input.body,
1932
+ action: supersededIds.length ? "superseded-prior" : "created",
1933
+ supersededIds
1934
+ };
1124
1935
  }
1125
1936
  /** One record by concept id, or null when it does not exist. */
1126
1937
  async read(bundlePath2, conceptId2) {
1127
1938
  const target = this.recordPath(bundlePath2, conceptId2);
1128
1939
  let raw;
1129
1940
  try {
1130
- raw = await (0, import_promises2.readFile)(target, "utf8");
1941
+ raw = await (0, import_promises4.readFile)(target, "utf8");
1131
1942
  } catch {
1132
1943
  return null;
1133
1944
  }
@@ -1144,14 +1955,14 @@ var KbStore = class {
1144
1955
  const root = this.root(bundlePath2);
1145
1956
  let names;
1146
1957
  try {
1147
- names = await (0, import_promises2.readdir)(root);
1958
+ names = await (0, import_promises4.readdir)(root);
1148
1959
  } catch {
1149
1960
  return [];
1150
1961
  }
1151
1962
  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
1963
  const records = await Promise.all(
1153
1964
  wanted.map(
1154
- async ({ name, conceptId: conceptId2 }) => this.parse(conceptId2, await (0, import_promises2.readFile)((0, import_node_path2.join)(root, name), "utf8"))
1965
+ async ({ name, conceptId: conceptId2 }) => this.parse(conceptId2, await (0, import_promises4.readFile)((0, import_node_path6.join)(root, name), "utf8"))
1155
1966
  )
1156
1967
  );
1157
1968
  return records.filter((record) => record !== null);
@@ -1184,15 +1995,11 @@ var KbStore = class {
1184
1995
  async supersede(bundlePath2, conceptId2, replacementId, actor = "unknown") {
1185
1996
  const replacement = await this.read(bundlePath2, replacementId);
1186
1997
  if (!replacement) throw new KbRecordNotFoundError(replacementId);
1187
- const superseded = await this.mutate(
1998
+ const superseded = await this.markSuperseded(
1188
1999
  bundlePath2,
1189
2000
  conceptId2,
1190
- (frontmatter) => ({
1191
- ...frontmatter,
1192
- strauss_status: "superseded",
1193
- strauss_superseded_by: replacementId
1194
- }),
1195
- { operation: "supersede", by: actor, target: replacementId }
2001
+ replacementId,
2002
+ actor
1196
2003
  );
1197
2004
  await this.mutate(
1198
2005
  bundlePath2,
@@ -1289,19 +2096,19 @@ ${answer}
1289
2096
  const adjudicated = adjudicate(wanted, bundle);
1290
2097
  const records = adjudicated.filter((hit) => hit.standing !== "superseded");
1291
2098
  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) {
2099
+ const approxTokens2 = records.reduce((total, hit) => total + estimateTokens(hit.record), 0) + superseded.reduce((total, entry) => total + estimateStubTokens(entry), 0);
2100
+ if (approxTokens2 > budgetTokens) {
1294
2101
  return {
1295
2102
  loaded: false,
1296
2103
  recordCount: wanted.length,
1297
- approxTokens,
2104
+ approxTokens: approxTokens2,
1298
2105
  budgetTokens
1299
2106
  };
1300
2107
  }
1301
2108
  return {
1302
2109
  loaded: true,
1303
2110
  recordCount: wanted.length,
1304
- approxTokens,
2111
+ approxTokens: approxTokens2,
1305
2112
  budgetTokens,
1306
2113
  records,
1307
2114
  superseded
@@ -1321,11 +2128,11 @@ ${answer}
1321
2128
  async readIndex(bundlePath2) {
1322
2129
  const root = this.root(bundlePath2);
1323
2130
  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(
2131
+ const stored = await (0, import_promises4.readFile)((0, import_node_path6.join)(root, INDEX_FILE), "utf8").catch(
1325
2132
  () => null
1326
2133
  );
1327
2134
  if (indexIsStale(stored, expected)) {
1328
- await this.publish((0, import_node_path2.join)(root, INDEX_FILE), expected, true, INDEX_FILE);
2135
+ await this.publish((0, import_node_path6.join)(root, INDEX_FILE), expected, true, INDEX_FILE);
1329
2136
  this.logger.info?.({
1330
2137
  operation: "kb.index.repair",
1331
2138
  bundlePath: root,
@@ -1342,8 +2149,8 @@ ${answer}
1342
2149
  * knows which agent touched what. So a bad line is surfaced and left alone.
1343
2150
  */
1344
2151
  async readLog(bundlePath2) {
1345
- const raw = await (0, import_promises2.readFile)(
1346
- (0, import_node_path2.join)(this.root(bundlePath2), LOG_FILE),
2152
+ const raw = await (0, import_promises4.readFile)(
2153
+ (0, import_node_path6.join)(this.root(bundlePath2), LOG_FILE),
1347
2154
  "utf8"
1348
2155
  ).catch(() => "");
1349
2156
  const result = parseLog(raw);
@@ -1356,16 +2163,52 @@ ${answer}
1356
2163
  }
1357
2164
  return result;
1358
2165
  }
2166
+ /**
2167
+ * `markSuperseded`, tolerant of the two ways it legitimately doesn't land:
2168
+ * a missing target (a broken link, legal per compose.ts) or a CAS conflict
2169
+ * from a concurrent writer touching the same target. A conflict is retried
2170
+ * a bounded number of times — each attempt re-reads the target fresh — and
2171
+ * on the last, `false` reports "not marked" rather than throwing: the
2172
+ * caller's own record is already published, so failing here would leave
2173
+ * that publish unreported instead of undone. kb_validate's existing
2174
+ * "not marked superseded" check is what surfaces the residue.
2175
+ */
2176
+ async markSupersededRetrying(bundlePath2, conceptId2, replacementId, actor, retries = 3) {
2177
+ for (let attempt = 0; attempt <= retries; attempt++) {
2178
+ try {
2179
+ await this.markSuperseded(bundlePath2, conceptId2, replacementId, actor);
2180
+ return true;
2181
+ } catch (error) {
2182
+ if (error instanceof KbRecordNotFoundError) return false;
2183
+ if (!(error instanceof KbWriteConflictError)) throw error;
2184
+ if (attempt === retries) return false;
2185
+ }
2186
+ }
2187
+ return false;
2188
+ }
2189
+ /** The one-directional half of `supersede`: marks `conceptId` superseded. */
2190
+ async markSuperseded(bundlePath2, conceptId2, replacementId, actor) {
2191
+ return this.mutate(
2192
+ bundlePath2,
2193
+ conceptId2,
2194
+ (frontmatter) => ({
2195
+ ...frontmatter,
2196
+ strauss_status: "superseded",
2197
+ strauss_superseded_by: replacementId
2198
+ }),
2199
+ { operation: "supersede", by: actor, target: replacementId }
2200
+ );
2201
+ }
1359
2202
  async mutate(bundlePath2, conceptId2, change, entry, changeBody = (body) => body) {
1360
2203
  const target = this.recordPath(bundlePath2, conceptId2);
1361
- const before = await (0, import_promises2.readFile)(target, "utf8").catch(() => null);
2204
+ const before = await (0, import_promises4.readFile)(target, "utf8").catch(() => null);
1362
2205
  if (before === null) throw new KbRecordNotFoundError(conceptId2);
1363
2206
  const parsed = this.parse(conceptId2, before);
1364
2207
  if (!parsed) throw new KbRecordNotFoundError(conceptId2);
1365
2208
  const frontmatter = change(parsed.frontmatter);
1366
2209
  const body = changeBody(parsed.body);
1367
2210
  const contents = stringifyMarkdownWithFrontmatter(body, frontmatter);
1368
- const witness = await (0, import_promises2.readFile)(target, "utf8").catch(() => null);
2211
+ const witness = await (0, import_promises4.readFile)(target, "utf8").catch(() => null);
1369
2212
  if (witness === null || digest(witness) !== digest(before)) {
1370
2213
  throw new KbWriteConflictError(conceptId2);
1371
2214
  }
@@ -1391,26 +2234,26 @@ ${answer}
1391
2234
  */
1392
2235
  async publish(target, contents, overwrite, conceptId2) {
1393
2236
  const staging = `${target}.${process.pid}.tmp`;
1394
- await (0, import_promises2.writeFile)(staging, contents, "utf8");
2237
+ await (0, import_promises4.writeFile)(staging, contents, "utf8");
1395
2238
  try {
1396
2239
  if (overwrite) {
1397
- await (0, import_promises2.rename)(staging, target);
2240
+ await (0, import_promises4.rename)(staging, target);
1398
2241
  return;
1399
2242
  }
1400
- await (0, import_promises2.link)(staging, target);
2243
+ await (0, import_promises4.link)(staging, target);
1401
2244
  } catch (error) {
1402
2245
  if (error.code === "EEXIST") {
1403
2246
  throw new KbRecordAlreadyExistsError(conceptId2);
1404
2247
  }
1405
2248
  throw error;
1406
2249
  } finally {
1407
- await (0, import_promises2.unlink)(staging).catch(() => void 0);
2250
+ await (0, import_promises4.unlink)(staging).catch(() => void 0);
1408
2251
  }
1409
2252
  }
1410
2253
  /** Appends one log line. Failing to log must not fail the mutation. */
1411
2254
  async record(root, entry) {
1412
2255
  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) => {
2256
+ await (0, import_promises4.appendFile)((0, import_node_path6.join)(root, LOG_FILE), line, "utf8").catch((error) => {
1414
2257
  this.logger.warn?.({
1415
2258
  operation: "kb.log.append",
1416
2259
  outcome: "failed",
@@ -1436,18 +2279,18 @@ ${answer}
1436
2279
  };
1437
2280
  }
1438
2281
  root(bundlePath2) {
1439
- return (0, import_node_path2.resolve)(bundlePath2);
2282
+ return (0, import_node_path6.resolve)(bundlePath2);
1440
2283
  }
1441
2284
  // Concept ids are `<type>.<slug>` and map to a single file directly under the
1442
2285
  // bundle root; anything carrying a separator would escape it.
1443
2286
  recordPath(bundlePath2, conceptId2) {
1444
- if (conceptId2.includes(import_node_path2.sep) || conceptId2.includes("/")) {
2287
+ if (conceptId2.includes(import_node_path6.sep) || conceptId2.includes("/")) {
1445
2288
  throw new KbInvalidConceptIdError(
1446
2289
  "concept id must not contain a path separator",
1447
2290
  { conceptId: conceptId2 }
1448
2291
  );
1449
2292
  }
1450
- return (0, import_node_path2.join)(this.root(bundlePath2), `${conceptId2}.md`);
2293
+ return (0, import_node_path6.join)(this.root(bundlePath2), `${conceptId2}.md`);
1451
2294
  }
1452
2295
  };
1453
2296
  function estimateTokens(record) {
@@ -1489,6 +2332,7 @@ function createKbMcpServer() {
1489
2332
  now: () => (/* @__PURE__ */ new Date()).toISOString()
1490
2333
  };
1491
2334
  for (const command of KB_COMMANDS) {
2335
+ if (!command.tool) continue;
1492
2336
  server.registerTool(
1493
2337
  command.tool,
1494
2338
  { description: command.description, inputSchema: command.input.shape },