@bunshin-cc/bunshin 0.10.5 → 0.11.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/bin.js +1615 -933
  2. package/package.json +1 -1
package/dist/bin.js CHANGED
@@ -336,35 +336,35 @@ function containedPath(root, rel) {
336
336
  const abs = path2.join(root, rel);
337
337
  return insideRoot(root, abs) ? abs : null;
338
338
  }
339
- function readJson(file, fallback) {
339
+ function readJson(file2, fallback) {
340
340
  try {
341
- return JSON.parse(fs2.readFileSync(file, "utf8"));
341
+ return JSON.parse(fs2.readFileSync(file2, "utf8"));
342
342
  } catch {
343
343
  return fallback;
344
344
  }
345
345
  }
346
- function writeJsonAtomic(file, value) {
347
- writeTextAtomic(file, JSON.stringify(value, null, 2) + "\n");
346
+ function writeJsonAtomic(file2, value) {
347
+ writeTextAtomic(file2, JSON.stringify(value, null, 2) + "\n");
348
348
  }
349
- function writeTextAtomic(file, text2) {
350
- ensureDir(path2.dirname(file));
351
- const tmp = `${file}.${process.pid}.${randomBytes(3).toString("hex")}.tmp`;
349
+ function writeTextAtomic(file2, text2) {
350
+ ensureDir(path2.dirname(file2));
351
+ const tmp = `${file2}.${process.pid}.${randomBytes(3).toString("hex")}.tmp`;
352
352
  let mode = 384;
353
353
  try {
354
- mode = fs2.statSync(file).mode & 448 || 384;
354
+ mode = fs2.statSync(file2).mode & 448 || 384;
355
355
  } catch {
356
356
  }
357
357
  fs2.writeFileSync(tmp, text2, { mode });
358
- fs2.renameSync(tmp, file);
358
+ fs2.renameSync(tmp, file2);
359
359
  }
360
- function appendLine(file, line) {
361
- ensureDir(path2.dirname(file));
362
- fs2.appendFileSync(file, line.endsWith("\n") ? line : line + "\n", { mode: 384 });
360
+ function appendLine(file2, line) {
361
+ ensureDir(path2.dirname(file2));
362
+ fs2.appendFileSync(file2, line.endsWith("\n") ? line : line + "\n", { mode: 384 });
363
363
  }
364
- function readJsonl(file) {
364
+ function readJsonl(file2) {
365
365
  let raw;
366
366
  try {
367
- raw = fs2.readFileSync(file, "utf8");
367
+ raw = fs2.readFileSync(file2, "utf8");
368
368
  } catch {
369
369
  return [];
370
370
  }
@@ -453,17 +453,17 @@ function trustStore(root) {
453
453
  const dir2 = configDir();
454
454
  fs3.mkdirSync(dir2, { recursive: true, mode: 448 });
455
455
  fs3.chmodSync(dir2, 448);
456
- const file = trustFile();
457
- const tmp = `${file}.${process.pid}.${randomBytes2(3).toString("hex")}.tmp`;
456
+ const file2 = trustFile();
457
+ const tmp = `${file2}.${process.pid}.${randomBytes2(3).toString("hex")}.tmp`;
458
458
  fs3.writeFileSync(tmp, JSON.stringify({ stores: [...list2, real] }, null, 2) + "\n", { mode: 384 });
459
- fs3.renameSync(tmp, file);
459
+ fs3.renameSync(tmp, file2);
460
460
  }
461
461
  function credentialAnchored(root, config) {
462
- const { credentialFile: file, apiUrl, orgId, userId } = config;
463
- if (typeof file !== "string" || typeof apiUrl !== "string" || typeof orgId !== "string" || typeof userId !== "string") return false;
464
- if (!path3.isAbsolute(file) || realish(path3.dirname(file)) !== realish(credentialDir())) return false;
462
+ const { credentialFile: file2, apiUrl, orgId, userId } = config;
463
+ if (typeof file2 !== "string" || typeof apiUrl !== "string" || typeof orgId !== "string" || typeof userId !== "string") return false;
464
+ if (!path3.isAbsolute(file2) || realish(path3.dirname(file2)) !== realish(credentialDir())) return false;
465
465
  try {
466
- if (!fs3.lstatSync(file).isFile()) return false;
466
+ if (!fs3.lstatSync(file2).isFile()) return false;
467
467
  } catch {
468
468
  return false;
469
469
  }
@@ -471,7 +471,7 @@ function credentialAnchored(root, config) {
471
471
  ${apiUrl}
472
472
  ${orgId}
473
473
  ${userId}`).digest("hex")}.json`;
474
- return [path3.resolve(root), realish(root)].some((r) => path3.basename(file) === name(r));
474
+ return [path3.resolve(root), realish(root)].some((r) => path3.basename(file2) === name(r));
475
475
  }
476
476
  function storeTrusted(root, config = readJson(path3.join(root, "config.json"), {})) {
477
477
  if (isGlobalStore(root) || trustedStores().includes(realish(root))) return true;
@@ -517,6 +517,9 @@ var init_trust = __esm({
517
517
  // src/store.ts
518
518
  import fs4 from "node:fs";
519
519
  import path4 from "node:path";
520
+ function recallRouter(config) {
521
+ return config.recall.router ?? (config.backend === "claude-cli" ? "claude-cli" : "server");
522
+ }
520
523
  function fileId(id) {
521
524
  if (!id || id === "." || id === ".." || /[\\/\0]/.test(id)) throw new Error(`unsafe id ${JSON.stringify(String(id).slice(0, 80))}`);
522
525
  return id;
@@ -691,9 +694,9 @@ var init_store = __esm({
691
694
  getLesson(id) {
692
695
  return fileExists(this.lessonPath(id)) ? this.readLessonFile(this.lessonPath(id)) : null;
693
696
  }
694
- readLessonFile(file) {
697
+ readLessonFile(file2) {
695
698
  try {
696
- return lessonFromMarkdown(fs4.readFileSync(file, "utf8"));
699
+ return lessonFromMarkdown(fs4.readFileSync(file2, "utf8"));
697
700
  } catch {
698
701
  return null;
699
702
  }
@@ -761,11 +764,11 @@ var init_store = __esm({
761
764
  }
762
765
  /** Rewrite one session's trace file with patched traces (used by attribution). */
763
766
  updateTraces(sessionId, patch) {
764
- const file = this.traceFile(sessionId);
765
- const lines = readJsonl(file);
767
+ const file2 = this.traceFile(sessionId);
768
+ const lines = readJsonl(file2);
766
769
  if (!lines.length) return;
767
770
  const text2 = lines.map((l) => l.kind === "trace" && l.trace ? { kind: "trace", trace: patch(l.trace) } : l).map((l) => JSON.stringify(l)).join("\n");
768
- writeTextAtomic(file, text2 + "\n");
771
+ writeTextAtomic(file2, text2 + "\n");
769
772
  }
770
773
  // ----- sessions / pending inject -----
771
774
  readSession(id) {
@@ -782,10 +785,10 @@ var init_store = __esm({
782
785
  writeTextAtomic(this.pendingInjectPath(sessionId), text2);
783
786
  }
784
787
  consumePendingInject(sessionId) {
785
- const file = this.pendingInjectPath(sessionId);
788
+ const file2 = this.pendingInjectPath(sessionId);
786
789
  try {
787
- const text2 = fs4.readFileSync(file, "utf8");
788
- fs4.unlinkSync(file);
790
+ const text2 = fs4.readFileSync(file2, "utf8");
791
+ fs4.unlinkSync(file2);
789
792
  return text2;
790
793
  } catch {
791
794
  return null;
@@ -980,32 +983,31 @@ var init_text = __esm({
980
983
  "vs"
981
984
  ]);
982
985
  PHRASE_ENTITIES = [
983
- "negative balance",
984
986
  "account closure",
985
987
  "close account",
986
988
  "closed account",
989
+ "delete account",
990
+ "account deletion",
991
+ "workspace deletion",
992
+ "data deletion",
993
+ "data retention",
994
+ "data export",
995
+ "personal data",
996
+ "legal hold",
987
997
  "opt out",
988
998
  "opt-out",
989
- "apr",
990
- "interest rate",
991
- "chargeback",
999
+ "cancel subscription",
1000
+ "subscription cancellation",
992
1001
  "refund",
993
- "credit balance",
1002
+ "chargeback",
1003
+ "invoice",
1004
+ "dispute",
994
1005
  "write off",
995
1006
  "write-off",
996
- "collections",
997
1007
  "settlement",
998
- "dispute",
999
- "kyc",
1000
- "aml",
1001
- "statement",
1002
- "billing cycle",
1003
- "late fee",
1004
- "credit limit",
1005
- "minimum payment",
1006
- "direct debit",
1007
- "card replacement",
1008
- "fraud hold"
1008
+ "offboarding",
1009
+ "access review",
1010
+ "audit log"
1009
1011
  ];
1010
1012
  CONSTRAINT_PATTERNS = [
1011
1013
  /\bmanual(?:ly)?\s+(?:process|step|review|closure|approval|handled|handle|close)\b/i,
@@ -1200,10 +1202,10 @@ function isLocalLayer(layer) {
1200
1202
  return kind === "user" || kind === "robot";
1201
1203
  }
1202
1204
  function withScope(layers, scope) {
1203
- const path29 = scopePath(scope?.tree, scope?.source);
1204
- if (!path29.length) return layers;
1205
+ const path30 = scopePath(scope?.tree, scope?.source);
1206
+ if (!path30.length) return layers;
1205
1207
  const i = layers.findIndex((l) => isLocalLayer(l));
1206
- return i < 0 ? [...layers, ...path29] : [...layers.slice(0, i), ...path29, ...layers.slice(i)];
1208
+ return i < 0 ? [...layers, ...path30] : [...layers.slice(0, i), ...path30, ...layers.slice(i)];
1207
1209
  }
1208
1210
  function readerFor(ctx, ownerClearance, scope) {
1209
1211
  if (ctx.kind === "robot" && !scope?.source) scope = { ...scope, source: `robot:${ctx.id}` };
@@ -1250,11 +1252,11 @@ function baseAffinity(section, reader) {
1250
1252
  const kind = layerKind(section.layer);
1251
1253
  if (kind === "group" || kind === "source") {
1252
1254
  if (!reader.layers.includes(section.layer)) return 0.05;
1253
- const path29 = reader.layers.filter((l) => {
1255
+ const path30 = reader.layers.filter((l) => {
1254
1256
  const k = layerKind(l);
1255
1257
  return k === "group" || k === "source";
1256
1258
  });
1257
- return 0.6 + 0.4 * ((path29.indexOf(section.layer) + 1) / path29.length);
1259
+ return 0.6 + 0.4 * ((path30.indexOf(section.layer) + 1) / path30.length);
1258
1260
  }
1259
1261
  if (isLocalLayer(section.layer)) return reader.layers.includes(section.layer) ? 1 : 0;
1260
1262
  return 0.5;
@@ -1454,17 +1456,17 @@ var init_document = __esm({
1454
1456
  function repoLayer(repo) {
1455
1457
  return `source:${repo.includes("/") ? "repo" : "folder"}:${repo}`;
1456
1458
  }
1457
- function repoSectionId(repo, path29, anchor = "") {
1458
- return anchor ? `repo:${repo}/${path29}#${anchor}` : `repo:${repo}/${path29}`;
1459
+ function repoSectionId(repo, path30, anchor = "") {
1460
+ return anchor ? `repo:${repo}/${path30}#${anchor}` : `repo:${repo}/${path30}`;
1459
1461
  }
1460
- function docKind(path29) {
1461
- const base = path29.split("/").pop()?.toLowerCase() ?? "";
1462
+ function docKind(path30) {
1463
+ const base = path30.split("/").pop()?.toLowerCase() ?? "";
1462
1464
  if (base === "testing.md") return "verification";
1463
1465
  if (base === "skill.md") return "skill";
1464
1466
  return "spec";
1465
1467
  }
1466
- function defaultPaths(path29) {
1467
- const dir2 = path29.split("/").slice(0, -1).join("/");
1468
+ function defaultPaths(path30) {
1469
+ const dir2 = path30.split("/").slice(0, -1).join("/");
1468
1470
  if (!dir2 || dir2.startsWith(".claude/") || dir2.startsWith(".codex/")) return [];
1469
1471
  return [`${dir2}/**`];
1470
1472
  }
@@ -1609,11 +1611,11 @@ function lintSkills(sections) {
1609
1611
  }
1610
1612
  const state = /* @__PURE__ */ new Map();
1611
1613
  const cycles = /* @__PURE__ */ new Set();
1612
- const dfs = (n, path29) => {
1614
+ const dfs = (n, path30) => {
1613
1615
  state.set(n, 1);
1614
1616
  for (const d of edges[n] ?? []) {
1615
- if (state.get(d) === 1) cycles.add([...path29.slice(path29.indexOf(d)), d].join(" -> "));
1616
- else if (!state.get(d)) dfs(d, [...path29, d]);
1617
+ if (state.get(d) === 1) cycles.add([...path30.slice(path30.indexOf(d)), d].join(" -> "));
1618
+ else if (!state.get(d)) dfs(d, [...path30, d]);
1617
1619
  }
1618
1620
  state.set(n, 2);
1619
1621
  };
@@ -1700,8 +1702,8 @@ function parsePythonSkills(text2) {
1700
1702
  }
1701
1703
  return { skills, constants };
1702
1704
  }
1703
- function harnessSectionId(path29, symbol) {
1704
- return `harness:${path29}#${symbol}`;
1705
+ function harnessSectionId(path30, symbol) {
1706
+ return `harness:${path30}#${symbol}`;
1705
1707
  }
1706
1708
  var DEF_RE;
1707
1709
  var init_python = __esm({
@@ -1827,11 +1829,11 @@ function globToRegExp(glob) {
1827
1829
  globCache.set(glob, out);
1828
1830
  return out;
1829
1831
  }
1830
- function normalPath(path29) {
1831
- return path29.replace(/\\/g, "/").split("/").filter((s) => s !== "" && s !== ".").join("/");
1832
+ function normalPath(path30) {
1833
+ return path30.replace(/\\/g, "/").split("/").filter((s) => s !== "" && s !== ".").join("/");
1832
1834
  }
1833
- function matchesGlob(path29, glob) {
1834
- return globToRegExp(glob.replace(/^\.\//, "")).test(normalPath(path29));
1835
+ function matchesGlob(path30, glob) {
1836
+ return globToRegExp(glob.replace(/^\.\//, "")).test(normalPath(path30));
1835
1837
  }
1836
1838
  var DEFAULT_EMBEDDERS, globCache;
1837
1839
  var init_text_index = __esm({
@@ -1922,10 +1924,10 @@ function push(sections, reader, query) {
1922
1924
  for (const s of recallable(sections, reader).filter((x) => reachesReader(x, reader))) {
1923
1925
  const triggers = [...(s.triggers ?? []).filter((t) => t.anchor), { anchor: "", paths: s.paths, entities: s.entities, skills: s.skills }];
1924
1926
  for (const t of triggers) {
1925
- const path29 = paths.find((p) => t.paths.some((g) => matchesGlob(p, g)));
1926
- const entity = path29 ? void 0 : t.entities.find((e) => entities.has(e) || text2 && text2.includes(e));
1927
- const skill = path29 || entity ? void 0 : skills.find((k) => t.skills.includes(k));
1928
- const trigger = path29 ? `path:${path29}` : entity ? `entity:${entity}` : skill ? `skill:${skill}` : "";
1927
+ const path30 = paths.find((p) => t.paths.some((g) => matchesGlob(p, g)));
1928
+ const entity = path30 ? void 0 : t.entities.find((e) => entities.has(e) || text2 && text2.includes(e));
1929
+ const skill = path30 || entity ? void 0 : skills.find((k) => t.skills.includes(k));
1930
+ const trigger = path30 ? `path:${path30}` : entity ? `entity:${entity}` : skill ? `skill:${skill}` : "";
1929
1931
  if (trigger) {
1930
1932
  hits.set(s.id, { section: s, trigger, anchor: t.anchor });
1931
1933
  break;
@@ -2040,8 +2042,8 @@ function renderSection(s, trigger, opts = {}) {
2040
2042
  return [
2041
2043
  ...head,
2042
2044
  "",
2043
- `The \`${s.skill.name}\` skill applies: ${s.skill.description}`,
2044
- `It is installed. Invoke it (Skill tool, or \`/${s.skill.name}\`) before doing this by hand${part2 ? `; the relevant part is \xA7${part2.anchor} "${part2.title}"` : ""}.`
2045
+ `The \`${s.skill.name}\` skill may apply: ${s.skill.description}`,
2046
+ `It is installed. If this starts that workflow, invoke it (Skill tool, or \`/${s.skill.name}\`). For one detail of it, don't load the whole skill: load the part you need with bunshin_load {"section_id": "${s.id}"${part2 ? `, "anchor": "${part2.anchor}"` : ""}} (or \`bunshin load ${s.id}${part2 ? ` --anchor ${part2.anchor}` : ""}\`)${part2 ? ` (the relevant part is \xA7${part2.anchor} "${part2.title}")` : ""}.`
2045
2047
  ].join("\n");
2046
2048
  }
2047
2049
  if (s.body.length <= max) return [...head, "", s.body.trim()].join("\n");
@@ -2080,6 +2082,230 @@ var init_engine = __esm({
2080
2082
  }
2081
2083
  });
2082
2084
 
2085
+ // ../core/src/v2/atoms.ts
2086
+ function compileTrigger(t) {
2087
+ if (compiled.has(t.match)) return compiled.get(t.match);
2088
+ let re = null;
2089
+ if (t.match && t.match.length <= MAX_PATTERN && !NESTED_QUANTIFIER.test(t.match)) {
2090
+ try {
2091
+ re = new RegExp(t.match, "i");
2092
+ } catch {
2093
+ re = null;
2094
+ }
2095
+ }
2096
+ if (compiled.size > 5e3) compiled.clear();
2097
+ compiled.set(t.match, re);
2098
+ return re;
2099
+ }
2100
+ function validTrigger(raw) {
2101
+ if (!raw || typeof raw !== "object") return null;
2102
+ const o = raw;
2103
+ const tool = typeof o.tool === "string" && o.tool.trim() ? o.tool.trim().slice(0, 120) : "*";
2104
+ const match = typeof o.match === "string" ? o.match.trim() : "";
2105
+ return match && compileTrigger({ match }) ? { tool, match } : null;
2106
+ }
2107
+ function toolCallText(input) {
2108
+ if (!input || typeof input !== "object") return "";
2109
+ if (typeof input.command === "string") return input.command.slice(0, TEXT_CHARS);
2110
+ const out = [];
2111
+ const walk = (v, depth) => {
2112
+ if (typeof v === "string") out.push(v.slice(0, TEXT_CHARS));
2113
+ else if (depth < 3 && Array.isArray(v)) v.forEach((x) => walk(x, depth + 1));
2114
+ else if (depth < 3 && v && typeof v === "object") Object.values(v).forEach((x) => walk(x, depth + 1));
2115
+ };
2116
+ walk(input, 0);
2117
+ return out.join("\n").slice(0, TEXT_CHARS);
2118
+ }
2119
+ function toolTriggerHits(sections, reader, call2, opts = {}) {
2120
+ const text2 = toolCallText(call2.input);
2121
+ if (!text2 || !call2.tool) return [];
2122
+ const skip = new Set(opts.exclude ?? []);
2123
+ const hits = [];
2124
+ for (const s of recallable(sections, reader)) {
2125
+ if (!s.toolTriggers?.length || skip.has(s.id) || !isAtom(s) || !reachesReader(s, reader)) continue;
2126
+ for (const [index, t] of s.toolTriggers.entries()) {
2127
+ if (!toolMatches(t.tool, call2.tool)) continue;
2128
+ const key = triggerKey(s, index);
2129
+ if (opts.muted?.has(key)) continue;
2130
+ const m = compileTrigger(t)?.exec(text2);
2131
+ if (!m) continue;
2132
+ hits.push({ section: s, index, trigger: t, match: m[0].slice(0, 120), key });
2133
+ break;
2134
+ }
2135
+ }
2136
+ const rank = (k) => ["guardrail", "rule", "fact", "card"].indexOf(k);
2137
+ return hits.sort((a, b) => rank(a.section.kind) - rank(b.section.kind) || a.section.title.localeCompare(b.section.title)).slice(0, opts.max ?? 2);
2138
+ }
2139
+ function usageCues(s) {
2140
+ const out = /* @__PURE__ */ new Set();
2141
+ const body = s.body.replace(/_\(learned \d{4}-[^)]*\)_/g, "");
2142
+ for (const m of body.matchAll(/`([^`\n]{2,80})`/g)) out.add(m[1].trim().toLowerCase());
2143
+ for (const c of s.cues ?? []) if (c.trim().length >= 3) out.add(c.trim().toLowerCase());
2144
+ for (const m of body.matchAll(/(?:^|[\s(])((?:--?[a-z][\w-]{1,30})|(?:[\w.-]*[_/.][\w./-]*\w))(?=$|[\s),.:;])/gim)) {
2145
+ const w = m[1].toLowerCase();
2146
+ if (w.length >= 3 && !STOP.has(w) && !/^\d+(\.\d+)*$/.test(w)) out.add(w);
2147
+ }
2148
+ return [...out].filter((c) => c.length >= 2).slice(0, 40);
2149
+ }
2150
+ function cardsOf(spine, sections) {
2151
+ const order = new Map((spine.outline ?? []).map((h, i) => [h.anchor, i]));
2152
+ return sections.filter((s) => s.partOf === spine.id && isAtom(s) && s.status !== "retired" && s.status !== "superseded" && s.status !== "pending").sort((a, b) => (order.get(a.step ?? "") ?? 1e9) - (order.get(b.step ?? "") ?? 1e9) || a.title.localeCompare(b.title));
2153
+ }
2154
+ function renderCardIndex(spine, cards, opts = {}) {
2155
+ if (!cards.length) return "";
2156
+ const stepTitle = new Map((spine.outline ?? []).map((h) => [h.anchor, h.title]));
2157
+ const oneLine = (t) => t.replace(/\s+/g, " ").trim().slice(0, 240);
2158
+ const lines = cards.map((c) => `- ${c.title} (${c.kind}, id: ${c.id}${c.step ? `, step: ${stepTitle.get(c.step) ?? c.step}` : ""}) \u2014 when: ${oneLine(c.when || c.title)}`);
2159
+ const load = opts.mcp ? `bunshin_load {"section_id": "<id>"}` : "`bunshin load <id>`";
2160
+ return [
2161
+ `### CARDS of ${spine.skill ? `the \`${spine.skill.name}\` skill` : spine.title}`,
2162
+ `The details of this workflow's steps are separate cards. Each arrives on its own when your work reaches it; load one yourself with ${load} when you get to its step and need the detail.`,
2163
+ "",
2164
+ ...lines
2165
+ ].join("\n");
2166
+ }
2167
+ function normalizeLine(line) {
2168
+ return line.replace(/^\s*(?:[-*+]|\d+[.)])\s+(?:\[[ xX]\]\s+)?/, "").replace(/^\s*#{1,6}\s+/, "").replace(/^\s*>\s?/, "").replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/[*_~`|]/g, "").replace(/\s+/g, " ").trim().toLowerCase();
2169
+ }
2170
+ function splitCoverage(source, units) {
2171
+ const body = source.slice(parseFrontmatter2(source).bodyStart);
2172
+ const held = units.map((u) => ` ${u.body.split("\n").map(normalizeLine).filter(Boolean).join(" ")} `);
2173
+ const missing = [];
2174
+ let lines = 0;
2175
+ for (const raw of body.split("\n")) {
2176
+ if (/^\s*(```|~~~)/.test(raw)) continue;
2177
+ const n = normalizeLine(raw);
2178
+ if (trivial(n)) continue;
2179
+ lines++;
2180
+ if (!held.some((h) => h.includes(n))) missing.push(raw.trim());
2181
+ }
2182
+ return { lines, missing };
2183
+ }
2184
+ function buildSplitPrompt(skill) {
2185
+ return `You split one long agent skill into a SPINE and ATOMS. Agents will get the spine when they
2186
+ start the workflow, and each atom only when their work reaches it (a tool call that matches its
2187
+ trigger, or a router that sees what they are doing), or when they ask a narrow question it answers.
2188
+
2189
+ The skill: ${skill.name}
2190
+ What it is for: ${skill.description}
2191
+
2192
+ <skill>
2193
+ ${skill.body.slice(parseFrontmatter2(skill.body).bodyStart)}
2194
+ </skill>
2195
+
2196
+ Units:
2197
+ - "spine" (exactly one): the workflow's map. Its headings in order, and under each step the one or
2198
+ two lines that say what the step is and when it is done. At most about 1000 words. A step whose
2199
+ detail moved into cards keeps its heading.
2200
+ - "card": the detail of one step or one situation within the workflow (how to do it, the commands,
2201
+ the checks). "step" names the spine heading it belongs under, as written there.
2202
+ - "fact": something that is true regardless of the step (a tool's quirk, an environment fact, a trap
2203
+ and what works instead, another team's process).
2204
+ - "rule": a correction or preference someone taught ("never \u2026", "always \u2026", "the user wants \u2026").
2205
+
2206
+ Rules for the split:
2207
+ - LOSSLESS. Every line of the skill goes into some unit, word for word. You may move lines, regroup
2208
+ them, and rewrap a paragraph; never reword, shorten, summarise or drop one. A line two units need
2209
+ may appear in both.
2210
+ - One atom is one thing: a fact, a rule, or one step's detail. Most are 30-300 words.
2211
+ - "title" names the thing; "when" says the moment an agent needs it, in the words of that moment
2212
+ ("before rerunning a failed CI job", "when a staging customer id is needed"), not a topic label.
2213
+ - "triggers": only when a tool call reliably marks that moment: [{"tool": "Bash", "match": "<regex>"}],
2214
+ a case-insensitive regular expression over the call's input (the shell command for Bash, else the
2215
+ call's strings). Specific enough that it rarely fires when the atom is not needed: a command
2216
+ together with the subcommand or flag the atom is about, not a bare program name. None is fine.
2217
+ - "from": the heading path in the skill the lines came from.
2218
+
2219
+ Return one JSON object and nothing else:
2220
+ {"spine": {"title": string, "when": string, "body": string},
2221
+ "units": [{"kind": "card"|"fact"|"rule", "title": string, "when": string, "body": string,
2222
+ "step"?: string, "triggers"?: [{"tool": string, "match": string}], "from"?: string}]}`;
2223
+ }
2224
+ function parseSplit(raw) {
2225
+ if (!raw || typeof raw !== "object") return null;
2226
+ const o = raw;
2227
+ const str8 = (v) => typeof v === "string" ? v.trim() : "";
2228
+ const spineBody = str8(o.spine?.body);
2229
+ if (!spineBody) return null;
2230
+ const units = [];
2231
+ for (const u of Array.isArray(o.units) ? o.units : []) {
2232
+ const x = u ?? {};
2233
+ const kind = x.kind === "card" || x.kind === "fact" || x.kind === "rule" ? x.kind : null;
2234
+ const title = str8(x.title);
2235
+ const body = str8(x.body);
2236
+ if (!kind || !title || !body) continue;
2237
+ const triggers = (Array.isArray(x.triggers) ? x.triggers : []).map(validTrigger).filter((t) => !!t).slice(0, 4);
2238
+ units.push({ kind, title: title.slice(0, 300), when: str8(x.when) || title, body, ...str8(x.step) ? { step: str8(x.step) } : {}, ...triggers.length ? { triggers } : {}, ...str8(x.from) ? { from: str8(x.from).slice(0, 300) } : {} });
2239
+ }
2240
+ return { spine: { kind: "spine", title: str8(o.spine?.title), when: str8(o.spine?.when), body: spineBody }, units };
2241
+ }
2242
+ function withSpineAtoms(chosen, sections, max = 30) {
2243
+ const have = new Set(chosen.map((s) => s.id));
2244
+ const byId = new Map(sections.map((s) => [s.id, s]));
2245
+ const extra = [];
2246
+ for (const c of chosen) {
2247
+ const s = byId.get(c.id);
2248
+ if (!s?.skill) continue;
2249
+ for (const a of cardsOf(s, sections)) if (!have.has(a.id) && extra.length < max) have.add(a.id), extra.push(a);
2250
+ }
2251
+ return [...chosen, ...extra];
2252
+ }
2253
+ var ATOM_KINDS, ATOM_CHARS, isAtom, MAX_PATTERN, TEXT_CHARS, compiled, NESTED_QUANTIFIER, toolMatches, triggerKey, STOP, cuesIn, TRIGGER_FLOOR, TRIGGER_MIN_JUDGED, triggerPrecision, triggerMuted, trivial, SPLIT_SCHEMA;
2254
+ var init_atoms = __esm({
2255
+ "../core/src/v2/atoms.ts"() {
2256
+ "use strict";
2257
+ init_layers();
2258
+ init_engine();
2259
+ init_document();
2260
+ ATOM_KINDS = /* @__PURE__ */ new Set(["rule", "fact", "card", "guardrail"]);
2261
+ ATOM_CHARS = 4e3;
2262
+ isAtom = (s) => ATOM_KINDS.has(s.kind) && s.body.length <= ATOM_CHARS;
2263
+ MAX_PATTERN = 300;
2264
+ TEXT_CHARS = 8e3;
2265
+ compiled = /* @__PURE__ */ new Map();
2266
+ NESTED_QUANTIFIER = /\((?:[^()\\]|\\.)*[+*}](?:[^()\\]|\\.)*\)\s*[+*{]/;
2267
+ toolMatches = (pattern, tool) => {
2268
+ const p = pattern.toLowerCase();
2269
+ const t = tool.toLowerCase();
2270
+ return p === "*" || p === t || p.endsWith("*") && t.startsWith(p.slice(0, -1));
2271
+ };
2272
+ triggerKey = (s, index) => `${s.id}#${index}@v${s.version}`;
2273
+ STOP = /* @__PURE__ */ new Set(["the", "and", "for", "with", "this", "that", "then", "when", "from", "into", "only", "never", "always", "use", "run", "not"]);
2274
+ cuesIn = (cues, text2) => {
2275
+ const t = text2.toLowerCase();
2276
+ return cues.filter((c) => t.includes(c));
2277
+ };
2278
+ TRIGGER_FLOOR = 0.4;
2279
+ TRIGGER_MIN_JUDGED = 8;
2280
+ triggerPrecision = (t) => t.judged ? t.used / t.judged : null;
2281
+ triggerMuted = (t) => !!t && t.judged >= TRIGGER_MIN_JUDGED && t.used / t.judged < TRIGGER_FLOOR;
2282
+ trivial = (n) => n.length < 3 || /^[-=:\s]+$/.test(n);
2283
+ SPLIT_SCHEMA = {
2284
+ type: "object",
2285
+ required: ["spine", "units"],
2286
+ properties: {
2287
+ spine: { type: "object", required: ["title", "when", "body"], properties: { title: { type: "string" }, when: { type: "string" }, body: { type: "string" } } },
2288
+ units: {
2289
+ type: "array",
2290
+ items: {
2291
+ type: "object",
2292
+ required: ["kind", "title", "when", "body"],
2293
+ properties: {
2294
+ kind: { type: "string", enum: ["card", "fact", "rule"] },
2295
+ title: { type: "string" },
2296
+ when: { type: "string" },
2297
+ body: { type: "string" },
2298
+ step: { type: "string" },
2299
+ from: { type: "string" },
2300
+ triggers: { type: "array", items: { type: "object", required: ["match"], properties: { tool: { type: "string" }, match: { type: "string" } } } }
2301
+ }
2302
+ }
2303
+ }
2304
+ }
2305
+ };
2306
+ }
2307
+ });
2308
+
2083
2309
  // ../core/src/v2/recall/router.ts
2084
2310
  function routerMessage(prompt, ctx, inContext2) {
2085
2311
  const lines = ["Session context:"];
@@ -2095,6 +2321,20 @@ ${prompt.slice(0, 6e3)}
2095
2321
  >>>
2096
2322
  Return the JSON line.`;
2097
2323
  }
2324
+ function checkpointMessage(ctx, actions, inContext2) {
2325
+ const lines = ["Checkpoint during the work (no new prompt). Session context:"];
2326
+ if (ctx.first) lines.push(`- First prompt of this session: ${ctx.first.slice(0, 600)}`);
2327
+ if (ctx.latest && ctx.latest !== ctx.first) lines.push(`- Latest user prompt: ${ctx.latest.slice(0, 600)}`);
2328
+ if (ctx.reply) lines.push(`- Agent's last reply: ${ctx.reply.slice(0, 1e3)}`);
2329
+ lines.push(`- Already in the agent's context: ${inContext2.length ? inContext2.join(", ") : "nothing from the library"}`);
2330
+ const recent = actions.slice(-20).map((a) => ` \xB7 ${a.replace(/\s+/g, " ").slice(0, 240)}`);
2331
+ return `${lines.join("\n")}
2332
+
2333
+ The agent's recent tool calls, oldest first:
2334
+ ${recent.join("\n") || " (none)"}
2335
+
2336
+ Which atoms does the step the agent is at, or about to start, need? Serve no document at a checkpoint ("serve": null). Return the JSON line.`;
2337
+ }
2098
2338
  function parseRouterAnswer(text2, items, skip = []) {
2099
2339
  const m = /\{[\s\S]*\}/.exec(text2);
2100
2340
  if (!m) return null;
@@ -2116,14 +2356,15 @@ var MAX_RULES, RULES;
2116
2356
  var init_router = __esm({
2117
2357
  "../core/src/v2/recall/router.ts"() {
2118
2358
  "use strict";
2359
+ init_atoms();
2119
2360
  MAX_RULES = 3;
2120
- RULES = `You are the prompt-time recall router for an engineering team's agent library. A coding agent is about to act on the user's latest prompt. You see the prompt plus session context: the session's first prompt, recent user prompts, the agent's last reply, and the items already in the agent's context. Decide what, if anything, to inject now.
2361
+ RULES = `You are the recall router for an engineering team's agent library. A coding agent is working; you see the moment (the user's latest prompt with session context, or at a checkpoint the agent's recent actions) and the items already in the agent's context. Decide what, if anything, to inject now. The library holds long documents (skills are workflows: a spine of steps) and short ATOMS: lessons (corrections or preferences taught before), facts (how something is, a trap and what works) and cards (the detail of one workflow step).
2121
2362
 
2122
- - "serve": at most ONE skill or document, injected in full (long). Serve only when this prompt starts or clearly redirects work that the item is the procedure for, and it is not already in context. Follow-ups, approvals, status questions, chatter, and continuing work already under way need none.
2123
- - "rules": at most ${MAX_RULES} LESSONS (short corrections or preferences learned from this team before), injected in full. Include a lesson only when what the agent will DO in response to this prompt \u2014 including the steps the work it starts normally leads to (a ticket ends in a PR and a report; a fix ends in evidence and a merge) \u2014 is the lesson's situation, even if the user does not mention the lesson. Not for shared topic words, not for preferences that would not change the agent's next actions, not if already in context. When unsure, include none.
2363
+ - "serve": at most ONE skill or document, injected in full (long). Serve only when this prompt STARTS or clearly redirects the workflow the item is the procedure for, and it is not already in context. A narrow question (how to find one value, why one command misbehaves, what one step needs) is answered by atoms, never by serving the whole skill. Follow-ups, approvals, status questions, chatter, and continuing work already under way need none.
2364
+ - "rules": at most ${MAX_RULES} ATOMS, injected in full. Include an atom only when what the agent will DO next \u2014 including the steps the work it starts normally leads to (a ticket ends in a PR and a report; a fix ends in evidence and a merge) \u2014 is the atom's situation, even if nobody mentions it. A card belongs to the step the agent is at or about to start. Not for shared topic words, not for items that would not change the agent's next actions, not if already in context. When unsure, include none.
2124
2365
  - "hints": up to 2 other possibly relevant document ids, shown as titles only.
2125
2366
 
2126
- Only use ids from the library. Output exactly one line of JSON and nothing else: {"serve": "<id or null>", "rules": ["<lesson id>", ...], "hints": ["<id>", ...]}`;
2367
+ Only use ids from the library. Output exactly one line of JSON and nothing else: {"serve": "<id or null>", "rules": ["<atom id>", ...], "hints": ["<id>", ...]}`;
2127
2368
  }
2128
2369
  });
2129
2370
 
@@ -2659,7 +2900,7 @@ ${sep}${rows.join("\n")}` : null;
2659
2900
  }
2660
2901
  },
2661
2902
  {
2662
- // Customer-adjacent identifiers named as such: customerId, loan account XUCS389, /loans/XUCS389, accountId=ABCD1234.
2903
+ // Customer-adjacent identifiers named as such: customerId, loan account ABC1234, /loans/ABC1234, accountId=ABCD1234.
2663
2904
  // Only values with a digit (a type name or a word in a spec is left alone).
2664
2905
  kind: "customer-id",
2665
2906
  marker: "[CUSTOMER-ID]",
@@ -2817,17 +3058,27 @@ A lesson is read by agents on other tasks, months from now. Write the rule, not
2817
3058
 
2818
3059
  ## Where it goes
2819
3060
 
2820
- Every entry is a whole document (a skill, a spec, a policy). Prefer editing an existing document
2821
- over creating one, and aim the edit: "anchor" names the heading (from its headings list) the text
2822
- belongs under, so it lands in the right part of the document.
2823
-
2824
- Steering and approach lessons (a, e) are the exception: each is its own short lesson. Use op
2825
- "create" with kind "rule": a title naming the behaviour, a "when" naming the situations it applies
2826
- in (as the user would phrase a request there, even one that never mentions it), and a body of at
2827
- most about 120 words: the rule, why, and when it was learned. Do not append such a lesson inside a
2828
- long skill or procedure: a rule buried in a long document goes unfollowed even when the document is
2829
- loaded, and the user ends up repeating it. If a short rule in the list below already says it, append
2830
- to that rule instead. Traps, procedures and facts (b, c, d) still go into the document they belong to.
3061
+ A lesson is an ATOM: one short item of its own, served on its own when the work reaches the moment
3062
+ it is about. Never append a lesson, a trap or a fact to a long skill or procedure: a line buried in a
3063
+ long document goes unfollowed even when the document is loaded, and every narrow question then loads
3064
+ the whole document. Use op "create" with:
3065
+ - kind "rule" for steering and approach lessons (a, e);
3066
+ - kind "fact" for how something is: a trap and what worked instead, a tool's or API's quirk,
3067
+ another team's process (b, c);
3068
+ - kind "card" for the detail of one step of a workflow a skill describes (how a step is done, what
3069
+ it needs), with "partOf" the skill's id and "step" the skill's heading anchor (d, or a step that
3070
+ went wrong and how it is done right).
3071
+ Each atom: a title naming the thing; a "when" naming the moment an agent needs it, as it would show
3072
+ in the work or in a request there (even one that never mentions it), not a topic label; a body of
3073
+ at most about 150 words: what to do or know, and why. Add "triggers" only when a tool call reliably
3074
+ marks that moment: [{"tool": "Bash", "match": "<regex>"}], a case-insensitive regular expression over
3075
+ the call's input (the shell command for Bash, else its strings), specific enough that it rarely
3076
+ fires when the atom is not needed (the command with the subcommand or flag it is about, never a bare
3077
+ program name).
3078
+ If an atom in the list below already says it, edit that atom instead (op "append" or "replace" on
3079
+ its id): one atom per thing. Edit a skill or other long document only when its workflow itself
3080
+ changes (a step is added, removed or reordered, or a step's one-line summary is wrong), and aim the
3081
+ edit: "anchor" names the heading (from its headings list) it belongs under.
2831
3082
 
2832
3083
  Library documents relevant to this session:
2833
3084
  ${index}
@@ -2874,8 +3125,10 @@ At most ${max} suggestions. Schema:
2874
3125
  "suggestions": [{"target": {"sectionId"?: string, "layer"?: string},
2875
3126
  "op": {"op": "append", "text": string, "condition"?: string, "anchor"?: string}
2876
3127
  | {"op": "replace", "find": string, "text": string, "anchor"?: string}
2877
- | {"op": "create", "section": {"kind": "skill"|"procedure"|"spec"|"verification"|"rule"|"guardrail"|"reference",
3128
+ | {"op": "create", "section": {"kind": "rule"|"fact"|"card"|"skill"|"procedure"|"spec"|"verification"|"guardrail"|"reference",
2878
3129
  "title": string, "body": string, "when": string,
3130
+ "triggers"?: [{"tool": string, "match": string}],
3131
+ "partOf"?: string, "step"?: string,
2879
3132
  "paths"?: string[], "entities"?: string[], "skills"?: string[]}}
2880
3133
  | {"op": "param", "key": string, "value": string|number|boolean}
2881
3134
  | {"op": "situation", "text": string},
@@ -2977,9 +3230,24 @@ function parseOp(raw) {
2977
3230
  const body = clean(s.body);
2978
3231
  const when = clean(s.when);
2979
3232
  if (!title || !body) return null;
3233
+ const atom = isAtom({ kind, body });
3234
+ const toolTriggers = atom ? (Array.isArray(s.triggers) ? s.triggers : []).map(validTrigger).filter((t) => !!t).slice(0, 4) : [];
3235
+ const partOf2 = atom ? clean(s.partOf) : "";
3236
+ const step = partOf2 ? clean(s.step).replace(/^[§#]/, "") : "";
2980
3237
  return {
2981
3238
  op: "create",
2982
- section: { kind, title, body, when: when || title, paths: strList(s.paths), entities: strList(s.entities).map((e) => e.toLowerCase()), skills: strList(s.skills) }
3239
+ section: {
3240
+ kind,
3241
+ title,
3242
+ body,
3243
+ when: when || title,
3244
+ paths: strList(s.paths),
3245
+ entities: strList(s.entities).map((e) => e.toLowerCase()),
3246
+ skills: strList(s.skills),
3247
+ ...toolTriggers.length ? { toolTriggers } : {},
3248
+ ...partOf2 ? { partOf: partOf2 } : {},
3249
+ ...step ? { step } : {}
3250
+ }
2983
3251
  };
2984
3252
  }
2985
3253
  case "situation": {
@@ -3011,6 +3279,10 @@ function parseReflection(raw, opts = { layers: [] }) {
3011
3279
  let sectionId = typeof t.sectionId === "string" && t.sectionId.trim() ? t.sectionId.trim() : void 0;
3012
3280
  if (op.op !== "create" && op.op !== "param" && (!sectionId || opts.knownSectionIds && !opts.knownSectionIds.has(sectionId))) continue;
3013
3281
  if (op.op === "create") sectionId = void 0;
3282
+ if (op.op === "create" && op.section.partOf && opts.knownSectionIds && !opts.knownSectionIds.has(op.section.partOf)) {
3283
+ const { partOf: _p, step: _s, ...rest } = op.section;
3284
+ op.section = rest;
3285
+ }
3014
3286
  const layerRaw = typeof t.layer === "string" ? t.layer.trim() : "";
3015
3287
  const layer = opts.layers.includes(layerRaw) ? layerRaw : void 0;
3016
3288
  out.push({
@@ -3046,6 +3318,7 @@ var REFLECT_MARKER, ENVIRONMENT_RECHECK_DAYS, SIGNAL_WORDS, REFLECT_SCHEMA, KIND
3046
3318
  var init_reflect = __esm({
3047
3319
  "../core/src/v2/reflect.ts"() {
3048
3320
  "use strict";
3321
+ init_atoms();
3049
3322
  init_guidelines();
3050
3323
  init_redact();
3051
3324
  init_types();
@@ -3080,7 +3353,7 @@ var init_reflect = __esm({
3080
3353
  }
3081
3354
  }
3082
3355
  };
3083
- KINDS = ["skill", "procedure", "spec", "verification", "rule", "guardrail", "reference", "tool"];
3356
+ KINDS = ["skill", "procedure", "spec", "verification", "rule", "guardrail", "reference", "tool", "fact", "card"];
3084
3357
  anchorOf = (v) => {
3085
3358
  const a = typeof v === "string" ? clean(v).replace(/^§/, "").replace(/^#/, "") : "";
3086
3359
  return a ? { anchor: a } : {};
@@ -3211,6 +3484,7 @@ var init_v2 = __esm({
3211
3484
  init_text_index();
3212
3485
  init_engine();
3213
3486
  init_router();
3487
+ init_atoms();
3214
3488
  init_reflect();
3215
3489
  init_digest();
3216
3490
  init_reflect_context();
@@ -3251,8 +3525,8 @@ import fs5 from "node:fs";
3251
3525
  function version() {
3252
3526
  for (const rel of ["../package.json", "../../package.json"]) {
3253
3527
  try {
3254
- const file = new URL(rel, import.meta.url);
3255
- const pkg = JSON.parse(fs5.readFileSync(file, "utf8"));
3528
+ const file2 = new URL(rel, import.meta.url);
3529
+ const pkg = JSON.parse(fs5.readFileSync(file2, "utf8"));
3256
3530
  if (pkg.name === "@bunshin-cc/bunshin" && pkg.version) return pkg.version;
3257
3531
  } catch {
3258
3532
  }
@@ -3322,334 +3596,52 @@ var init_api = __esm({
3322
3596
  }
3323
3597
  });
3324
3598
 
3325
- // src/v2/repo.ts
3326
- import fs6 from "node:fs";
3327
- import path5 from "node:path";
3328
- import { execFileSync } from "node:child_process";
3329
- function git(cwd, args, timeout = 1500) {
3330
- try {
3331
- return execFileSync("git", ["-C", cwd, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout, maxBuffer: 64 * 1024 * 1024 });
3332
- } catch {
3333
- return null;
3334
- }
3335
- }
3336
- function repoRoot(cwd, storeRoot) {
3337
- const key = `${cwd}
3338
- ${storeRoot ?? ""}`;
3339
- const hit = rootCache.get(key);
3340
- if (hit) return hit;
3341
- const top = git(cwd, ["rev-parse", "--show-toplevel"])?.trim();
3342
- let root = top || "";
3343
- if (!root && storeRoot && path5.basename(storeRoot) === ".bunshin") {
3344
- const parent = path5.dirname(storeRoot);
3345
- if (path5.resolve(cwd).startsWith(path5.resolve(parent))) root = parent;
3346
- }
3347
- root = root || path5.resolve(cwd);
3348
- rootCache.set(key, root);
3349
- return root;
3350
- }
3351
- function parseRemote(url) {
3352
- const clean2 = url.trim().replace(/\.git$/, "").replace(/\/+$/, "");
3353
- if (!clean2) return null;
3354
- const scp = clean2.match(/^[^@/\s]+@[^:/\s]+:(.+)$/);
3355
- const pathPart = scp ? scp[1] : (() => {
3356
- try {
3357
- return new URL(clean2).pathname;
3358
- } catch {
3359
- return clean2;
3360
- }
3361
- })();
3362
- const segs = pathPart.split("/").filter(Boolean);
3363
- if (segs.length >= 2) return `${segs[segs.length - 2]}/${segs[segs.length - 1]}`;
3364
- return segs[0] ?? null;
3365
- }
3366
- function repoName(root) {
3367
- const url = git(root, ["remote", "get-url", "origin"]);
3368
- return url && parseRemote(url) || path5.basename(root);
3369
- }
3370
- function repoCommit(root) {
3371
- return git(root, ["rev-parse", "HEAD"])?.trim() || void 0;
3372
- }
3373
- function listDocs(root) {
3374
- const listed = git(root, ["ls-files", "-co", "--exclude-standard", "-z"], 3e3);
3375
- if (listed !== null) return [...new Set(listed.split("\0").filter(Boolean).filter(isDoc))].filter((rel) => fs6.existsSync(path5.join(root, rel)) && !deployedSkill(root, rel)).sort();
3376
- const out = [];
3377
- let visited = 0;
3378
- const walk = (dir2, rel, depth) => {
3379
- if (depth > 8 || visited++ > 2e4) return;
3380
- let entries;
3381
- try {
3382
- entries = fs6.readdirSync(dir2, { withFileTypes: true });
3383
- } catch {
3384
- return;
3385
- }
3386
- for (const e of entries) {
3387
- if (e.isDirectory()) {
3388
- if (!SKIP_DIRS.has(e.name) && !fs6.existsSync(path5.join(dir2, e.name, ".git"))) walk(path5.join(dir2, e.name), rel ? `${rel}/${e.name}` : e.name, depth + 1);
3389
- } else if (e.isFile()) {
3390
- const r = rel ? `${rel}/${e.name}` : e.name;
3391
- if (isDoc(r) && !deployedSkill(root, r)) out.push(r);
3392
- }
3393
- }
3394
- };
3395
- walk(root, "", 0);
3396
- return out.sort();
3397
- }
3398
- function indexWorkingTree(v2, config, cwd, opts = {}) {
3399
- const root = repoRoot(cwd, v2.store.root);
3400
- const now = opts.now ?? Date.now();
3401
- const cached = v2.readRepoIndex(root);
3402
- const ownerTeam = config.ownerTeam || config.orgUnit || "unknown";
3403
- const source = sourceFor(root, v2.store.root);
3404
- const sameRepo = cached && cached.ownerTeam === ownerTeam && cached.format === INDEX_FORMAT;
3405
- const repo = sameRepo && cached.repo && !opts.force ? cached.repo : repoName(root);
3406
- const fresh = sameRepo && cached.repo === repo && cached.paths && cached.listedAt && now - Date.parse(cached.listedAt) < LIST_TTL_MS && !opts.force;
3407
- const paths = fresh ? cached.paths : listDocs(root);
3408
- let changed = !fresh || !sameRepo || cached.repo !== repo;
3409
- const files = {};
3410
- for (const rel of paths) {
3411
- const abs = path5.join(root, rel);
3412
- let stat;
3413
- try {
3414
- stat = fs6.statSync(abs);
3415
- } catch {
3416
- changed = true;
3417
- continue;
3418
- }
3419
- const prev = sameRepo && cached.repo === repo ? cached.files[rel] : void 0;
3420
- if (prev && prev.mtimeMs === stat.mtimeMs && prev.size === stat.size) {
3421
- files[rel] = prev;
3422
- continue;
3423
- }
3424
- changed = true;
3425
- try {
3426
- const text2 = fs6.readFileSync(abs, "utf8");
3427
- files[rel] = { mtimeMs: stat.mtimeMs, size: stat.size, sections: parseRepoDoc({ repo, path: rel, text: text2 }, { orgId: config.orgId, ownerTeam, layer: source ? sourceLayer(source) : "org" }) };
3428
- } catch {
3429
- }
3430
- }
3431
- const index = {
3432
- format: INDEX_FORMAT,
3433
- repo,
3434
- ownerTeam,
3435
- listedAt: fresh ? cached.listedAt : new Date(now).toISOString(),
3436
- paths,
3437
- files
3438
- };
3439
- if (changed) {
3440
- try {
3441
- v2.writeRepoIndex(root, index);
3442
- } catch {
3443
- }
3599
+ // ../core/src/types.ts
3600
+ var init_types2 = __esm({
3601
+ "../core/src/types.ts"() {
3602
+ "use strict";
3444
3603
  }
3445
- return { root, index, sections: Object.values(files).flatMap((f) => f.sections) };
3446
- }
3447
- function relativeToRoot(root, file, cwd = root) {
3448
- if (!file) return null;
3449
- const abs = path5.isAbsolute(file) ? file : path5.resolve(cwd, file);
3450
- let real = abs;
3451
- let realRoot = root;
3452
- try {
3453
- realRoot = fs6.realpathSync(root);
3454
- } catch {
3604
+ });
3605
+
3606
+ // ../core/src/gate.ts
3607
+ var CURRENT_CHAT_PREFIX, ANAPHORIC_QUESTION;
3608
+ var init_gate = __esm({
3609
+ "../core/src/gate.ts"() {
3610
+ "use strict";
3611
+ CURRENT_CHAT_PREFIX = "(?:(?:so\\s+)?(?:in|within)\\s+(?:this|the)\\s+(?:chat|conversation|session)\\s*,?\\s*)?";
3612
+ ANAPHORIC_QUESTION = new RegExp(
3613
+ "^" + CURRENT_CHAT_PREFIX + "(?:(?:and\\s+)?(?:does|do|did|is|are|was|were|can|could|would|will|has|have|had)\\s+.*\\b(?:this|that|it|these|those|they)\\b.*|(?:and\\s+)?(?:does|do|did|is|are|was|were|can|could|would|will|has|have|had)\\b.*\\b(?:also|too|as\\s+well)\\b.*|(?:what|why|how|where|when)\\s+(?:does|do|did|is|are|was|were)\\s+(?:this|that|it|these|those|they)\\b.*|(?:can|could|would)\\s+you\\s+(?:explain|clarify|show)\\s+(?:this|that|it)\\b.*)$",
3614
+ "i"
3615
+ );
3455
3616
  }
3456
- try {
3457
- real = fs6.realpathSync(abs);
3458
- } catch {
3459
- try {
3460
- real = path5.join(fs6.realpathSync(path5.dirname(abs)), path5.basename(abs));
3461
- } catch {
3462
- }
3617
+ });
3618
+
3619
+ // ../core/src/metrics.ts
3620
+ var init_metrics = __esm({
3621
+ "../core/src/metrics.ts"() {
3622
+ "use strict";
3463
3623
  }
3464
- for (const [r, f] of [
3465
- [realRoot, real],
3466
- [root, abs]
3467
- ]) {
3468
- const rel = path5.relative(r, f);
3469
- if (rel && !rel.startsWith("..") && !path5.isAbsolute(rel)) return rel.split(path5.sep).join("/");
3624
+ });
3625
+
3626
+ // ../core/src/lesson/id.ts
3627
+ var init_id = __esm({
3628
+ "../core/src/lesson/id.ts"() {
3629
+ "use strict";
3470
3630
  }
3471
- return null;
3472
- }
3473
- var DOC_NAMES, SKIP_DIRS, LIST_TTL_MS, rootCache, isDoc, deployedSkill, INDEX_FORMAT;
3474
- var init_repo = __esm({
3475
- "src/v2/repo.ts"() {
3631
+ });
3632
+
3633
+ // ../core/src/lesson/markdown.ts
3634
+ var init_markdown2 = __esm({
3635
+ "../core/src/lesson/markdown.ts"() {
3476
3636
  "use strict";
3477
- init_v22();
3478
- init_source();
3479
- DOC_NAMES = /* @__PURE__ */ new Set(["spec.md", "testing.md", "skill.md"]);
3480
- SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", "dist", ".bunshin"]);
3481
- LIST_TTL_MS = 6e4;
3482
- rootCache = /* @__PURE__ */ new Map();
3483
- isDoc = (rel) => {
3484
- const parts = rel.split("/");
3485
- if (parts.some((p) => SKIP_DIRS.has(p))) return false;
3486
- return DOC_NAMES.has(parts[parts.length - 1].toLowerCase());
3487
- };
3488
- deployedSkill = (root, rel) => /(^|\/)SKILL\.md$/i.test(rel) && fs6.existsSync(path5.join(root, path5.posix.dirname(rel), ".bunshin.json"));
3489
- INDEX_FORMAT = 2;
3490
3637
  }
3491
3638
  });
3492
3639
 
3493
- // src/v2/source.ts
3494
- var source_exports = {};
3495
- __export(source_exports, {
3496
- cwdInPool: () => cwdInPool,
3497
- inPool: () => inPool,
3498
- listFolders: () => listFolders,
3499
- projectRootFor: () => projectRootFor,
3500
- select: () => select,
3501
- sourceFor: () => sourceFor,
3502
- storeHome: () => storeHome,
3503
- topFolder: () => topFolder
3504
- });
3505
- import fs7 from "node:fs";
3506
- import path6 from "node:path";
3507
- import { execFileSync as execFileSync2 } from "node:child_process";
3508
- function storeHome(storeRoot) {
3509
- return path6.dirname(path6.resolve(storeRoot));
3510
- }
3511
- function topFolder(cwd, storeRoot) {
3512
- const rel = path6.relative(storeHome(storeRoot), path6.resolve(cwd));
3513
- if (!rel || rel.startsWith("..") || path6.isAbsolute(rel)) return "";
3514
- return rel.split(path6.sep)[0] ?? "";
3515
- }
3516
- function inPool(selection, folder) {
3517
- if (!folder || !selection) return true;
3518
- if (selection.exclude?.includes(folder)) return false;
3519
- return selection.only ? selection.only.includes(folder) : true;
3520
- }
3521
- function cwdInPool(config, cwd, storeRoot) {
3522
- return inPool(config.sources, topFolder(cwd, storeRoot));
3523
- }
3524
- function git2(cwd, args) {
3525
- try {
3526
- return execFileSync2("git", ["-C", cwd, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 1500 }).trim() || null;
3527
- } catch {
3528
- return null;
3529
- }
3530
- }
3531
- function sourceFor(cwd, storeRoot, ctx) {
3532
- if (ctx?.kind === "robot") return sourceId("robot", ctx.id);
3533
- const key = `${path6.resolve(cwd)}
3534
- ${storeRoot}`;
3535
- if (sourceCache.has(key)) return sourceCache.get(key);
3536
- const found = findSource(cwd, storeRoot);
3537
- sourceCache.set(key, found);
3538
- return found;
3539
- }
3540
- function findSource(cwd, storeRoot) {
3541
- const home = storeHome(storeRoot);
3542
- const top = git2(cwd, ["rev-parse", "--show-toplevel"]);
3543
- if (top) {
3544
- const remote = git2(top, ["remote", "get-url", "origin"]);
3545
- const named = remote ? parseRemote(remote) : null;
3546
- if (named) return sourceId("repo", named);
3547
- const rel = path6.relative(home, top);
3548
- return sourceId("folder", rel && !rel.startsWith("..") && !path6.isAbsolute(rel) ? rel.split(path6.sep).join("/") : path6.basename(top));
3549
- }
3550
- const folder = topFolder(cwd, storeRoot);
3551
- return folder ? sourceId("folder", folder) : void 0;
3552
- }
3553
- function projectRootFor(cwd, storeRoot) {
3554
- const home = storeHome(storeRoot);
3555
- const top = git2(cwd, ["rev-parse", "--show-toplevel"]);
3556
- if (top) {
3557
- const rel = path6.relative(home, top);
3558
- if (!rel.startsWith("..") && !path6.isAbsolute(rel)) return top;
3559
- }
3560
- const folder = topFolder(cwd, storeRoot);
3561
- return folder ? path6.join(home, folder) : home;
3562
- }
3563
- function listFolders(storeRoot, selection, opts = {}) {
3564
- const home = storeHome(storeRoot);
3565
- let names = [];
3566
- try {
3567
- names = fs7.readdirSync(home, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name).sort((a, b) => a.localeCompare(b));
3568
- } catch {
3569
- }
3570
- return names.map((folder) => ({
3571
- folder,
3572
- included: inPool(selection, folder),
3573
- ...opts.sources ? { source: sourceFor(path6.join(home, folder), storeRoot) } : {}
3574
- }));
3575
- }
3576
- function select(current, action, folders) {
3577
- const uniq = (xs) => [...new Set(xs)].sort((a, b) => a.localeCompare(b));
3578
- const only = current?.only;
3579
- const exclude = current?.exclude ?? [];
3580
- let next;
3581
- switch (action) {
3582
- case "all":
3583
- return void 0;
3584
- case "only":
3585
- next = { only: uniq(folders) };
3586
- break;
3587
- case "include":
3588
- next = { ...only ? { only: uniq([...only, ...folders]) } : {}, exclude: exclude.filter((f) => !folders.includes(f)) };
3589
- break;
3590
- case "exclude":
3591
- next = { ...only ? { only: only.filter((f) => !folders.includes(f)) } : {}, exclude: uniq([...exclude, ...folders]) };
3592
- break;
3593
- }
3594
- if (!next.exclude?.length) delete next.exclude;
3595
- return next.only || next.exclude ? next : void 0;
3596
- }
3597
- var sourceCache;
3598
- var init_source = __esm({
3599
- "src/v2/source.ts"() {
3600
- "use strict";
3601
- init_v22();
3602
- init_repo();
3603
- sourceCache = /* @__PURE__ */ new Map();
3604
- }
3605
- });
3606
-
3607
- // ../core/src/types.ts
3608
- var init_types2 = __esm({
3609
- "../core/src/types.ts"() {
3610
- "use strict";
3611
- }
3612
- });
3613
-
3614
- // ../core/src/gate.ts
3615
- var CURRENT_CHAT_PREFIX, ANAPHORIC_QUESTION;
3616
- var init_gate = __esm({
3617
- "../core/src/gate.ts"() {
3618
- "use strict";
3619
- CURRENT_CHAT_PREFIX = "(?:(?:so\\s+)?(?:in|within)\\s+(?:this|the)\\s+(?:chat|conversation|session)\\s*,?\\s*)?";
3620
- ANAPHORIC_QUESTION = new RegExp(
3621
- "^" + CURRENT_CHAT_PREFIX + "(?:(?:and\\s+)?(?:does|do|did|is|are|was|were|can|could|would|will|has|have|had)\\s+.*\\b(?:this|that|it|these|those|they)\\b.*|(?:and\\s+)?(?:does|do|did|is|are|was|were|can|could|would|will|has|have|had)\\b.*\\b(?:also|too|as\\s+well)\\b.*|(?:what|why|how|where|when)\\s+(?:does|do|did|is|are|was|were)\\s+(?:this|that|it|these|those|they)\\b.*|(?:can|could|would)\\s+you\\s+(?:explain|clarify|show)\\s+(?:this|that|it)\\b.*)$",
3622
- "i"
3623
- );
3624
- }
3625
- });
3626
-
3627
- // ../core/src/metrics.ts
3628
- var init_metrics = __esm({
3629
- "../core/src/metrics.ts"() {
3630
- "use strict";
3631
- }
3632
- });
3633
-
3634
- // ../core/src/lesson/id.ts
3635
- var init_id = __esm({
3636
- "../core/src/lesson/id.ts"() {
3637
- "use strict";
3638
- }
3639
- });
3640
-
3641
- // ../core/src/lesson/markdown.ts
3642
- var init_markdown2 = __esm({
3643
- "../core/src/lesson/markdown.ts"() {
3644
- "use strict";
3645
- }
3646
- });
3647
-
3648
- // ../core/src/lesson/index.ts
3649
- var init_lesson = __esm({
3650
- "../core/src/lesson/index.ts"() {
3651
- "use strict";
3652
- }
3640
+ // ../core/src/lesson/index.ts
3641
+ var init_lesson = __esm({
3642
+ "../core/src/lesson/index.ts"() {
3643
+ "use strict";
3644
+ }
3653
3645
  });
3654
3646
 
3655
3647
  // ../core/src/serve/score.ts
@@ -4036,38 +4028,38 @@ var init_reconcile2 = __esm({
4036
4028
  }
4037
4029
  });
4038
4030
 
4039
- // ../core/src/examples/apr.ts
4040
- function aprScenario(now = (/* @__PURE__ */ new Date()).toISOString()) {
4031
+ // ../core/src/examples/demo.ts
4032
+ function demoScenario(now = (/* @__PURE__ */ new Date()).toISOString()) {
4041
4033
  const constraint = {
4042
4034
  id: "l_00000001",
4043
4035
  kind: "fact",
4044
- title: "Collections must clear negative balances before account closure",
4045
- gist: "Negative-balance accounts require manual handling by Collections before they can close.",
4046
- content: "When the company owes a customer money, Collections clears the negative balance through a manual process. Account closure automation must not close these accounts. Route them to Collections and wait for confirmation that the balance has been cleared.",
4047
- tags: ["account-closure", "negative-balance", "collections", "manual-process"],
4036
+ title: "Legal must release a legal hold before workspace deletion",
4037
+ gist: "Workspaces under a legal hold must be preserved until Legal releases the hold by hand.",
4038
+ content: "When a customer is part of a dispute or investigation, Legal places their workspace under a legal hold through a manual process. Workspace deletion automation must not delete these workspaces. Route them to Legal and wait for confirmation that the hold has been released.",
4039
+ tags: ["workspace-deletion", "legal-hold", "legal", "manual-process"],
4048
4040
  status: "active",
4049
4041
  clearance: "org",
4050
4042
  version: 1,
4051
4043
  updatedAt: now,
4052
- provenance: { orgId: APR_ENGINEER.orgId, userId: "ops", role: "collections-analyst", orgUnit: "operations/collections", harness: "other", createdAt: now },
4044
+ provenance: { orgId: DEMO_ENGINEER.orgId, userId: "counsel", role: "legal-counsel", orgUnit: "legal/commercial", harness: "other", createdAt: now },
4053
4045
  stats: { served: 0, used: 0, helped: 0, hurt: 0 }
4054
4046
  };
4055
4047
  const workflow = {
4056
4048
  ...constraint,
4057
4049
  id: "l_00000002",
4058
4050
  kind: "workflow",
4059
- title: "Implement account closure with a Collections handoff",
4060
- gist: "Check the balance, branch to manual handling when needed, and verify both closure paths.",
4061
- content: "Use this workflow when building APR opt-out account closure automation.",
4062
- provenance: { ...constraint.provenance, userId: "payments-lead", role: "backend-engineer", orgUnit: "engineering/payments" },
4063
- preconditions: ["Read the current account balance", "Confirm the Collections handoff with its owner"],
4051
+ title: "Implement workspace deletion with a legal hold check",
4052
+ gist: "Check for a hold, branch to Legal when needed, and verify both deletion paths.",
4053
+ content: "Use this workflow when building workspace deletion automation after a subscription is cancelled.",
4054
+ provenance: { ...constraint.provenance, userId: "platform-lead", role: "backend-engineer", orgUnit: "engineering/platform" },
4055
+ preconditions: ["Read the workspace's current legal hold status", "Confirm the Legal handoff with its owner"],
4064
4056
  steps: [
4065
- { n: 1, action: "Read the balance before attempting account closure", verify: "The decision uses the latest balance." },
4066
- { n: 2, action: "For a negative balance, queue manual handling and leave the account open", verify: "The Collections handoff exists and no closure request was sent." },
4067
- { n: 3, action: "Close eligible accounts only after all closure prerequisites pass", verify: "The account status changes to closed only on the eligible branch." },
4068
- { n: 4, action: "Test negative, zero, and positive balances, including a retried handoff", verify: "Negative balances stay open; repeated delivery does not duplicate the handoff." }
4057
+ { n: 1, action: "Read the legal hold status before attempting workspace deletion", verify: "The decision uses the latest hold status." },
4058
+ { n: 2, action: "For a workspace under legal hold, queue it for Legal and keep its data", verify: "The Legal handoff exists and no deletion request was sent." },
4059
+ { n: 3, action: "Delete eligible workspaces only after all deletion prerequisites pass", verify: "Data is deleted only on the eligible branch." },
4060
+ { n: 4, action: "Test held, released, and never-held workspaces, including a retried handoff", verify: "Held workspaces keep their data; repeated delivery does not duplicate the handoff." }
4069
4061
  ],
4070
- outcome: "Eligible accounts close and negative-balance accounts remain open for Collections."
4062
+ outcome: "Eligible workspaces are deleted and workspaces under legal hold are preserved for Legal."
4071
4063
  };
4072
4064
  return {
4073
4065
  constraint,
@@ -4075,25 +4067,25 @@ function aprScenario(now = (/* @__PURE__ */ new Date()).toISOString()) {
4075
4067
  lessons: [
4076
4068
  constraint,
4077
4069
  workflow,
4078
- { ...constraint, id: "l_00000003", title: "Board plan for APR pricing", gist: "Confidential APR strategy", content: "Executive-only pricing strategy.", clearance: "csuite", provenance: { ...constraint.provenance, userId: "ceo", role: "ceo", orgUnit: "executive" } },
4079
- { ...constraint, id: "l_00000004", title: "Facilities visitor badges", gist: "Visitor badges require manual approval.", content: "Facilities must approve visitor badges.", tags: ["facilities", "badges"], provenance: { ...constraint.provenance, userId: "facilities", orgUnit: "facilities/london" } },
4080
- { ...constraint, id: "l_00000005", title: "Old account closure procedure", status: "superseded" },
4070
+ { ...constraint, id: "l_00000003", title: "Board plan for next year's pricing", gist: "Confidential pricing strategy", content: "Executive-only pricing strategy.", clearance: "csuite", provenance: { ...constraint.provenance, userId: "ceo", role: "ceo", orgUnit: "executive" } },
4071
+ { ...constraint, id: "l_00000004", title: "Facilities visitor badges", gist: "Visitor badges require manual approval.", content: "Facilities must approve visitor badges.", tags: ["facilities", "badges"], provenance: { ...constraint.provenance, userId: "facilities", orgUnit: "facilities/hq" } },
4072
+ { ...constraint, id: "l_00000005", title: "Old workspace deletion procedure", status: "superseded" },
4081
4073
  { ...constraint, id: "l_00000006", provenance: { ...constraint.provenance, orgId: "another-company" } }
4082
4074
  ]
4083
4075
  };
4084
4076
  }
4085
- var APR_TASK, APR_ENGINEER;
4086
- var init_apr = __esm({
4087
- "../core/src/examples/apr.ts"() {
4077
+ var DEMO_TASK, DEMO_ENGINEER;
4078
+ var init_demo = __esm({
4079
+ "../core/src/examples/demo.ts"() {
4088
4080
  "use strict";
4089
- APR_TASK = "Implement APR opt-out: automatically close the customer's account and stop billing when they reject the new interest rate.";
4090
- APR_ENGINEER = {
4081
+ DEMO_TASK = "Automate workspace deletion: when a customer cancels their subscription, delete their workspace and its data after 30 days.";
4082
+ DEMO_ENGINEER = {
4091
4083
  orgId: "org_demo",
4092
4084
  userId: "engineer",
4093
4085
  role: "backend-engineer",
4094
- orgUnit: "engineering/payments",
4086
+ orgUnit: "engineering/platform",
4095
4087
  clearance: "team",
4096
- responsibilities: ["account closure", "APR opt-out", "billing"]
4088
+ responsibilities: ["workspace deletion", "subscription cancellation", "data retention"]
4097
4089
  };
4098
4090
  }
4099
4091
  });
@@ -4119,7 +4111,7 @@ var init_src = __esm({
4119
4111
  init_reflect2();
4120
4112
  init_metaReflect();
4121
4113
  init_reconcile2();
4122
- init_apr();
4114
+ init_demo();
4123
4115
  }
4124
4116
  });
4125
4117
 
@@ -4132,8 +4124,8 @@ __export(store_exports, {
4132
4124
  hexId: () => hexId,
4133
4125
  normalizeSession: () => normalizeSession
4134
4126
  });
4135
- import fs8 from "node:fs";
4136
- import path7 from "node:path";
4127
+ import fs6 from "node:fs";
4128
+ import path5 from "node:path";
4137
4129
  import { createHash as createHash2, randomBytes as randomBytes3 } from "node:crypto";
4138
4130
  function hexId(prefix) {
4139
4131
  return `${prefix}_${randomBytes3(6).toString("hex")}`;
@@ -4167,12 +4159,12 @@ var init_store2 = __esm({
4167
4159
  V2Store = class {
4168
4160
  constructor(store) {
4169
4161
  this.store = store;
4170
- this.dir = path7.join(store.root, "v2");
4162
+ this.dir = path5.join(store.root, "v2");
4171
4163
  }
4172
4164
  store;
4173
4165
  dir;
4174
4166
  p(...parts) {
4175
- return path7.join(this.dir, ...parts);
4167
+ return path5.join(this.dir, ...parts);
4176
4168
  }
4177
4169
  // ── context / bundle / params ──
4178
4170
  readContext() {
@@ -4253,9 +4245,9 @@ var init_store2 = __esm({
4253
4245
  const dir2 = this.p("sessions");
4254
4246
  if (!fileExists(dir2)) return [];
4255
4247
  const out = [];
4256
- for (const f of fs8.readdirSync(dir2)) {
4248
+ for (const f of fs6.readdirSync(dir2)) {
4257
4249
  if (!f.endsWith(".json") || f === "current.json") continue;
4258
- const raw = readJson(path7.join(dir2, f), null);
4250
+ const raw = readJson(path5.join(dir2, f), null);
4259
4251
  if (raw?.sessionId) out.push(normalizeSession(raw.sessionId, raw));
4260
4252
  }
4261
4253
  return out;
@@ -4283,7 +4275,7 @@ var init_store2 = __esm({
4283
4275
  let at = raw.at;
4284
4276
  if (!at) {
4285
4277
  try {
4286
- at = fs8.statSync(this.p("outcome", `${fileSafe(sessionId)}.json`)).mtime.toISOString();
4278
+ at = fs6.statSync(this.p("outcome", `${fileSafe(sessionId)}.json`)).mtime.toISOString();
4287
4279
  } catch {
4288
4280
  at = (/* @__PURE__ */ new Date()).toISOString();
4289
4281
  }
@@ -4309,14 +4301,14 @@ var init_store2 = __esm({
4309
4301
  }
4310
4302
  /** Exclusive lock file; returns a release function, or null when another process holds it. */
4311
4303
  tryLock(name, staleMs = 10 * 6e4) {
4312
- const file = this.p("locks", `${fileSafe(name)}.lock`);
4313
- ensureDir(path7.dirname(file));
4304
+ const file2 = this.p("locks", `${fileSafe(name)}.lock`);
4305
+ ensureDir(path5.dirname(file2));
4314
4306
  for (let attempt = 0; attempt < 2; attempt++) {
4315
4307
  try {
4316
- fs8.writeFileSync(file, String(process.pid), { flag: "wx" });
4308
+ fs6.writeFileSync(file2, String(process.pid), { flag: "wx" });
4317
4309
  return () => {
4318
4310
  try {
4319
- fs8.unlinkSync(file);
4311
+ fs6.unlinkSync(file2);
4320
4312
  } catch {
4321
4313
  }
4322
4314
  };
@@ -4324,8 +4316,8 @@ var init_store2 = __esm({
4324
4316
  if (err.code !== "EEXIST") return null;
4325
4317
  let stale = false;
4326
4318
  try {
4327
- const owner = Number(fs8.readFileSync(file, "utf8"));
4328
- const age = Date.now() - fs8.statSync(file).mtimeMs;
4319
+ const owner = Number(fs6.readFileSync(file2, "utf8"));
4320
+ const age = Date.now() - fs6.statSync(file2).mtimeMs;
4329
4321
  if (age > staleMs) stale = true;
4330
4322
  else if (Number.isInteger(owner) && owner > 0) {
4331
4323
  try {
@@ -4339,7 +4331,7 @@ var init_store2 = __esm({
4339
4331
  }
4340
4332
  if (!stale) return null;
4341
4333
  try {
4342
- fs8.unlinkSync(file);
4334
+ fs6.unlinkSync(file2);
4343
4335
  } catch {
4344
4336
  }
4345
4337
  }
@@ -4356,31 +4348,447 @@ var init_store2 = __esm({
4356
4348
  const dir2 = this.p(name);
4357
4349
  if (!fileExists(dir2)) return [];
4358
4350
  const out = [];
4359
- for (const f of fs8.readdirSync(dir2)) {
4351
+ for (const f of fs6.readdirSync(dir2)) {
4360
4352
  if (!f.endsWith(".json")) continue;
4361
- const v = readJson(path7.join(dir2, f), null);
4353
+ const v = readJson(path5.join(dir2, f), null);
4362
4354
  if (v) out.push(v);
4363
4355
  }
4364
4356
  return out;
4365
4357
  }
4366
4358
  };
4367
- rootKey = (root) => createHash2("sha256").update(path7.resolve(root)).digest("hex").slice(0, 16);
4359
+ rootKey = (root) => createHash2("sha256").update(path5.resolve(root)).digest("hex").slice(0, 16);
4368
4360
  addUnique = (list2, ...ids) => {
4369
4361
  for (const id of ids) if (id && !list2.includes(id)) list2.push(id);
4370
4362
  };
4371
4363
  }
4372
4364
  });
4373
4365
 
4366
+ // src/v2/atoms.ts
4367
+ var atoms_exports = {};
4368
+ __export(atoms_exports, {
4369
+ JUDGE_WINDOW: () => JUDGE_WINDOW,
4370
+ MAX_ACTIONS: () => MAX_ACTIONS,
4371
+ MAX_TRIGGERED: () => MAX_TRIGGERED,
4372
+ actionLine: () => actionLine,
4373
+ cmdAtoms: () => cmdAtoms,
4374
+ judgeFires: () => judgeFires,
4375
+ mutedTriggers: () => mutedTriggers,
4376
+ openFire: () => openFire,
4377
+ readTriggers: () => readTriggers,
4378
+ recordTriggers: () => recordTriggers,
4379
+ routerFires: () => routerFires,
4380
+ triggeredAtoms: () => triggeredAtoms
4381
+ });
4382
+ import fs7 from "node:fs";
4383
+ import path6 from "node:path";
4384
+ function readTriggers(v2) {
4385
+ try {
4386
+ const t = JSON.parse(fs7.readFileSync(file(v2), "utf8"));
4387
+ if (t?.v === 1 && t.triggers) return t;
4388
+ } catch {
4389
+ }
4390
+ return { v: 1, triggers: {} };
4391
+ }
4392
+ function mutedTriggers(v2) {
4393
+ return new Set(Object.entries(readTriggers(v2).triggers).filter(([, t]) => triggerMuted(t)).map(([k]) => k));
4394
+ }
4395
+ function recordTriggers(v2, updates, now = (/* @__PURE__ */ new Date()).toISOString()) {
4396
+ if (!updates.length) return;
4397
+ let release = null;
4398
+ for (let i = 0; i < 4 && !(release = v2.tryLock("atom-triggers", 1e4)); i++) {
4399
+ const until = Date.now() + 25;
4400
+ while (Date.now() < until) {
4401
+ }
4402
+ }
4403
+ if (!release) return;
4404
+ try {
4405
+ const t = readTriggers(v2);
4406
+ for (const u of updates) {
4407
+ const r = t.triggers[u.key] ??= { fires: 0, judged: 0, used: 0 };
4408
+ if (u.title) r.title = u.title.slice(0, 120);
4409
+ if (u.fired) {
4410
+ r.fires++;
4411
+ r.lastAt = now;
4412
+ }
4413
+ if (u.used !== void 0) {
4414
+ r.judged++;
4415
+ if (u.used) r.used++;
4416
+ }
4417
+ }
4418
+ writeJsonAtomic(file(v2), t);
4419
+ } catch {
4420
+ } finally {
4421
+ release();
4422
+ }
4423
+ }
4424
+ function actionLine(tool, text2) {
4425
+ return `${tool}: ${redact2(text2).replace(/\s+/g, " ").trim().slice(0, 240)}`;
4426
+ }
4427
+ function judgeFires(s, text2, expire) {
4428
+ const open = s.fires ?? [];
4429
+ if (!open.length) return [];
4430
+ const calls = s.toolCalls ?? 0;
4431
+ const out = [];
4432
+ const keep = [];
4433
+ for (const f of open) {
4434
+ if (text2 && cuesIn(f.cues, text2).length) out.push({ key: f.key, used: true });
4435
+ else if (expire && calls - f.call >= JUDGE_WINDOW) out.push({ key: f.key, used: false });
4436
+ else keep.push(f);
4437
+ }
4438
+ s.fires = keep;
4439
+ return out;
4440
+ }
4441
+ function openFire(atom, key, call2, firingText) {
4442
+ const cues = usageCues(atom).filter((c) => !firingText.toLowerCase().includes(c));
4443
+ return cues.length ? { key, id: atom.id, call: call2, cues } : null;
4444
+ }
4445
+ function triggeredAtoms(v2, sections, reader, call2, inContext2, callNo) {
4446
+ const hits = toolTriggerHits(sections, reader, call2, { exclude: inContext2, muted: mutedTriggers(v2), max: MAX_TRIGGERED });
4447
+ const why = hits.map((h) => `a ${call2.tool} call matched its trigger (${h.match})`);
4448
+ return {
4449
+ atoms: hits.map((h) => h.section),
4450
+ text: hits.map((h, i) => renderSection(h.section, why[i], { deployed: false })).join("\n\n"),
4451
+ updates: hits.map((h) => ({ key: h.key, title: h.section.title, fired: true })),
4452
+ fires: hits.map((h) => openFire(h.section, h.key, callNo, call2.text)).filter((f) => !!f),
4453
+ why
4454
+ };
4455
+ }
4456
+ function routerFires(atoms, callNo, firingText) {
4457
+ const short = atoms.filter(isAtom);
4458
+ const key = (s) => `${s.id}#router@v${s.version}`;
4459
+ return {
4460
+ updates: short.map((s) => ({ key: key(s), title: s.title, fired: true })),
4461
+ fires: short.map((s) => openFire(s, key(s), callNo, firingText)).filter((f) => !!f)
4462
+ };
4463
+ }
4464
+ function cmdAtoms(store, args, out) {
4465
+ const rows = Object.entries(readTriggers(new V2Store(store)).triggers).map(([key, t]) => ({ key, ...t, precision: triggerPrecision(t), muted: triggerMuted(t) }));
4466
+ rows.sort((a, b) => (a.precision ?? 2) - (b.precision ?? 2) || b.fires - a.fires);
4467
+ if (args.flags.json === true) {
4468
+ out(`${JSON.stringify(rows, null, 2)}
4469
+ `);
4470
+ return 0;
4471
+ }
4472
+ if (!rows.length) {
4473
+ out("No atom has fired on this machine yet.\n");
4474
+ return 0;
4475
+ }
4476
+ for (const r of rows) {
4477
+ const p = r.precision === null ? " \u2014" : `${String(Math.round(r.precision * 100)).padStart(3)}%`;
4478
+ out(`${p} used ${String(r.used).padStart(3)}/${String(r.judged).padEnd(3)} judged ${String(r.fires).padStart(4)} fires ${r.muted ? "MUTED " : " "}${r.key}${r.title ? ` ${r.title}` : ""}
4479
+ `);
4480
+ }
4481
+ out(`${rows.filter((r) => r.muted).length} muted (judged at least 8 times, used under 40%); an edit to the atom starts its record again.
4482
+ `);
4483
+ return 0;
4484
+ }
4485
+ var JUDGE_WINDOW, MAX_TRIGGERED, MAX_ACTIONS, file;
4486
+ var init_atoms2 = __esm({
4487
+ "src/v2/atoms.ts"() {
4488
+ "use strict";
4489
+ init_v22();
4490
+ init_redact2();
4491
+ init_util();
4492
+ init_store2();
4493
+ JUDGE_WINDOW = 8;
4494
+ MAX_TRIGGERED = 2;
4495
+ MAX_ACTIONS = 20;
4496
+ file = (v2) => path6.join(v2.dir, "atoms", "triggers.json");
4497
+ }
4498
+ });
4499
+
4500
+ // src/v2/repo.ts
4501
+ import fs8 from "node:fs";
4502
+ import path7 from "node:path";
4503
+ import { execFileSync } from "node:child_process";
4504
+ function git(cwd, args, timeout = 1500) {
4505
+ try {
4506
+ return execFileSync("git", ["-C", cwd, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout, maxBuffer: 64 * 1024 * 1024 });
4507
+ } catch {
4508
+ return null;
4509
+ }
4510
+ }
4511
+ function repoRoot(cwd, storeRoot) {
4512
+ const key = `${cwd}
4513
+ ${storeRoot ?? ""}`;
4514
+ const hit = rootCache.get(key);
4515
+ if (hit) return hit;
4516
+ const top = git(cwd, ["rev-parse", "--show-toplevel"])?.trim();
4517
+ let root = top || "";
4518
+ if (!root && storeRoot && path7.basename(storeRoot) === ".bunshin") {
4519
+ const parent = path7.dirname(storeRoot);
4520
+ if (path7.resolve(cwd).startsWith(path7.resolve(parent))) root = parent;
4521
+ }
4522
+ root = root || path7.resolve(cwd);
4523
+ rootCache.set(key, root);
4524
+ return root;
4525
+ }
4526
+ function parseRemote(url) {
4527
+ const clean2 = url.trim().replace(/\.git$/, "").replace(/\/+$/, "");
4528
+ if (!clean2) return null;
4529
+ const scp = clean2.match(/^[^@/\s]+@[^:/\s]+:(.+)$/);
4530
+ const pathPart = scp ? scp[1] : (() => {
4531
+ try {
4532
+ return new URL(clean2).pathname;
4533
+ } catch {
4534
+ return clean2;
4535
+ }
4536
+ })();
4537
+ const segs = pathPart.split("/").filter(Boolean);
4538
+ if (segs.length >= 2) return `${segs[segs.length - 2]}/${segs[segs.length - 1]}`;
4539
+ return segs[0] ?? null;
4540
+ }
4541
+ function repoName(root) {
4542
+ const url = git(root, ["remote", "get-url", "origin"]);
4543
+ return url && parseRemote(url) || path7.basename(root);
4544
+ }
4545
+ function repoCommit(root) {
4546
+ return git(root, ["rev-parse", "HEAD"])?.trim() || void 0;
4547
+ }
4548
+ function listDocs(root) {
4549
+ const listed = git(root, ["ls-files", "-co", "--exclude-standard", "-z"], 3e3);
4550
+ if (listed !== null) return [...new Set(listed.split("\0").filter(Boolean).filter(isDoc))].filter((rel) => fs8.existsSync(path7.join(root, rel)) && !deployedSkill(root, rel)).sort();
4551
+ const out = [];
4552
+ let visited = 0;
4553
+ const walk = (dir2, rel, depth) => {
4554
+ if (depth > 8 || visited++ > 2e4) return;
4555
+ let entries;
4556
+ try {
4557
+ entries = fs8.readdirSync(dir2, { withFileTypes: true });
4558
+ } catch {
4559
+ return;
4560
+ }
4561
+ for (const e of entries) {
4562
+ if (e.isDirectory()) {
4563
+ if (!SKIP_DIRS.has(e.name) && !fs8.existsSync(path7.join(dir2, e.name, ".git"))) walk(path7.join(dir2, e.name), rel ? `${rel}/${e.name}` : e.name, depth + 1);
4564
+ } else if (e.isFile()) {
4565
+ const r = rel ? `${rel}/${e.name}` : e.name;
4566
+ if (isDoc(r) && !deployedSkill(root, r)) out.push(r);
4567
+ }
4568
+ }
4569
+ };
4570
+ walk(root, "", 0);
4571
+ return out.sort();
4572
+ }
4573
+ function indexWorkingTree(v2, config, cwd, opts = {}) {
4574
+ const root = repoRoot(cwd, v2.store.root);
4575
+ const now = opts.now ?? Date.now();
4576
+ const cached = v2.readRepoIndex(root);
4577
+ const ownerTeam = config.ownerTeam || config.orgUnit || "unknown";
4578
+ const source = sourceFor(root, v2.store.root);
4579
+ const sameRepo = cached && cached.ownerTeam === ownerTeam && cached.format === INDEX_FORMAT;
4580
+ const repo = sameRepo && cached.repo && !opts.force ? cached.repo : repoName(root);
4581
+ const fresh = sameRepo && cached.repo === repo && cached.paths && cached.listedAt && now - Date.parse(cached.listedAt) < LIST_TTL_MS && !opts.force;
4582
+ const paths = fresh ? cached.paths : listDocs(root);
4583
+ let changed = !fresh || !sameRepo || cached.repo !== repo;
4584
+ const files = {};
4585
+ for (const rel of paths) {
4586
+ const abs = path7.join(root, rel);
4587
+ let stat;
4588
+ try {
4589
+ stat = fs8.statSync(abs);
4590
+ } catch {
4591
+ changed = true;
4592
+ continue;
4593
+ }
4594
+ const prev = sameRepo && cached.repo === repo ? cached.files[rel] : void 0;
4595
+ if (prev && prev.mtimeMs === stat.mtimeMs && prev.size === stat.size) {
4596
+ files[rel] = prev;
4597
+ continue;
4598
+ }
4599
+ changed = true;
4600
+ try {
4601
+ const text2 = fs8.readFileSync(abs, "utf8");
4602
+ files[rel] = { mtimeMs: stat.mtimeMs, size: stat.size, sections: parseRepoDoc({ repo, path: rel, text: text2 }, { orgId: config.orgId, ownerTeam, layer: source ? sourceLayer(source) : "org" }) };
4603
+ } catch {
4604
+ }
4605
+ }
4606
+ const index = {
4607
+ format: INDEX_FORMAT,
4608
+ repo,
4609
+ ownerTeam,
4610
+ listedAt: fresh ? cached.listedAt : new Date(now).toISOString(),
4611
+ paths,
4612
+ files
4613
+ };
4614
+ if (changed) {
4615
+ try {
4616
+ v2.writeRepoIndex(root, index);
4617
+ } catch {
4618
+ }
4619
+ }
4620
+ return { root, index, sections: Object.values(files).flatMap((f) => f.sections) };
4621
+ }
4622
+ function relativeToRoot(root, file2, cwd = root) {
4623
+ if (!file2) return null;
4624
+ const abs = path7.isAbsolute(file2) ? file2 : path7.resolve(cwd, file2);
4625
+ let real = abs;
4626
+ let realRoot = root;
4627
+ try {
4628
+ realRoot = fs8.realpathSync(root);
4629
+ } catch {
4630
+ }
4631
+ try {
4632
+ real = fs8.realpathSync(abs);
4633
+ } catch {
4634
+ try {
4635
+ real = path7.join(fs8.realpathSync(path7.dirname(abs)), path7.basename(abs));
4636
+ } catch {
4637
+ }
4638
+ }
4639
+ for (const [r, f] of [
4640
+ [realRoot, real],
4641
+ [root, abs]
4642
+ ]) {
4643
+ const rel = path7.relative(r, f);
4644
+ if (rel && !rel.startsWith("..") && !path7.isAbsolute(rel)) return rel.split(path7.sep).join("/");
4645
+ }
4646
+ return null;
4647
+ }
4648
+ var DOC_NAMES, SKIP_DIRS, LIST_TTL_MS, rootCache, isDoc, deployedSkill, INDEX_FORMAT;
4649
+ var init_repo = __esm({
4650
+ "src/v2/repo.ts"() {
4651
+ "use strict";
4652
+ init_v22();
4653
+ init_source();
4654
+ DOC_NAMES = /* @__PURE__ */ new Set(["spec.md", "testing.md", "skill.md"]);
4655
+ SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", "dist", ".bunshin"]);
4656
+ LIST_TTL_MS = 6e4;
4657
+ rootCache = /* @__PURE__ */ new Map();
4658
+ isDoc = (rel) => {
4659
+ const parts = rel.split("/");
4660
+ if (parts.some((p) => SKIP_DIRS.has(p))) return false;
4661
+ return DOC_NAMES.has(parts[parts.length - 1].toLowerCase());
4662
+ };
4663
+ deployedSkill = (root, rel) => /(^|\/)SKILL\.md$/i.test(rel) && fs8.existsSync(path7.join(root, path7.posix.dirname(rel), ".bunshin.json"));
4664
+ INDEX_FORMAT = 2;
4665
+ }
4666
+ });
4667
+
4668
+ // src/v2/source.ts
4669
+ var source_exports = {};
4670
+ __export(source_exports, {
4671
+ cwdInPool: () => cwdInPool,
4672
+ inPool: () => inPool,
4673
+ listFolders: () => listFolders,
4674
+ projectRootFor: () => projectRootFor,
4675
+ select: () => select,
4676
+ sourceFor: () => sourceFor,
4677
+ storeHome: () => storeHome,
4678
+ topFolder: () => topFolder
4679
+ });
4680
+ import fs9 from "node:fs";
4681
+ import path8 from "node:path";
4682
+ import { execFileSync as execFileSync2 } from "node:child_process";
4683
+ function storeHome(storeRoot) {
4684
+ return path8.dirname(path8.resolve(storeRoot));
4685
+ }
4686
+ function topFolder(cwd, storeRoot) {
4687
+ const rel = path8.relative(storeHome(storeRoot), path8.resolve(cwd));
4688
+ if (!rel || rel.startsWith("..") || path8.isAbsolute(rel)) return "";
4689
+ return rel.split(path8.sep)[0] ?? "";
4690
+ }
4691
+ function inPool(selection, folder) {
4692
+ if (!folder || !selection) return true;
4693
+ if (selection.exclude?.includes(folder)) return false;
4694
+ return selection.only ? selection.only.includes(folder) : true;
4695
+ }
4696
+ function cwdInPool(config, cwd, storeRoot) {
4697
+ return inPool(config.sources, topFolder(cwd, storeRoot));
4698
+ }
4699
+ function git2(cwd, args) {
4700
+ try {
4701
+ return execFileSync2("git", ["-C", cwd, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 1500 }).trim() || null;
4702
+ } catch {
4703
+ return null;
4704
+ }
4705
+ }
4706
+ function sourceFor(cwd, storeRoot, ctx) {
4707
+ if (ctx?.kind === "robot") return sourceId("robot", ctx.id);
4708
+ const key = `${path8.resolve(cwd)}
4709
+ ${storeRoot}`;
4710
+ if (sourceCache.has(key)) return sourceCache.get(key);
4711
+ const found = findSource(cwd, storeRoot);
4712
+ sourceCache.set(key, found);
4713
+ return found;
4714
+ }
4715
+ function findSource(cwd, storeRoot) {
4716
+ const home = storeHome(storeRoot);
4717
+ const top = git2(cwd, ["rev-parse", "--show-toplevel"]);
4718
+ if (top) {
4719
+ const remote = git2(top, ["remote", "get-url", "origin"]);
4720
+ const named = remote ? parseRemote(remote) : null;
4721
+ if (named) return sourceId("repo", named);
4722
+ const rel = path8.relative(home, top);
4723
+ return sourceId("folder", rel && !rel.startsWith("..") && !path8.isAbsolute(rel) ? rel.split(path8.sep).join("/") : path8.basename(top));
4724
+ }
4725
+ const folder = topFolder(cwd, storeRoot);
4726
+ return folder ? sourceId("folder", folder) : void 0;
4727
+ }
4728
+ function projectRootFor(cwd, storeRoot) {
4729
+ const home = storeHome(storeRoot);
4730
+ const top = git2(cwd, ["rev-parse", "--show-toplevel"]);
4731
+ if (top) {
4732
+ const rel = path8.relative(home, top);
4733
+ if (!rel.startsWith("..") && !path8.isAbsolute(rel)) return top;
4734
+ }
4735
+ const folder = topFolder(cwd, storeRoot);
4736
+ return folder ? path8.join(home, folder) : home;
4737
+ }
4738
+ function listFolders(storeRoot, selection, opts = {}) {
4739
+ const home = storeHome(storeRoot);
4740
+ let names = [];
4741
+ try {
4742
+ names = fs9.readdirSync(home, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name).sort((a, b) => a.localeCompare(b));
4743
+ } catch {
4744
+ }
4745
+ return names.map((folder) => ({
4746
+ folder,
4747
+ included: inPool(selection, folder),
4748
+ ...opts.sources ? { source: sourceFor(path8.join(home, folder), storeRoot) } : {}
4749
+ }));
4750
+ }
4751
+ function select(current, action, folders) {
4752
+ const uniq = (xs) => [...new Set(xs)].sort((a, b) => a.localeCompare(b));
4753
+ const only = current?.only;
4754
+ const exclude = current?.exclude ?? [];
4755
+ let next;
4756
+ switch (action) {
4757
+ case "all":
4758
+ return void 0;
4759
+ case "only":
4760
+ next = { only: uniq(folders) };
4761
+ break;
4762
+ case "include":
4763
+ next = { ...only ? { only: uniq([...only, ...folders]) } : {}, exclude: exclude.filter((f) => !folders.includes(f)) };
4764
+ break;
4765
+ case "exclude":
4766
+ next = { ...only ? { only: only.filter((f) => !folders.includes(f)) } : {}, exclude: uniq([...exclude, ...folders]) };
4767
+ break;
4768
+ }
4769
+ if (!next.exclude?.length) delete next.exclude;
4770
+ return next.only || next.exclude ? next : void 0;
4771
+ }
4772
+ var sourceCache;
4773
+ var init_source = __esm({
4774
+ "src/v2/source.ts"() {
4775
+ "use strict";
4776
+ init_v22();
4777
+ init_repo();
4778
+ sourceCache = /* @__PURE__ */ new Map();
4779
+ }
4780
+ });
4781
+
4374
4782
  // src/v2/deploy.ts
4375
4783
  import { execFileSync as execFileSync3 } from "node:child_process";
4376
4784
  import { createHash as createHash3 } from "node:crypto";
4377
- import fs9 from "node:fs";
4785
+ import fs10 from "node:fs";
4378
4786
  import os2 from "node:os";
4379
- import path8 from "node:path";
4787
+ import path9 from "node:path";
4380
4788
  function deployWorkspace(env = process.env) {
4381
- if (env.BUNSHIN_DEPLOY_WORKSPACE) return path8.resolve(env.BUNSHIN_DEPLOY_WORKSPACE);
4789
+ if (env.BUNSHIN_DEPLOY_WORKSPACE) return path9.resolve(env.BUNSHIN_DEPLOY_WORKSPACE);
4382
4790
  try {
4383
- const ws = JSON.parse(fs9.readFileSync(settingsFile(env.BUNSHIN_DEPLOY_HOME || os2.homedir()), "utf8")).workspace;
4791
+ const ws = JSON.parse(fs10.readFileSync(settingsFile(env.BUNSHIN_DEPLOY_HOME || os2.homedir()), "utf8")).workspace;
4384
4792
  return typeof ws === "string" && ws ? ws : null;
4385
4793
  } catch {
4386
4794
  return null;
@@ -4389,46 +4797,46 @@ function deployWorkspace(env = process.env) {
4389
4797
  function deployPaths(env = process.env, orgId) {
4390
4798
  const home = env.BUNSHIN_DEPLOY_HOME || os2.homedir();
4391
4799
  const ws = deployWorkspace(env);
4392
- const state = path8.join(home, ".bunshin", "deploy");
4393
- const shared = { claude: path8.join(ws ?? home, ".claude", "skills"), codex: path8.join(ws ?? home, ".codex", "skills") };
4394
- const org = orgId ? path8.join(state, orgKey(orgId)) : null;
4800
+ const state = path9.join(home, ".bunshin", "deploy");
4801
+ const shared = { claude: path9.join(ws ?? home, ".claude", "skills"), codex: path9.join(ws ?? home, ".codex", "skills") };
4802
+ const org = orgId ? path9.join(state, orgKey(orgId)) : null;
4395
4803
  return {
4396
4804
  home,
4397
- claudeSkills: org ? path8.join(org, "claude-skills") : shared.claude,
4398
- codexSkills: org ? path8.join(org, "codex-skills") : shared.codex,
4399
- ...org ? { legacy: [.../* @__PURE__ */ new Set([shared.claude, shared.codex, path8.join(home, ".claude", "skills"), path8.join(home, ".codex", "skills"), path8.join(home, ".bunshin", "library")])] } : {},
4400
- claudeMd: ws ? path8.join(ws, "CLAUDE.md") : path8.join(home, ".claude", "CLAUDE.md"),
4401
- agentsMd: ws ? path8.join(ws, "AGENTS.md") : path8.join(home, ".codex", "AGENTS.md"),
4402
- library: org ? path8.join(org, "library") : path8.join(home, ".bunshin", "library"),
4805
+ claudeSkills: org ? path9.join(org, "claude-skills") : shared.claude,
4806
+ codexSkills: org ? path9.join(org, "codex-skills") : shared.codex,
4807
+ ...org ? { legacy: [.../* @__PURE__ */ new Set([shared.claude, shared.codex, path9.join(home, ".claude", "skills"), path9.join(home, ".codex", "skills"), path9.join(home, ".bunshin", "library")])] } : {},
4808
+ claudeMd: ws ? path9.join(ws, "CLAUDE.md") : path9.join(home, ".claude", "CLAUDE.md"),
4809
+ agentsMd: ws ? path9.join(ws, "AGENTS.md") : path9.join(home, ".codex", "AGENTS.md"),
4810
+ library: org ? path9.join(org, "library") : path9.join(home, ".bunshin", "library"),
4403
4811
  // Pack executables are linked into one folder on PATH (shared by name; their files are per organization).
4404
- bin: path8.join(home, ".bunshin", "bin"),
4812
+ bin: path9.join(home, ".bunshin", "bin"),
4405
4813
  state
4406
4814
  };
4407
4815
  }
4408
4816
  function statePath(p, orgId) {
4409
- return path8.join(p.state, `${orgKey(orgId)}.json`);
4817
+ return path9.join(p.state, `${orgKey(orgId)}.json`);
4410
4818
  }
4411
4819
  function readState(p, orgId) {
4412
4820
  const s = readJson(statePath(p, orgId), null);
4413
4821
  return { orgId, since: s?.since ?? (/* @__PURE__ */ new Date()).toISOString(), docs: s?.docs ?? {}, created: s?.created ?? {}, links: s?.links ?? [], ...s?.linked?.length ? { linked: s.linked } : {}, ...s?.libraryVersion ? { libraryVersion: s.libraryVersion } : {} };
4414
4822
  }
4415
- function readText(file) {
4823
+ function readText(file2) {
4416
4824
  try {
4417
- return fs9.readFileSync(file, "utf8");
4825
+ return fs10.readFileSync(file2, "utf8");
4418
4826
  } catch {
4419
4827
  return null;
4420
4828
  }
4421
4829
  }
4422
- function writeFile(file, content, mode) {
4423
- writeTextAtomic(file, content);
4830
+ function writeFile(file2, content, mode) {
4831
+ writeTextAtomic(file2, content);
4424
4832
  try {
4425
- fs9.chmodSync(file, mode === "x" ? 493 : 420);
4833
+ fs10.chmodSync(file2, mode === "x" ? 493 : 420);
4426
4834
  } catch {
4427
4835
  }
4428
4836
  }
4429
- function removeFile(file) {
4837
+ function removeFile(file2) {
4430
4838
  try {
4431
- fs9.unlinkSync(file);
4839
+ fs10.unlinkSync(file2);
4432
4840
  } catch {
4433
4841
  }
4434
4842
  }
@@ -4436,33 +4844,33 @@ function pruneDirs(dir2, stop) {
4436
4844
  let d = dir2;
4437
4845
  while (d.startsWith(stop) && d !== stop) {
4438
4846
  try {
4439
- if (fs9.readdirSync(d).length) return;
4440
- fs9.rmdirSync(d);
4847
+ if (fs10.readdirSync(d).length) return;
4848
+ fs10.rmdirSync(d);
4441
4849
  } catch {
4442
4850
  return;
4443
4851
  }
4444
- d = path8.dirname(d);
4852
+ d = path9.dirname(d);
4445
4853
  }
4446
4854
  }
4447
4855
  function listFiles(dir2, base = dir2) {
4448
4856
  let entries;
4449
4857
  try {
4450
- entries = fs9.readdirSync(dir2, { withFileTypes: true });
4858
+ entries = fs10.readdirSync(dir2, { withFileTypes: true });
4451
4859
  } catch {
4452
4860
  return [];
4453
4861
  }
4454
4862
  const out = [];
4455
4863
  for (const e of entries) {
4456
- const abs = path8.join(dir2, e.name);
4864
+ const abs = path9.join(dir2, e.name);
4457
4865
  if (e.isDirectory()) out.push(...listFiles(abs, base));
4458
- else if (e.isFile()) out.push(path8.relative(base, abs).split(path8.sep).join("/"));
4866
+ else if (e.isFile()) out.push(path9.relative(base, abs).split(path9.sep).join("/"));
4459
4867
  }
4460
4868
  return out.sort();
4461
4869
  }
4462
4870
  function childDir(root, name) {
4463
4871
  if (!name || !SAFE_NAME.test(name)) return null;
4464
- const dir2 = path8.join(root, name);
4465
- return path8.dirname(path8.resolve(dir2)) === path8.resolve(root) && insideRoot(root, dir2) ? dir2 : null;
4872
+ const dir2 = path9.join(root, name);
4873
+ return path9.dirname(path9.resolve(dir2)) === path9.resolve(root) && insideRoot(root, dir2) ? dir2 : null;
4466
4874
  }
4467
4875
  function layerRank(layer, tree) {
4468
4876
  const kind = layerKind(layer);
@@ -4543,8 +4951,8 @@ function planDeploy(bundle, p, harnesses) {
4543
4951
  }
4544
4952
  return plan;
4545
4953
  }
4546
- function readBlock(file) {
4547
- const text2 = readText(file);
4954
+ function readBlock(file2) {
4955
+ const text2 = readText(file2);
4548
4956
  if (text2 === null) return null;
4549
4957
  const start = text2.indexOf(BLOCK_BEGIN);
4550
4958
  const end = text2.indexOf(BLOCK_END);
@@ -4566,25 +4974,25 @@ ${neutralizeMarkers(d.text).replace(/\n*$/, "\n")}`),
4566
4974
  ];
4567
4975
  return parts.join("\n");
4568
4976
  }
4569
- function removeBlock(file) {
4570
- const text2 = readText(file);
4977
+ function removeBlock(file2) {
4978
+ const text2 = readText(file2);
4571
4979
  if (text2 === null) return false;
4572
4980
  const start = text2.indexOf(BLOCK_BEGIN);
4573
4981
  const end = text2.indexOf(BLOCK_END);
4574
4982
  if (start < 0 || end < start) return false;
4575
4983
  const rest = (text2.slice(0, start).replace(/\s*$/, "") + "\n" + text2.slice(end + BLOCK_END.length).replace(/^\s*/, "")).trim();
4576
- if (rest) writeTextAtomic(file, rest + "\n");
4577
- else fs9.unlinkSync(file);
4984
+ if (rest) writeTextAtomic(file2, rest + "\n");
4985
+ else fs10.unlinkSync(file2);
4578
4986
  return true;
4579
4987
  }
4580
- function writeBlock(file, block2) {
4581
- const text2 = readText(file) ?? "";
4988
+ function writeBlock(file2, block2) {
4989
+ const text2 = readText(file2) ?? "";
4582
4990
  const start = text2.indexOf(BLOCK_BEGIN);
4583
4991
  const end = text2.indexOf(BLOCK_END);
4584
4992
  const next = start >= 0 && end > start ? text2.slice(0, start) + block2 + text2.slice(end + BLOCK_END.length) : `${text2.replace(/\s*$/, "")}${text2.trim() ? "\n\n" : ""}${block2}
4585
4993
  `;
4586
4994
  if (next === text2) return false;
4587
- writeTextAtomic(file, next);
4995
+ writeTextAtomic(file2, next);
4588
4996
  return true;
4589
4997
  }
4590
4998
  function skillIndex(skills, p) {
@@ -4595,7 +5003,7 @@ function skillIndex(skills, p) {
4595
5003
  "",
4596
5004
  "When a task matches a skill below, read its SKILL.md and follow it before doing the work by hand.",
4597
5005
  "",
4598
- ...skills.map((s) => `- **${s.skill.name}** (\`${path8.join(p.codexSkills, s.skill.name, "SKILL.md")}\`): ${neutralizeMarkers(s.skill.description).replace(/\s+/g, " ").trim()}`)
5006
+ ...skills.map((s) => `- **${s.skill.name}** (\`${path9.join(p.codexSkills, s.skill.name, "SKILL.md")}\`): ${neutralizeMarkers(s.skill.description).replace(/\s+/g, " ").trim()}`)
4599
5007
  ];
4600
5008
  return lines.join("\n");
4601
5009
  }
@@ -4644,7 +5052,7 @@ function captureDoc(c, doc, out) {
4644
5052
  for (const dir2 of doc.dirs ?? []) {
4645
5053
  for (const rel of listFiles(dir2)) {
4646
5054
  if (rel === "SKILL.md" || rel === MANIFEST || seen.has(`file:${rel}`)) continue;
4647
- const abs = path8.join(dir2, rel);
5055
+ const abs = path9.join(dir2, rel);
4648
5056
  const content = readText(abs);
4649
5057
  if (content === null || Buffer.byteLength(content) > MAX_FILE) continue;
4650
5058
  byRel.set(`file:${rel}`, { target: { abs, rel, role: "file", sha: "", ...isExecutable(abs) ? { mode: "x" } : {} }, content });
@@ -4683,18 +5091,18 @@ function captureNewSkills(c, state, roots, owned, incoming, out, layer, only) {
4683
5091
  for (const root of roots) {
4684
5092
  let names = [];
4685
5093
  try {
4686
- names = fs9.readdirSync(root, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name);
5094
+ names = fs10.readdirSync(root, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name);
4687
5095
  } catch {
4688
5096
  continue;
4689
5097
  }
4690
5098
  for (const name of names) {
4691
- const dir2 = path8.join(root, name);
5099
+ const dir2 = path9.join(root, name);
4692
5100
  if (owned.has(dir2) || incoming.has(name) || only && name !== only) continue;
4693
- const skillMd = readText(path8.join(dir2, "SKILL.md"));
5101
+ const skillMd = readText(path9.join(dir2, "SKILL.md"));
4694
5102
  if (skillMd === null) continue;
4695
5103
  let born = 0;
4696
5104
  try {
4697
- const st = fs9.statSync(path8.join(dir2, "SKILL.md"));
5105
+ const st = fs10.statSync(path9.join(dir2, "SKILL.md"));
4698
5106
  born = Math.min(st.birthtimeMs || st.mtimeMs, st.mtimeMs);
4699
5107
  } catch {
4700
5108
  continue;
@@ -4703,8 +5111,8 @@ function captureNewSkills(c, state, roots, owned, incoming, out, layer, only) {
4703
5111
  const files = {};
4704
5112
  for (const rel of listFiles(dir2).filter((r) => !r.split("/").some((seg) => seg.startsWith(".")))) {
4705
5113
  if (rel === "SKILL.md" || rel === MANIFEST) continue;
4706
- const content = readText(path8.join(dir2, rel));
4707
- if (content !== null && Buffer.byteLength(content) <= MAX_FILE) files[rel] = { content, ...isExecutable(path8.join(dir2, rel)) ? { mode: "x" } : {} };
5114
+ const content = readText(path9.join(dir2, rel));
5115
+ if (content !== null && Buffer.byteLength(content) <= MAX_FILE) files[rel] = { content, ...isExecutable(path9.join(dir2, rel)) ? { mode: "x" } : {} };
4708
5116
  }
4709
5117
  const hash = sha(JSON.stringify([skillMd, files]));
4710
5118
  if (state.created[name]?.hash === hash) continue;
@@ -4752,15 +5160,15 @@ function captureEdits(v2, config, ctx, opts = {}) {
4752
5160
  }
4753
5161
  function lockDeploy(p) {
4754
5162
  ensureDir(p.state);
4755
- const file = path8.join(p.state, ".lock");
5163
+ const file2 = path9.join(p.state, ".lock");
4756
5164
  for (let i = 0; i < 2; i++) {
4757
5165
  try {
4758
- fs9.writeFileSync(file, String(process.pid), { flag: "wx" });
4759
- return () => removeFile(file);
5166
+ fs10.writeFileSync(file2, String(process.pid), { flag: "wx" });
5167
+ return () => removeFile(file2);
4760
5168
  } catch {
4761
5169
  try {
4762
- const age = Date.now() - fs9.statSync(file).mtimeMs;
4763
- const pid = Number(readText(file));
5170
+ const age = Date.now() - fs10.statSync(file2).mtimeMs;
5171
+ const pid = Number(readText(file2));
4764
5172
  let alive = age < 12e4;
4765
5173
  if (alive && pid > 0) {
4766
5174
  try {
@@ -4770,7 +5178,7 @@ function lockDeploy(p) {
4770
5178
  }
4771
5179
  }
4772
5180
  if (alive) return null;
4773
- removeFile(file);
5181
+ removeFile(file2);
4774
5182
  } catch {
4775
5183
  }
4776
5184
  }
@@ -4826,7 +5234,7 @@ function deployLocked(v2, config, ctx, bundle, opts, p, harnesses, now) {
4826
5234
  const foreign = /* @__PURE__ */ new Set();
4827
5235
  if (d.kind === "skill" && !prev) {
4828
5236
  for (const dir2 of d.dirs ?? []) {
4829
- const cur = readText(path8.join(dir2, "SKILL.md"));
5237
+ const cur = readText(path9.join(dir2, "SKILL.md"));
4830
5238
  if (cur === null || cur === d.section.body || state.created[d.name]) continue;
4831
5239
  foreign.add(dir2);
4832
5240
  report.warnings.push(`${dir2} is not managed by Bunshin; the library's ${d.name} skill was not installed there`);
@@ -4838,7 +5246,7 @@ function deployLocked(v2, config, ctx, bundle, opts, p, harnesses, now) {
4838
5246
  targets.push({ ...t, sha: sha(neutralizeMarkers(d.section.body).replace(/\n*$/, "\n")) });
4839
5247
  continue;
4840
5248
  }
4841
- if ([...foreign].some((dir2) => t.abs.startsWith(dir2 + path8.sep))) continue;
5249
+ if ([...foreign].some((dir2) => t.abs.startsWith(dir2 + path9.sep))) continue;
4842
5250
  if (!(d.dirs ?? (d.root ? [d.root] : [])).some((r) => insideRoot(r, t.abs))) {
4843
5251
  report.warnings.push(`${t.abs} not written: it leads outside its folder`);
4844
5252
  continue;
@@ -4847,10 +5255,10 @@ function deployLocked(v2, config, ctx, bundle, opts, p, harnesses, now) {
4847
5255
  const existing = readText(t.abs);
4848
5256
  try {
4849
5257
  if (existing !== content) {
4850
- ensureDir(path8.dirname(t.abs));
5258
+ ensureDir(path9.dirname(t.abs));
4851
5259
  writeFile(t.abs, content, t.mode);
4852
5260
  report.written++;
4853
- } else if (t.mode === "x" && !isExecutable(t.abs)) fs9.chmodSync(t.abs, 493);
5261
+ } else if (t.mode === "x" && !isExecutable(t.abs)) fs10.chmodSync(t.abs, 493);
4854
5262
  } catch (err) {
4855
5263
  report.warnings.push(`${t.abs} not written: ${err instanceof Error ? err.message : String(err)}`);
4856
5264
  continue;
@@ -4863,19 +5271,19 @@ function deployLocked(v2, config, ctx, bundle, opts, p, harnesses, now) {
4863
5271
  const cur = readText(old.abs);
4864
5272
  if (cur !== null && sha(cur) === old.sha) {
4865
5273
  removeFile(old.abs);
4866
- pruneDirs(path8.dirname(old.abs), d.kind === "skill" ? path8.dirname(path8.dirname(old.abs)) : p.library);
5274
+ pruneDirs(path9.dirname(old.abs), d.kind === "skill" ? path9.dirname(path9.dirname(old.abs)) : p.library);
4867
5275
  report.removed++;
4868
5276
  }
4869
5277
  }
4870
5278
  if (d.kind === "skill") {
4871
5279
  for (const dir2 of prev?.dirs ?? []) {
4872
5280
  if ((d.dirs ?? []).includes(dir2) || !removable(dir2)) continue;
4873
- removeFile(path8.join(dir2, MANIFEST));
4874
- pruneDirs(dir2, path8.dirname(dir2));
5281
+ removeFile(path9.join(dir2, MANIFEST));
5282
+ pruneDirs(dir2, path9.dirname(dir2));
4875
5283
  }
4876
5284
  for (const dir2 of d.dirs ?? []) {
4877
5285
  const manifest = safeJoin(dir2, MANIFEST);
4878
- if (foreign.has(dir2) || !manifest || !fs9.existsSync(path8.join(dir2, "SKILL.md"))) continue;
5286
+ if (foreign.has(dir2) || !manifest || !fs10.existsSync(path9.join(dir2, "SKILL.md"))) continue;
4879
5287
  writeJsonAtomic(manifest, { sectionId: id, name: d.name, version: d.section.version, libraryVersion: bundle.libraryVersion ?? null, managedBy: "bunshin sync" });
4880
5288
  }
4881
5289
  report.skills++;
@@ -4900,12 +5308,12 @@ function deployLocked(v2, config, ctx, bundle, opts, p, harnesses, now) {
4900
5308
  }
4901
5309
  for (const dir2 of doc.dirs ?? []) {
4902
5310
  if (!removable(dir2)) continue;
4903
- removeFile(path8.join(dir2, MANIFEST));
4904
- pruneDirs(dir2, path8.dirname(dir2));
4905
- if (fs9.existsSync(dir2)) {
5311
+ removeFile(path9.join(dir2, MANIFEST));
5312
+ pruneDirs(dir2, path9.dirname(dir2));
5313
+ if (fs10.existsSync(dir2)) {
4906
5314
  const left = listFiles(dir2);
4907
5315
  if (left.length) report.warnings.push(`${dir2} kept: it has files Bunshin did not write`);
4908
- else pruneDirs(dir2, path8.dirname(dir2));
5316
+ else pruneDirs(dir2, path9.dirname(dir2));
4909
5317
  }
4910
5318
  }
4911
5319
  }
@@ -4921,17 +5329,17 @@ function deployLocked(v2, config, ctx, bundle, opts, p, harnesses, now) {
4921
5329
  if (d.kind === "skill") continue;
4922
5330
  for (const t of d.targets) {
4923
5331
  if (t.role === "block" || t.mode !== "x" || !/(^|\/)bin\/[^/]+$/.test(t.rel) || !owned(t.abs)) continue;
4924
- const link = path8.join(p.bin, path8.basename(t.abs));
5332
+ const link = path9.join(p.bin, path9.basename(t.abs));
4925
5333
  ensureDir(p.bin);
4926
5334
  try {
4927
- const cur = fs9.readlinkSync(link);
5335
+ const cur = fs10.readlinkSync(link);
4928
5336
  if (cur !== t.abs) {
4929
- fs9.unlinkSync(link);
4930
- fs9.symlinkSync(t.abs, link);
5337
+ fs10.unlinkSync(link);
5338
+ fs10.symlinkSync(t.abs, link);
4931
5339
  }
4932
5340
  } catch {
4933
5341
  try {
4934
- if (!fs9.existsSync(link)) fs9.symlinkSync(t.abs, link);
5342
+ if (!fs10.existsSync(link)) fs10.symlinkSync(t.abs, link);
4935
5343
  } catch {
4936
5344
  }
4937
5345
  }
@@ -4942,19 +5350,19 @@ function deployLocked(v2, config, ctx, bundle, opts, p, harnesses, now) {
4942
5350
  if (harnesses.has("claude-code")) {
4943
5351
  for (const pack of packs) {
4944
5352
  const dir2 = childDir(p.library, pack);
4945
- if (!dir2 || !insideRoot(dir2, path8.join(dir2, ".claude", "x"))) continue;
4946
- const link = path8.join(dir2, ".claude", "skills");
5353
+ if (!dir2 || !insideRoot(dir2, path9.join(dir2, ".claude", "x"))) continue;
5354
+ const link = path9.join(dir2, ".claude", "skills");
4947
5355
  try {
4948
- fs9.lstatSync(link);
4949
- if (fs9.readlinkSync(link) !== p.claudeSkills) {
4950
- fs9.unlinkSync(link);
4951
- fs9.symlinkSync(p.claudeSkills, link);
5356
+ fs10.lstatSync(link);
5357
+ if (fs10.readlinkSync(link) !== p.claudeSkills) {
5358
+ fs10.unlinkSync(link);
5359
+ fs10.symlinkSync(p.claudeSkills, link);
4952
5360
  }
4953
5361
  } catch {
4954
- ensureDir(path8.dirname(link));
5362
+ ensureDir(path9.dirname(link));
4955
5363
  ensureDir(p.claudeSkills);
4956
5364
  try {
4957
- fs9.symlinkSync(p.claudeSkills, link);
5365
+ fs10.symlinkSync(p.claudeSkills, link);
4958
5366
  } catch {
4959
5367
  }
4960
5368
  }
@@ -4963,8 +5371,8 @@ function deployLocked(v2, config, ctx, bundle, opts, p, harnesses, now) {
4963
5371
  for (const old of state.links) {
4964
5372
  if (links.has(old)) continue;
4965
5373
  try {
4966
- const target = fs9.readlinkSync(old);
4967
- if (!fs9.existsSync(target)) fs9.unlinkSync(old);
5374
+ const target = fs10.readlinkSync(old);
5375
+ if (!fs10.existsSync(target)) fs10.unlinkSync(old);
4968
5376
  } catch {
4969
5377
  }
4970
5378
  }
@@ -4972,7 +5380,7 @@ function deployLocked(v2, config, ctx, bundle, opts, p, harnesses, now) {
4972
5380
  if (p.legacy) {
4973
5381
  const deployed = Object.values(next).filter((d) => d.kind === "skill" && (d.dirs ?? []).length);
4974
5382
  const layerOf = new Map(plan.skills.map((x) => [x.skill.name, x.layer]));
4975
- const roots = [.../* @__PURE__ */ new Set([...linked, ...opts.linkRoot ? [path8.resolve(opts.linkRoot)] : []])];
5383
+ const roots = [.../* @__PURE__ */ new Set([...linked, ...opts.linkRoot ? [path9.resolve(opts.linkRoot)] : []])];
4976
5384
  linked = [];
4977
5385
  for (const root of roots) {
4978
5386
  let source;
@@ -5003,13 +5411,13 @@ function materialize(sections, dir2) {
5003
5411
  const put = (rel, content, mode) => {
5004
5412
  const abs = safeJoin(dir2, rel);
5005
5413
  if (!abs) return;
5006
- ensureDir(path8.dirname(abs));
5414
+ ensureDir(path9.dirname(abs));
5007
5415
  writeFile(abs, content, mode);
5008
5416
  files++;
5009
5417
  };
5010
5418
  for (const s of sections.filter((x) => x.status === "active" || x.status === "stale")) {
5011
5419
  if (s.skill) {
5012
- const base = s.packPath && /(^|\/)SKILL\.md$/.test(s.packPath) ? path8.posix.dirname(s.packPath) : `.claude/skills/${s.skill.name}`;
5420
+ const base = s.packPath && /(^|\/)SKILL\.md$/.test(s.packPath) ? path9.posix.dirname(s.packPath) : `.claude/skills/${s.skill.name}`;
5013
5421
  put(`${base}/SKILL.md`, s.body);
5014
5422
  for (const [rel, f] of Object.entries(s.skill.files ?? {})) put(`${base}/${rel}`, f.content, f.mode);
5015
5423
  continue;
@@ -5021,51 +5429,51 @@ function materialize(sections, dir2) {
5021
5429
  }
5022
5430
  function linkSkills(p, root, harnesses, names) {
5023
5431
  const out = { linked: 0, removed: 0, kept: false, warnings: [] };
5024
- const abs = path8.resolve(root);
5025
- if (abs === path8.resolve(p.home) || abs === path8.resolve(os2.homedir()) || !fs9.existsSync(abs)) return out;
5026
- const managed = (target) => target.startsWith(path8.resolve(p.state) + path8.sep);
5432
+ const abs = path9.resolve(root);
5433
+ if (abs === path9.resolve(p.home) || abs === path9.resolve(os2.homedir()) || !fs10.existsSync(abs)) return out;
5434
+ const managed = (target) => target.startsWith(path9.resolve(p.state) + path9.sep);
5027
5435
  const excluded = [];
5028
5436
  for (const h of harnesses) {
5029
5437
  const spec = LINK_DIRS[h];
5030
5438
  if (!spec) continue;
5031
- const dir2 = path8.join(abs, spec.rel);
5032
- const canonical = path8.resolve(p[spec.key]);
5033
- const want = new Set(names.filter((n) => SAFE_NAME.test(n) && fs9.existsSync(path8.join(canonical, n, "SKILL.md"))));
5439
+ const dir2 = path9.join(abs, spec.rel);
5440
+ const canonical = path9.resolve(p[spec.key]);
5441
+ const want = new Set(names.filter((n) => SAFE_NAME.test(n) && fs10.existsSync(path9.join(canonical, n, "SKILL.md"))));
5034
5442
  let entries = [];
5035
5443
  try {
5036
- entries = fs9.readdirSync(dir2, { withFileTypes: true });
5444
+ entries = fs10.readdirSync(dir2, { withFileTypes: true });
5037
5445
  } catch {
5038
5446
  }
5039
5447
  for (const e of entries) {
5040
5448
  if (!e.isSymbolicLink()) continue;
5041
- const link = path8.join(dir2, e.name);
5449
+ const link = path9.join(dir2, e.name);
5042
5450
  let target = "";
5043
5451
  try {
5044
- target = path8.resolve(dir2, fs9.readlinkSync(link));
5452
+ target = path9.resolve(dir2, fs10.readlinkSync(link));
5045
5453
  } catch {
5046
5454
  continue;
5047
5455
  }
5048
5456
  if (!managed(target)) continue;
5049
- if (want.has(e.name) && target === path8.join(canonical, e.name)) {
5457
+ if (want.has(e.name) && target === path9.join(canonical, e.name)) {
5050
5458
  want.delete(e.name);
5051
- excluded.push(path8.join(spec.rel, e.name));
5459
+ excluded.push(path9.join(spec.rel, e.name));
5052
5460
  continue;
5053
5461
  }
5054
5462
  removeFile(link);
5055
5463
  out.removed++;
5056
5464
  }
5057
5465
  for (const name of want) {
5058
- const link = path8.join(dir2, name);
5466
+ const link = path9.join(dir2, name);
5059
5467
  try {
5060
- fs9.lstatSync(link);
5468
+ fs10.lstatSync(link);
5061
5469
  out.warnings.push(`${link} is the project's own; the library's ${name} skill was not linked there`);
5062
5470
  continue;
5063
5471
  } catch {
5064
5472
  }
5065
5473
  try {
5066
5474
  ensureDir(dir2);
5067
- fs9.symlinkSync(path8.join(canonical, name), link, "dir");
5068
- excluded.push(path8.join(spec.rel, name));
5475
+ fs10.symlinkSync(path9.join(canonical, name), link, "dir");
5476
+ excluded.push(path9.join(spec.rel, name));
5069
5477
  out.linked++;
5070
5478
  } catch (err) {
5071
5479
  out.warnings.push(`${link} not linked: ${err instanceof Error ? err.message : String(err)}`);
@@ -5078,26 +5486,26 @@ function linkSkills(p, root, harnesses, names) {
5078
5486
  return out;
5079
5487
  }
5080
5488
  function gitExclude(root, rels) {
5081
- if (!fs9.existsSync(path8.join(root, ".git"))) return;
5082
- let file;
5489
+ if (!fs10.existsSync(path9.join(root, ".git"))) return;
5490
+ let file2;
5083
5491
  try {
5084
- file = path8.resolve(root, execFileSync3("git", ["-C", root, "rev-parse", "--git-path", "info/exclude"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 2e3 }).trim());
5492
+ file2 = path9.resolve(root, execFileSync3("git", ["-C", root, "rev-parse", "--git-path", "info/exclude"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 2e3 }).trim());
5085
5493
  } catch {
5086
5494
  return;
5087
5495
  }
5088
- const cur = readText(file) ?? "";
5496
+ const cur = readText(file2) ?? "";
5089
5497
  const start = cur.indexOf(EXCLUDE_BEGIN);
5090
5498
  const end = start >= 0 ? cur.indexOf(EXCLUDE_END, start) : -1;
5091
5499
  const rest = start >= 0 && end >= 0 ? cur.slice(0, start) + cur.slice(end + EXCLUDE_END.length).replace(/^\n/, "") : cur;
5092
5500
  const block2 = rels.length ? `${EXCLUDE_BEGIN}
5093
- ${[...new Set(rels)].sort().map((r) => `/${r.split(path8.sep).join("/")}`).join("\n")}
5501
+ ${[...new Set(rels)].sort().map((r) => `/${r.split(path9.sep).join("/")}`).join("\n")}
5094
5502
  ${EXCLUDE_END}
5095
5503
  ` : "";
5096
5504
  const next = block2 ? `${rest}${rest && !rest.endsWith("\n") ? "\n" : ""}${block2}` : rest;
5097
5505
  if (next === cur) return;
5098
5506
  try {
5099
- ensureDir(path8.dirname(file));
5100
- fs9.writeFileSync(file, next);
5507
+ ensureDir(path9.dirname(file2));
5508
+ fs10.writeFileSync(file2, next);
5101
5509
  } catch {
5102
5510
  }
5103
5511
  }
@@ -5109,16 +5517,16 @@ var init_deploy = __esm({
5109
5517
  init_source();
5110
5518
  init_util();
5111
5519
  init_store2();
5112
- settingsFile = (home) => path8.join(home, ".bunshin", "deploy", "settings.json");
5520
+ settingsFile = (home) => path9.join(home, ".bunshin", "deploy", "settings.json");
5113
5521
  orgKey = (orgId) => orgId.replace(/[^A-Za-z0-9._-]/g, "_") || "org";
5114
5522
  sha = (text2) => createHash3("sha256").update(text2).digest("hex");
5115
5523
  BLOCK_BEGIN = "<!-- bunshin:begin -->";
5116
5524
  BLOCK_END = "<!-- bunshin:end -->";
5117
5525
  MANIFEST = ".bunshin.json";
5118
5526
  MAX_FILE = 2 * 1024 * 1024;
5119
- isExecutable = (file) => {
5527
+ isExecutable = (file2) => {
5120
5528
  try {
5121
- return (fs9.statSync(file).mode & 73) !== 0;
5529
+ return (fs10.statSync(file2).mode & 73) !== 0;
5122
5530
  } catch {
5123
5531
  return false;
5124
5532
  }
@@ -5129,8 +5537,8 @@ var init_deploy = __esm({
5129
5537
  docMarker = (id, version2) => `<!-- bunshin:doc id=${id} v=${version2} -->`;
5130
5538
  BORN_SLACK_MS = 2e3;
5131
5539
  LINK_DIRS = {
5132
- "claude-code": { rel: path8.join(".claude", "skills"), key: "claudeSkills" },
5133
- codex: { rel: path8.join(".codex", "skills"), key: "codexSkills" }
5540
+ "claude-code": { rel: path9.join(".claude", "skills"), key: "claudeSkills" },
5541
+ codex: { rel: path9.join(".codex", "skills"), key: "codexSkills" }
5134
5542
  };
5135
5543
  EXCLUDE_BEGIN = "# >>> bunshin: library skills linked here (managed by bunshin sync)";
5136
5544
  EXCLUDE_END = "# <<< bunshin";
@@ -5242,11 +5650,11 @@ var init_live = __esm({
5242
5650
  });
5243
5651
 
5244
5652
  // src/transcript.ts
5245
- import fs10 from "node:fs";
5246
- function parseTranscript(file) {
5653
+ import fs11 from "node:fs";
5654
+ function parseTranscript(file2) {
5247
5655
  let raw = "";
5248
5656
  try {
5249
- raw = fs10.readFileSync(file, "utf8");
5657
+ raw = fs11.readFileSync(file2, "utf8");
5250
5658
  } catch {
5251
5659
  return { turns: [], userMessages: 0, toolCalls: 0, toolFailures: 0 };
5252
5660
  }
@@ -5444,8 +5852,8 @@ function traceChunks(turns, maxBytes = 1e6) {
5444
5852
  if (cur) out.push(cur);
5445
5853
  return out;
5446
5854
  }
5447
- function recentContext(file, { turns = 2, maxChars = 6e3 } = {}) {
5448
- const facts = parseTranscript(file);
5855
+ function recentContext(file2, { turns = 2, maxChars = 6e3 } = {}) {
5856
+ const facts = parseTranscript(file2);
5449
5857
  const visible = facts.turns.filter((t) => t.role !== "tool");
5450
5858
  const userIdx = visible.map((t, i) => t.role === "user" ? i : -1).filter((i) => i >= 0);
5451
5859
  const start = userIdx.length > turns ? userIdx[userIdx.length - turns] : 0;
@@ -5566,7 +5974,7 @@ var init_view = __esm({
5566
5974
  });
5567
5975
 
5568
5976
  // src/v2/apply.ts
5569
- import fs11 from "node:fs";
5977
+ import fs12 from "node:fs";
5570
5978
  function appendedText(op) {
5571
5979
  return op.condition ? `- **${op.condition}:** ${op.text.trim()}` : op.text.trim();
5572
5980
  }
@@ -5619,14 +6027,14 @@ function applyLocally(v2, view, s) {
5619
6027
  const section = s.target.sectionId ? view.byId.get(s.target.sectionId) : void 0;
5620
6028
  if (!section) return { applied: false, target: s.target.sectionId ?? "?", reason: "target section not in the local view" };
5621
6029
  if (section.storage.type === "repo") {
5622
- const file = isDoc(section.storage.path) ? containedPath(view.root, section.storage.path) : null;
6030
+ const file2 = isDoc(section.storage.path) ? containedPath(view.root, section.storage.path) : null;
5623
6031
  const ours = !view.repo || section.storage.repo === view.repo;
5624
- if (ours && file && fs11.existsSync(file)) {
5625
- const before = fs11.readFileSync(file, "utf8");
6032
+ if (ours && file2 && fs12.existsSync(file2)) {
6033
+ const before = fs12.readFileSync(file2, "utf8");
5626
6034
  const res2 = applyOpToMarkdown(before, section.storage.anchor, op);
5627
6035
  if (res2.ok) {
5628
6036
  const changed = res2.text !== before;
5629
- if (changed) fs11.writeFileSync(file, res2.text);
6037
+ if (changed) fs12.writeFileSync(file2, res2.text);
5630
6038
  const overlay2 = { ...base, kind: "working-tree", sectionId: section.id, file: section.storage.path, anchor: section.storage.anchor, changed };
5631
6039
  upsertOverlay(v2, overlay2);
5632
6040
  return { applied: true, target: describeTarget(s, view), overlay: overlay2 };
@@ -5643,11 +6051,11 @@ function applyLocally(v2, view, s) {
5643
6051
  function revertWorkingTree(root, o) {
5644
6052
  if (o.changed === false) return { reverted: false, reason: "edit was a no-op" };
5645
6053
  if (!o.file) return { reverted: false, reason: "no file" };
5646
- const file = containedPath(root, o.file);
5647
- if (!file) return { reverted: false, reason: "path outside the repository" };
6054
+ const file2 = containedPath(root, o.file);
6055
+ if (!file2) return { reverted: false, reason: "path outside the repository" };
5648
6056
  let text2;
5649
6057
  try {
5650
- text2 = fs11.readFileSync(file, "utf8");
6058
+ text2 = fs12.readFileSync(file2, "utf8");
5651
6059
  } catch {
5652
6060
  return { reverted: false, reason: "file missing" };
5653
6061
  }
@@ -5667,7 +6075,7 @@ ${appendedText(o.op)}`;
5667
6075
  if (once(text2, o.op.text) >= 0 && !text2.includes(o.op.find)) next = text2.replace(o.op.text, o.op.find);
5668
6076
  }
5669
6077
  if (next === null) return { reverted: false, reason: "file changed since the trial edit" };
5670
- fs11.writeFileSync(file, next);
6078
+ fs12.writeFileSync(file2, next);
5671
6079
  return { reverted: true };
5672
6080
  }
5673
6081
  function revertParam(v2, o) {
@@ -5741,7 +6149,7 @@ var init_apply = __esm({
5741
6149
  });
5742
6150
 
5743
6151
  // src/v2/signals.ts
5744
- import fs12 from "node:fs";
6152
+ import fs13 from "node:fs";
5745
6153
  function isCorrection(text2) {
5746
6154
  const t = text2.trim().slice(0, 600);
5747
6155
  return !!t && CORRECTION_RE.test(t);
@@ -5758,16 +6166,16 @@ function codeOf(input) {
5758
6166
  if (v && typeof v === "object" && typeof v.code === "string") return v.code;
5759
6167
  return null;
5760
6168
  }
5761
- function scanTranscript(file) {
6169
+ function scanTranscript(file2) {
5762
6170
  const empty = { facts: { turns: [], userMessages: 0, toolCalls: 0, toolFailures: 0 }, snippets: [] };
5763
- if (!file) return empty;
6171
+ if (!file2) return empty;
5764
6172
  let raw;
5765
6173
  try {
5766
- raw = fs12.readFileSync(file, "utf8");
6174
+ raw = fs13.readFileSync(file2, "utf8");
5767
6175
  } catch {
5768
6176
  return empty;
5769
6177
  }
5770
- const out = { facts: parseTranscript(file), snippets: [] };
6178
+ const out = { facts: parseTranscript(file2), snippets: [] };
5771
6179
  for (const text2 of raw.split("\n")) {
5772
6180
  if (!text2.trim()) continue;
5773
6181
  let line;
@@ -5847,8 +6255,28 @@ var init_signals = __esm({
5847
6255
  });
5848
6256
 
5849
6257
  // src/v2/ui.ts
5850
- import fs13 from "node:fs";
5851
- import path9 from "node:path";
6258
+ var ui_exports = {};
6259
+ __export(ui_exports, {
6260
+ MOD_FRESH_MS: () => MOD_FRESH_MS,
6261
+ UI_FEED_VERSION: () => UI_FEED_VERSION,
6262
+ addEvent: () => addEvent,
6263
+ addServed: () => addServed,
6264
+ cliArgv: () => cliArgv,
6265
+ feedLines: () => feedLines,
6266
+ feedPath: () => feedPath,
6267
+ label: () => label,
6268
+ latestFeed: () => latestFeed,
6269
+ modActive: () => modActive,
6270
+ modPath: () => modPath,
6271
+ readFeed: () => readFeed,
6272
+ renderFeed: () => renderFeed,
6273
+ takeLines: () => takeLines,
6274
+ uiMode: () => uiMode,
6275
+ updateFeed: () => updateFeed,
6276
+ whyServed: () => whyServed
6277
+ });
6278
+ import fs14 from "node:fs";
6279
+ import path10 from "node:path";
5852
6280
  function feedPath(v2, sessionId) {
5853
6281
  return v2.p("ui", `${safe(sessionId)}.json`);
5854
6282
  }
@@ -5864,7 +6292,7 @@ function emptyFeed(v2, sessionId, now) {
5864
6292
  }
5865
6293
  function cliArgv() {
5866
6294
  const entry = process.argv[1];
5867
- return entry ? [process.execPath, path9.resolve(entry)] : ["bunshin"];
6295
+ return entry ? [process.execPath, path10.resolve(entry)] : ["bunshin"];
5868
6296
  }
5869
6297
  function updateFeed(v2, sessionId, patch, now = (/* @__PURE__ */ new Date()).toISOString()) {
5870
6298
  if (!sessionId || sessionId === "no-session") return null;
@@ -5879,7 +6307,7 @@ function updateFeed(v2, sessionId, patch, now = (/* @__PURE__ */ new Date()).toI
5879
6307
  f.cli = cliArgv();
5880
6308
  f.served = f.served.slice(0, MAX_SERVED);
5881
6309
  f.events = f.events.slice(-MAX_EVENTS);
5882
- fs13.mkdirSync(path9.dirname(feedPath(v2, sessionId)), { recursive: true });
6310
+ fs14.mkdirSync(path10.dirname(feedPath(v2, sessionId)), { recursive: true });
5883
6311
  writeJsonAtomic(feedPath(v2, sessionId), f);
5884
6312
  return f;
5885
6313
  } catch {
@@ -5980,16 +6408,16 @@ function latestFeed(v2) {
5980
6408
  const dir2 = v2.p("ui");
5981
6409
  let best = null;
5982
6410
  try {
5983
- for (const f2 of fs13.readdirSync(dir2)) {
6411
+ for (const f2 of fs14.readdirSync(dir2)) {
5984
6412
  if (!f2.endsWith(".json") || f2.endsWith(".mod.json")) continue;
5985
- const m = fs13.statSync(path9.join(dir2, f2)).mtimeMs;
6413
+ const m = fs14.statSync(path10.join(dir2, f2)).mtimeMs;
5986
6414
  if (!best || m > best.m) best = { f: f2, m };
5987
6415
  }
5988
6416
  } catch {
5989
6417
  return null;
5990
6418
  }
5991
6419
  if (!best) return null;
5992
- const f = readJson(path9.join(dir2, best.f), null);
6420
+ const f = readJson(path10.join(dir2, best.f), null);
5993
6421
  return f && f.v === UI_FEED_VERSION ? f : null;
5994
6422
  }
5995
6423
  var UI_FEED_VERSION, MAX_SERVED, MAX_EVENTS, MOD_FRESH_MS, DEFAULT_MODES;
@@ -6014,8 +6442,8 @@ __export(sync_exports, {
6014
6442
  syncV2: () => syncV2,
6015
6443
  uploadIndex: () => uploadIndex
6016
6444
  });
6017
- import fs14 from "node:fs";
6018
- import path10 from "node:path";
6445
+ import fs15 from "node:fs";
6446
+ import path11 from "node:path";
6019
6447
  function episodePayload(e) {
6020
6448
  const { orgId: _o, uploaded: _u, servedReported: _s, reportedServed: _rs, reportedLoaded: _rl, transcriptPath: _tp, ...rest } = e;
6021
6449
  void _o, _u, _s, _rs, _rl, _tp;
@@ -6048,15 +6476,15 @@ function markForRetrace(v2, { days = 30, now = Date.now() } = {}) {
6048
6476
  for (const e of v2.listEpisodes()) {
6049
6477
  if (e.upload === "header-only" || e.cliVersion || !e.transcript) continue;
6050
6478
  if (now - Date.parse(e.endedAt || e.startedAt) > days * 864e5) continue;
6051
- const file = e.transcriptPath ?? v2.readSession(e.sessionId)?.transcriptPath;
6052
- if (!file || !fs14.existsSync(file)) {
6479
+ const file2 = e.transcriptPath ?? v2.readSession(e.sessionId)?.transcriptPath;
6480
+ if (!file2 || !fs15.existsSync(file2)) {
6053
6481
  missing++;
6054
6482
  continue;
6055
6483
  }
6056
- const turns = e.turns ?? parseTranscript(file).turns.length;
6484
+ const turns = e.turns ?? parseTranscript(file2).turns.length;
6057
6485
  const { transcript: _t, ...rest } = e;
6058
6486
  void _t;
6059
- v2.writeEpisode({ ...rest, transcriptPath: file, transcriptFrom: e.transcriptFrom ?? 0, turns, cliVersion: version(), uploaded: false });
6487
+ v2.writeEpisode({ ...rest, transcriptPath: file2, transcriptFrom: e.transcriptFrom ?? 0, turns, cliVersion: version(), uploaded: false });
6060
6488
  queued++;
6061
6489
  }
6062
6490
  return { queued, missing };
@@ -6064,7 +6492,7 @@ function markForRetrace(v2, { days = 30, now = Date.now() } = {}) {
6064
6492
  async function syncV2(store, opts = {}) {
6065
6493
  const v2 = new V2Store(store);
6066
6494
  const config = store.config();
6067
- const cwd = opts.cwd ?? path10.dirname(store.root);
6495
+ const cwd = opts.cwd ?? path11.dirname(store.root);
6068
6496
  const report = { offline: !canCall(config), uploadedEpisodes: 0, deferredTraces: 0, uploadedSuggestions: 0, trialUpdates: 0, bundle: v2.readBundle() ? "cached" : "none", settled: [], errors: [] };
6069
6497
  const deadline = Date.now() + (opts.budgetMs ?? 24e4);
6070
6498
  if (report.offline) {
@@ -6211,7 +6639,7 @@ async function uploadIndex(store, cwd, deadline = Date.now() + 3e4) {
6211
6639
  const { root, index } = indexWorkingTree(v2, config, cwd, { force: true });
6212
6640
  const docs = (index.paths ?? Object.keys(index.files)).flatMap((rel) => {
6213
6641
  try {
6214
- return [{ path: rel, text: fs14.readFileSync(path10.join(root, rel), "utf8") }];
6642
+ return [{ path: rel, text: fs15.readFileSync(path11.join(root, rel), "utf8") }];
6215
6643
  } catch {
6216
6644
  return [];
6217
6645
  }
@@ -6242,7 +6670,7 @@ var init_sync = __esm({
6242
6670
  // src/v2/reflect.ts
6243
6671
  import { spawn as spawn3 } from "node:child_process";
6244
6672
  import { createHash as createHash4 } from "node:crypto";
6245
- import fs15 from "node:fs";
6673
+ import fs16 from "node:fs";
6246
6674
  function episodeIdFor(contextId, sessionId) {
6247
6675
  return `e_${createHash4("sha256").update(`${contextId}
6248
6676
  ${sessionId}`).digest("hex").slice(0, 16)}`;
@@ -6277,7 +6705,7 @@ function runClaudeFork(sessionId, prompt, { cwd, model, timeoutMs = FORK_TIMEOUT
6277
6705
  };
6278
6706
  let child;
6279
6707
  try {
6280
- child = spawn3(bin, args, { cwd: cwd && fs15.existsSync(cwd) ? cwd : void 0, env: modelEnv("claude-cli"), stdio: ["ignore", "pipe", "pipe"] });
6708
+ child = spawn3(bin, args, { cwd: cwd && fs16.existsSync(cwd) ? cwd : void 0, env: modelEnv("claude-cli"), stdio: ["ignore", "pipe", "pipe"] });
6281
6709
  } catch (e) {
6282
6710
  resolve({ ok: false, error: e instanceof Error ? e.message : String(e) });
6283
6711
  return;
@@ -6319,10 +6747,10 @@ function reflectionIndex(view, ids, task, focus, humanTurns = []) {
6319
6747
  } catch {
6320
6748
  }
6321
6749
  }
6322
- return [...chosen.values()].slice(0, 30).map(({ id, kind, layer, title, when, outline }) => ({ id, kind, layer, title, when, ...outline?.length ? { outline } : {} }));
6750
+ return withSpineAtoms([...chosen.values()].slice(0, 30), view.sections).map(({ id, kind, layer, title, when, outline }) => ({ id, kind, layer, title, when, ...outline?.length ? { outline } : {} }));
6323
6751
  }
6324
6752
  function humanTurnsOf(transcriptPath) {
6325
- if (!transcriptPath || !fs15.existsSync(transcriptPath)) return [];
6753
+ if (!transcriptPath || !fs16.existsSync(transcriptPath)) return [];
6326
6754
  try {
6327
6755
  return parseTranscript(transcriptPath).turns.filter((t) => t.role === "user" && t.text.trim()).map((t) => t.text.slice(0, 1e3));
6328
6756
  } catch {
@@ -6330,7 +6758,7 @@ function humanTurnsOf(transcriptPath) {
6330
6758
  }
6331
6759
  }
6332
6760
  function readFacts(transcriptPath) {
6333
- if (!transcriptPath || !fs15.existsSync(transcriptPath)) return null;
6761
+ if (!transcriptPath || !fs16.existsSync(transcriptPath)) return null;
6334
6762
  try {
6335
6763
  return parseTranscript(transcriptPath);
6336
6764
  } catch {
@@ -6393,7 +6821,7 @@ async function runReflectionV2(store, opts) {
6393
6821
  result.method = "fork";
6394
6822
  } else result.error = fork.error;
6395
6823
  }
6396
- if (result.method === "none" && session.transcriptPath && fs15.existsSync(session.transcriptPath)) {
6824
+ if (result.method === "none" && session.transcriptPath && fs16.existsSync(session.transcriptPath)) {
6397
6825
  const transcriptDigest = digest(facts ?? parseTranscript(session.transcriptPath), { from, maxChars: 4e4 });
6398
6826
  const res = await askJson(config, {
6399
6827
  system: "You are Bunshin's reflection pass. Follow the instructions in the user message and reply with one JSON object only.",
@@ -6522,11 +6950,11 @@ __export(route_exports, {
6522
6950
  });
6523
6951
  import { spawn as spawn4 } from "node:child_process";
6524
6952
  import { createHash as createHash5 } from "node:crypto";
6525
- import fs16 from "node:fs";
6526
- import path11 from "node:path";
6527
- function readJson2(file) {
6953
+ import fs17 from "node:fs";
6954
+ import path12 from "node:path";
6955
+ function readJson2(file2) {
6528
6956
  try {
6529
- return JSON.parse(fs16.readFileSync(file, "utf8"));
6957
+ return JSON.parse(fs17.readFileSync(file2, "utf8"));
6530
6958
  } catch {
6531
6959
  return null;
6532
6960
  }
@@ -6534,12 +6962,12 @@ function readJson2(file) {
6534
6962
  function lastReply(transcriptPath, maxBytes = 256e3) {
6535
6963
  if (!transcriptPath) return void 0;
6536
6964
  try {
6537
- const fd = fs16.openSync(transcriptPath, "r");
6965
+ const fd = fs17.openSync(transcriptPath, "r");
6538
6966
  try {
6539
- const size = fs16.fstatSync(fd).size;
6967
+ const size = fs17.fstatSync(fd).size;
6540
6968
  const len = Math.min(size, maxBytes);
6541
6969
  const buf = Buffer.alloc(len);
6542
- fs16.readSync(fd, buf, 0, len, size - len);
6970
+ fs17.readSync(fd, buf, 0, len, size - len);
6543
6971
  const lines = buf.toString("utf8").split("\n");
6544
6972
  for (let i = lines.length - 1; i >= 0; i--) {
6545
6973
  let m;
@@ -6554,7 +6982,7 @@ function lastReply(transcriptPath, maxBytes = 256e3) {
6554
6982
  if (text2.trim()) return redact2(text2.trim()).slice(0, 1500);
6555
6983
  }
6556
6984
  } finally {
6557
- fs16.closeSync(fd);
6985
+ fs17.closeSync(fd);
6558
6986
  }
6559
6987
  } catch {
6560
6988
  }
@@ -6566,9 +6994,13 @@ function promptContext(session) {
6566
6994
  const reply = lastReply(session.transcriptPath);
6567
6995
  return { ...session.task ? { first: session.task.slice(0, 1e3) } : {}, recent, ...reply ? { reply } : {} };
6568
6996
  }
6997
+ function withReply(session) {
6998
+ const reply = lastReply(session.transcriptPath);
6999
+ return reply ? { reply } : {};
7000
+ }
6569
7001
  async function routerIndex(store, v2, source) {
6570
- const file = path11.join(dir(v2), `index-${createHash5("sha256").update(source).digest("hex").slice(0, 12)}.json`);
6571
- const cached = readJson2(file);
7002
+ const file2 = path12.join(dir(v2), `index-${createHash5("sha256").update(source).digest("hex").slice(0, 12)}.json`);
7003
+ const cached = readJson2(file2);
6572
7004
  if (cached && Date.now() - Date.parse(cached.fetchedAt) < INDEX_TTL_MS) return cached;
6573
7005
  try {
6574
7006
  const res = await v2api(
@@ -6580,7 +7012,7 @@ async function routerIndex(store, v2, source) {
6580
7012
  );
6581
7013
  const next = res.unchanged && cached ? { ...cached, fetchedAt: (/* @__PURE__ */ new Date()).toISOString() } : { hash: res.hash, system: res.system ?? "", items: res.items ?? [], source, fetchedAt: (/* @__PURE__ */ new Date()).toISOString() };
6582
7014
  if (!next.system) throw new Error("the server sent no index");
6583
- writeJsonAtomic(file, next);
7015
+ writeJsonAtomic(file2, next);
6584
7016
  return next;
6585
7017
  } catch (err) {
6586
7018
  if (cached) return cached;
@@ -6643,15 +7075,16 @@ async function routeJob(store, sessionId, seq) {
6643
7075
  if (!job || job.seq !== seq || job.cancelled) return null;
6644
7076
  const started = Date.parse(job.at) || Date.now();
6645
7077
  const model = config.recall.routerModel || process.env.BUNSHIN_ROUTER_MODEL || ROUTER_MODEL;
6646
- const { picks, indexHash } = await askRouter(store, v2, sessionId, model);
7078
+ const { picks, indexHash } = await askRouter(store, v2, sessionId, model, job.kind);
7079
+ if (job.kind === "checkpoint") delete picks.serve;
6647
7080
  const answer = { seq, at: (/* @__PURE__ */ new Date()).toISOString(), ms: Date.now() - started, ...picks };
6648
7081
  writeJsonAtomic(answerFile(v2, sessionId, seq), answer);
6649
7082
  const dense = (readJob(v2, sessionId) ?? job).dense;
6650
- v2.log("v2-router", { session: sessionId, seq, serve: answer.serve ?? null, rules: answer.rules ?? [], hint: answer.hint ?? [], ms: answer.ms, modelMs: answer.modelMs, error: answer.error, dense: dense?.serve ?? null, denseHint: dense?.hint ?? [], usage: answer.usage, costUsd: answer.costUsd });
7083
+ v2.log("v2-router", { session: sessionId, seq, ...job.kind ? { kind: job.kind } : {}, serve: answer.serve ?? null, rules: answer.rules ?? [], hint: answer.hint ?? [], ms: answer.ms, modelMs: answer.modelMs, error: answer.error, dense: dense?.serve ?? null, denseHint: dense?.hint ?? [], usage: answer.usage, costUsd: answer.costUsd });
6651
7084
  await recordStats(v2, sessionId, answer, model, indexHash);
6652
7085
  return answer;
6653
7086
  }
6654
- async function askRouter(store, v2, sessionId, model) {
7087
+ async function askRouter(store, v2, sessionId, model, kind) {
6655
7088
  const config = store.config();
6656
7089
  let indexHash;
6657
7090
  try {
@@ -6661,13 +7094,14 @@ async function askRouter(store, v2, sessionId, model) {
6661
7094
  const index = await routerIndex(store, v2, session.source ?? "");
6662
7095
  if (!/^[\w-]{1,64}$/.test(index.hash)) return { picks: { error: "the router index came back with a malformed hash" } };
6663
7096
  indexHash = index.hash;
6664
- const systemFile = path11.join(dir(v2), `system-${index.hash}.txt`);
6665
- if (!fs16.existsSync(systemFile)) fs16.writeFileSync(systemFile, index.system);
6666
- const cwd = path11.join(dir(v2), "cwd");
6667
- fs16.mkdirSync(cwd, { recursive: true });
7097
+ const systemFile = path12.join(dir(v2), `system-${index.hash}.txt`);
7098
+ if (!fs17.existsSync(systemFile)) fs17.writeFileSync(systemFile, index.system);
7099
+ const cwd = path12.join(dir(v2), "cwd");
7100
+ fs17.mkdirSync(cwd, { recursive: true });
6668
7101
  const inContext2 = session.inContext ?? [...session.loaded, ...session.pushed];
6669
7102
  const titles = new Map((v2.readBundle()?.sections ?? []).map((s) => [s.id, s.skill?.name ?? s.title]));
6670
- const message = routerMessage(session.lastPrompt, promptContext(session), inContext2.map((id) => titles.get(id)).filter((t) => !!t));
7103
+ const inTitles = inContext2.map((id) => titles.get(id)).filter((t) => !!t);
7104
+ const message = kind === "checkpoint" ? checkpointMessage({ ...session.task ? { first: session.task.slice(0, 1e3) } : {}, latest: session.lastPrompt, ...withReply(session) }, session.actions ?? [], inTitles) : routerMessage(session.lastPrompt, promptContext(session), inTitles);
6671
7105
  const res = await askClaude(systemFile, message, model, cwd);
6672
7106
  const u = res.usage ?? {};
6673
7107
  const usage = { input: u.input_tokens ?? 0, cacheRead: u.cache_read_input_tokens ?? 0, cacheWrite: u.cache_creation_input_tokens ?? 0, output: u.output_tokens ?? 0, ...u.output_tokens_details?.thinking_tokens ? { thinking: u.output_tokens_details.thinking_tokens } : {} };
@@ -6702,7 +7136,7 @@ async function recordStats(v2, sessionId, a, model, indexHash) {
6702
7136
  add(stats.sessions[sessionId] ??= emptyTally());
6703
7137
  stats.model = model;
6704
7138
  if (a.usage || !stats.last) stats.last = { at: a.at, session: sessionId, ms: a.ms, costUsd: a.costUsd ?? 0, input: u.input, cacheRead: u.cacheRead, cacheWrite: u.cacheWrite, ...indexHash ? { indexHash } : {}, ...a.error ? { error: a.error } : {} };
6705
- writeJsonAtomic(path11.join(dir(v2), "stats.json"), stats);
7139
+ writeJsonAtomic(path12.join(dir(v2), "stats.json"), stats);
6706
7140
  } catch {
6707
7141
  } finally {
6708
7142
  release?.();
@@ -6710,10 +7144,10 @@ async function recordStats(v2, sessionId, a, model, indexHash) {
6710
7144
  }
6711
7145
  function sweepRouter(v2, now = Date.now()) {
6712
7146
  try {
6713
- for (const f of fs16.readdirSync(dir(v2))) {
7147
+ for (const f of fs17.readdirSync(dir(v2))) {
6714
7148
  if (!/\.(job|answer)\.json$/.test(f)) continue;
6715
- const p = path11.join(dir(v2), f);
6716
- if (now - fs16.statSync(p).mtimeMs > 864e5) fs16.rmSync(p, { force: true });
7149
+ const p = path12.join(dir(v2), f);
7150
+ if (now - fs17.statSync(p).mtimeMs > 864e5) fs17.rmSync(p, { force: true });
6717
7151
  }
6718
7152
  } catch {
6719
7153
  }
@@ -6731,16 +7165,16 @@ var init_route = __esm({
6731
7165
  ROUTER_MODEL = "claude-haiku-5-5";
6732
7166
  INDEX_TTL_MS = 10 * 6e4;
6733
7167
  CLAUDE_TIMEOUT_MS = 6e4;
6734
- dir = (v2) => path11.join(v2.dir, "router");
7168
+ dir = (v2) => path12.join(v2.dir, "router");
6735
7169
  safe2 = (id) => id.replace(/[^\w.-]/g, "_");
6736
- jobFile = (v2, session) => path11.join(dir(v2), `${safe2(session)}.job.json`);
6737
- answerFile = (v2, session, seq) => path11.join(dir(v2), `${safe2(session)}.${seq}.answer.json`);
7170
+ jobFile = (v2, session) => path12.join(dir(v2), `${safe2(session)}.job.json`);
7171
+ answerFile = (v2, session, seq) => path12.join(dir(v2), `${safe2(session)}.${seq}.answer.json`);
6738
7172
  readJob = (v2, session) => readJson2(jobFile(v2, session));
6739
7173
  writeJob = (v2, session, job) => writeJsonAtomic(jobFile(v2, session), job);
6740
7174
  readAnswer = (v2, session, seq) => readJson2(answerFile(v2, session, seq));
6741
7175
  emptyTally = () => ({ calls: 0, errors: 0, costUsd: 0, input: 0, cacheRead: 0, cacheWrite: 0, output: 0, msTotal: 0 });
6742
7176
  localDay = (d = /* @__PURE__ */ new Date()) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
6743
- readStats = (v2) => readJson2(path11.join(dir(v2), "stats.json"));
7177
+ readStats = (v2) => readJson2(path12.join(dir(v2), "stats.json"));
6744
7178
  }
6745
7179
  });
6746
7180
 
@@ -6756,51 +7190,51 @@ __export(uicmd_exports, {
6756
7190
  modSource: () => modSource
6757
7191
  });
6758
7192
  import { spawnSync } from "node:child_process";
6759
- import fs17 from "node:fs";
7193
+ import fs18 from "node:fs";
6760
7194
  import os3 from "node:os";
6761
- import path12 from "node:path";
7195
+ import path13 from "node:path";
6762
7196
  import { fileURLToPath } from "node:url";
6763
7197
  function modHome(home = process.env.BUNSHIN_DEPLOY_HOME || os3.homedir()) {
6764
- return path12.join(home, ".bunshin", "claude-code-ui");
7198
+ return path13.join(home, ".bunshin", "claude-code-ui");
6765
7199
  }
6766
7200
  function modSource() {
6767
- const here = path12.dirname(fileURLToPath(import.meta.url));
6768
- for (const dir2 of [path12.join(here, "claude-code-ui"), path12.join(here, "..", "claude-code-ui"), path12.resolve(here, "../../../../adapters/claude-code-ui")]) {
6769
- if (fs17.existsSync(path12.join(dir2, ".claude-plugin", "plugin.json"))) return dir2;
7201
+ const here = path13.dirname(fileURLToPath(import.meta.url));
7202
+ for (const dir2 of [path13.join(here, "claude-code-ui"), path13.join(here, "..", "claude-code-ui"), path13.resolve(here, "../../../../adapters/claude-code-ui")]) {
7203
+ if (fs18.existsSync(path13.join(dir2, ".claude-plugin", "plugin.json"))) return dir2;
6770
7204
  }
6771
7205
  return null;
6772
7206
  }
6773
7207
  function installedModVersion(home) {
6774
7208
  try {
6775
- return JSON.parse(fs17.readFileSync(path12.join(modHome(home), MOD_PLUGIN, ".claude-plugin", "plugin.json"), "utf8")).version ?? null;
7209
+ return fs18.readFileSync(path13.join(modHome(home), INSTALLED_MARKER), "utf8").trim() || null;
6776
7210
  } catch {
6777
7211
  return null;
6778
7212
  }
6779
7213
  }
6780
7214
  function copyDir(from, to) {
6781
- fs17.mkdirSync(to, { recursive: true });
6782
- for (const e of fs17.readdirSync(from, { withFileTypes: true })) {
7215
+ fs18.mkdirSync(to, { recursive: true });
7216
+ for (const e of fs18.readdirSync(from, { withFileTypes: true })) {
6783
7217
  if (e.name === "types" && from.endsWith(".claude-plugin")) continue;
6784
7218
  if (e.name === "node_modules") continue;
6785
- const a = path12.join(from, e.name);
6786
- const b = path12.join(to, e.name);
7219
+ const a = path13.join(from, e.name);
7220
+ const b = path13.join(to, e.name);
6787
7221
  if (e.isDirectory()) copyDir(a, b);
6788
- else fs17.copyFileSync(a, b);
7222
+ else fs18.copyFileSync(a, b);
6789
7223
  }
6790
7224
  }
6791
7225
  function installMod(version2, opts = {}) {
6792
7226
  const src = modSource();
6793
7227
  if (!src) throw new Error("the bunshin-ui mod is not in this build of the CLI");
6794
7228
  const home = modHome(opts.home);
6795
- const dir2 = path12.join(home, MOD_PLUGIN);
6796
- fs17.rmSync(dir2, { recursive: true, force: true });
7229
+ const dir2 = path13.join(home, MOD_PLUGIN);
7230
+ fs18.rmSync(dir2, { recursive: true, force: true });
6797
7231
  copyDir(src, dir2);
6798
- const manifest = path12.join(dir2, ".claude-plugin", "plugin.json");
6799
- const m = JSON.parse(fs17.readFileSync(manifest, "utf8"));
6800
- fs17.writeFileSync(manifest, JSON.stringify({ ...m, version: version2 }, null, 2) + "\n");
6801
- fs17.mkdirSync(path12.join(home, ".claude-plugin"), { recursive: true });
6802
- fs17.writeFileSync(
6803
- path12.join(home, ".claude-plugin", "marketplace.json"),
7232
+ const manifest = path13.join(dir2, ".claude-plugin", "plugin.json");
7233
+ const m = JSON.parse(fs18.readFileSync(manifest, "utf8"));
7234
+ fs18.writeFileSync(manifest, JSON.stringify({ ...m, version: version2 }, null, 2) + "\n");
7235
+ fs18.mkdirSync(path13.join(home, ".claude-plugin"), { recursive: true });
7236
+ fs18.writeFileSync(
7237
+ path13.join(home, ".claude-plugin", "marketplace.json"),
6804
7238
  JSON.stringify({ name: MOD_MARKETPLACE, owner: { name: "Bunshin" }, plugins: [{ name: MOD_PLUGIN, source: `./${MOD_PLUGIN}`, description: m.description }] }, null, 2) + "\n"
6805
7239
  );
6806
7240
  const run2 = opts.run ?? spawnSync;
@@ -6813,7 +7247,10 @@ function installMod(version2, opts = {}) {
6813
7247
  return r.status === 0;
6814
7248
  };
6815
7249
  if (!step(["plugin", "marketplace", "add", home])) step(["plugin", "marketplace", "update", MOD_MARKETPLACE]);
6816
- if (!step(["plugin", "install", `${MOD_PLUGIN}@${MOD_MARKETPLACE}`, "--scope", "user"])) step(["plugin", "update", `${MOD_PLUGIN}@${MOD_MARKETPLACE}`]);
7250
+ const ok = step(["plugin", "install", `${MOD_PLUGIN}@${MOD_MARKETPLACE}`, "--scope", "user"]) || step(["plugin", "update", `${MOD_PLUGIN}@${MOD_MARKETPLACE}`]);
7251
+ const marker = path13.join(home, INSTALLED_MARKER);
7252
+ if (ok) fs18.writeFileSync(marker, version2 + "\n");
7253
+ else fs18.rmSync(marker, { force: true });
6817
7254
  return { dir: dir2, version: version2, steps };
6818
7255
  }
6819
7256
  async function cmdUi(store, args, out, err, version2) {
@@ -6835,7 +7272,7 @@ async function cmdUi(store, args, out, err, version2) {
6835
7272
  `);
6836
7273
  for (const s of res.steps) out(` ${s.ok ? "\u2713" : "\xB7"} ${s.command}${s.ok ? "" : `: ${s.output.split("\n")[0] ?? ""}`}
6837
7274
  `);
6838
- out(installed ? "The mod loads in new Claude Code sessions (and after /reload-plugins): a Bunshin band above the prompt, /bunshin, toasts.\nUntil it runs, Bunshin prints one short line per event instead.\n" : "Could not install with `claude plugin`; install it yourself:\n claude plugin marketplace add " + path12.dirname(res.dir) + "\n claude plugin install bunshin-ui@bunshin-local --scope user\n");
7275
+ out(installed ? "The mod loads in new Claude Code sessions (and after /reload-plugins): a Bunshin band above the prompt, /bunshin, toasts.\nUntil it runs, Bunshin prints one short line per event instead.\n" : "Could not install with `claude plugin`; install it yourself:\n claude plugin marketplace add " + path13.dirname(res.dir) + "\n claude plugin install bunshin-ui@bunshin-local --scope user\n");
6839
7276
  }
6840
7277
  return installed || !failed.length ? 0 : 1;
6841
7278
  }
@@ -6893,7 +7330,7 @@ Claude Code mod: ${v ? `bunshin-ui ${v} (${modHome()})` : "not installed (bunshi
6893
7330
  show();
6894
7331
  return 0;
6895
7332
  }
6896
- var str2, bool, MOD_PLUGIN, MOD_MARKETPLACE, HARNESSES, MODES;
7333
+ var str2, bool, MOD_PLUGIN, MOD_MARKETPLACE, HARNESSES, MODES, INSTALLED_MARKER;
6897
7334
  var init_uicmd = __esm({
6898
7335
  "src/v2/uicmd.ts"() {
6899
7336
  "use strict";
@@ -6905,6 +7342,7 @@ var init_uicmd = __esm({
6905
7342
  MOD_MARKETPLACE = "bunshin-local";
6906
7343
  HARNESSES = ["claude-code", "codex", "pi", "other"];
6907
7344
  MODES = ["auto", "mod", "widget", "lines", "off"];
7345
+ INSTALLED_MARKER = ".installed-version";
6908
7346
  }
6909
7347
  });
6910
7348
 
@@ -6916,19 +7354,19 @@ __export(update_exports, {
6916
7354
  updateCheckDue: () => updateCheckDue,
6917
7355
  updateNotice: () => updateNotice
6918
7356
  });
6919
- import fs18 from "node:fs";
6920
- import path13 from "node:path";
7357
+ import fs19 from "node:fs";
7358
+ import path14 from "node:path";
6921
7359
  function readState2() {
6922
7360
  try {
6923
- return JSON.parse(fs18.readFileSync(stateFile(), "utf8"));
7361
+ return JSON.parse(fs19.readFileSync(stateFile(), "utf8"));
6924
7362
  } catch {
6925
7363
  return {};
6926
7364
  }
6927
7365
  }
6928
7366
  function writeState(s) {
6929
7367
  try {
6930
- fs18.mkdirSync(path13.dirname(stateFile()), { recursive: true });
6931
- fs18.writeFileSync(stateFile(), JSON.stringify(s, null, 2) + "\n");
7368
+ fs19.mkdirSync(path14.dirname(stateFile()), { recursive: true });
7369
+ fs19.writeFileSync(stateFile(), JSON.stringify(s, null, 2) + "\n");
6932
7370
  } catch {
6933
7371
  }
6934
7372
  }
@@ -6978,14 +7416,14 @@ var init_update = __esm({
6978
7416
  PKG = "@bunshin-cc/bunshin";
6979
7417
  LATEST_URL = `https://registry.npmjs.org/${PKG.replace("/", "%2f")}/latest`;
6980
7418
  DAY = 864e5;
6981
- stateFile = () => path13.join(homeDir(), ".bunshin", "update.json");
7419
+ stateFile = () => path14.join(homeDir(), ".bunshin", "update.json");
6982
7420
  disabled = () => process.env.BUNSHIN_NO_UPDATE_CHECK === "1" || process.env.BUNSHIN_NO_UPDATE_CHECK === "true";
6983
7421
  }
6984
7422
  });
6985
7423
 
6986
7424
  // src/v2/hooks.ts
6987
- import fs19 from "node:fs";
6988
- import path14 from "node:path";
7425
+ import fs20 from "node:fs";
7426
+ import path15 from "node:path";
6989
7427
  function inContext(s) {
6990
7428
  return s.inContext ?? [...s.loaded, ...s.pushed];
6991
7429
  }
@@ -7052,10 +7490,13 @@ async function keepModCurrent(ctx, config) {
7052
7490
  const { version: version2 } = await Promise.resolve().then(() => (init_cli(), cli_exports));
7053
7491
  const current = version2();
7054
7492
  if (!modSource2() || installedModVersion2() === current) return;
7055
- const marker = path14.join(modHome2(), `.attempted-${current}`);
7056
- if (fs19.existsSync(marker)) return;
7057
- fs19.mkdirSync(modHome2(), { recursive: true });
7058
- fs19.writeFileSync(marker, (/* @__PURE__ */ new Date()).toISOString());
7493
+ const marker = path15.join(modHome2(), `.attempted-${current}`);
7494
+ try {
7495
+ if (Date.now() - fs20.statSync(marker).mtimeMs < 24 * 36e5) return;
7496
+ } catch {
7497
+ }
7498
+ fs20.mkdirSync(modHome2(), { recursive: true });
7499
+ fs20.writeFileSync(marker, (/* @__PURE__ */ new Date()).toISOString());
7059
7500
  ctx.detach(["--root", ctx.store.root, "ui", "install", "--quiet"], { cwd: ctx.cwd });
7060
7501
  } catch {
7061
7502
  }
@@ -7182,7 +7623,7 @@ function liveUpdate(v2, ctx, session) {
7182
7623
  }
7183
7624
  function skillHint(sec, others) {
7184
7625
  const also = others.length ? ` Also possibly relevant: ${others.map((t) => `"${t}"`).join(", ")}.` : "";
7185
- return `Bunshin: the \`${sec.skill.name}\` skill may apply: ${sec.skill.description.replace(/\s+/g, " ").trim()} If it does, invoke it (Skill tool, or \`/${sec.skill.name}\`) before doing this by hand.${also}`;
7626
+ return `Bunshin: the \`${sec.skill.name}\` skill may apply: ${sec.skill.description.replace(/\s+/g, " ").trim()} If this starts that workflow, invoke it (Skill tool, or \`/${sec.skill.name}\`). For one detail of it, don't load the whole skill: recall just that (bunshin_recall, or \`bunshin recall\`).${also}`;
7186
7627
  }
7187
7628
  async function remoteAuto(ctx, prompt, exclude, source, context) {
7188
7629
  const config = ctx.store.config();
@@ -7207,11 +7648,18 @@ function invokedSkill(prompt, sections) {
7207
7648
  const name = m[1].split(":").pop().toLowerCase();
7208
7649
  return sections.find((s) => s.skill && s.skill.name.toLowerCase() === name);
7209
7650
  }
7210
- function startRoute(v2, ctx, sessionId, now) {
7651
+ function cardIndex(sections, spine, harness) {
7652
+ if (!spine.skill) return "";
7653
+ return renderCardIndex(spine, cardsOf(spine, sections), { mcp: harness === "claude-code" });
7654
+ }
7655
+ function startRoute(v2, ctx, sessionId, now, kind) {
7211
7656
  const prev = readJob(v2, sessionId);
7212
7657
  if (prev && !prev.delivered && !prev.cancelled) v2.log("v2-router-undelivered", { session: sessionId, seq: prev.seq, answered: !!readAnswer(v2, sessionId, prev.seq) });
7213
- const job = { seq: (prev?.seq ?? 0) + 1, at: now };
7658
+ const job = { seq: (prev?.seq ?? 0) + 1, at: now, ...kind ? { kind } : {} };
7214
7659
  writeJob(v2, sessionId, job);
7660
+ v2.updateSession(sessionId, ctx.cwd, (s) => {
7661
+ s.routeCalls = s.toolCalls ?? 0;
7662
+ });
7215
7663
  ctx.detach(["--root", ctx.store.root, "route", "--session", sessionId, "--seq", String(job.seq), "--quiet"], { cwd: ctx.cwd });
7216
7664
  return job;
7217
7665
  }
@@ -7236,7 +7684,7 @@ async function onPrompt(ctx) {
7236
7684
  const config = ctx.store.config();
7237
7685
  const view = localView(v2, config, ctx.cwd, session.source !== void 0 ? { source: session.source } : {});
7238
7686
  const injected = inContext(session);
7239
- const job = config.recall.router === "claude-cli" && canCall(config) ? startRoute(v2, ctx, session.sessionId, now) : void 0;
7687
+ const job = recallRouter(config) === "claude-cli" && canCall(config) ? startRoute(v2, ctx, session.sessionId, now) : void 0;
7240
7688
  const named = invokedSkill(prompt, view.sections);
7241
7689
  if (named && job) writeJob(v2, session.sessionId, { ...job, cancelled: true });
7242
7690
  if (named) {
@@ -7253,7 +7701,8 @@ async function onPrompt(ctx) {
7253
7701
  addServed(f, { id: named.id, title: named.title, kind: named.kind, skill: named.skill.name, how: "load", why });
7254
7702
  addEvent(f, "served", `loaded ${label({ skill: named.skill.name, title: named.title, kind: named.kind })} \u2014 ${why}`);
7255
7703
  });
7256
- return withLive(deployed || !fresh2 ? {} : additional("UserPromptSubmit", renderSection(named, why, { deployed: false })));
7704
+ const cards = fresh2 ? cardIndex(view.sections, named, config.harness) : "";
7705
+ return withLive(additional("UserPromptSubmit", [deployed || !fresh2 ? "" : renderSection(named, why, { deployed: false }), cards].filter(Boolean).join("\n\n")));
7257
7706
  }
7258
7707
  const res = auto(view.sections, view.reader, prompt, { exclude: injected });
7259
7708
  const recent = session.recentPrompts ?? [];
@@ -7314,7 +7763,7 @@ async function onPrompt(ctx) {
7314
7763
  addServed(f, { id: sec.id, title: sec.title, kind: sec.kind, ...sec.skill ? { skill: sec.skill.name } : {}, how: "auto", why });
7315
7764
  addEvent(f, "served", `served ${label({ ...sec.skill ? { skill: sec.skill.name } : {}, title: sec.title, kind: sec.kind })} \u2014 ${why}`);
7316
7765
  });
7317
- return withLessons(renderSection(sec, "your prompt matches it", { ...res.anchor ? { anchor: res.anchor } : {}, deployed: !!sec.skill && deployEnabled(config, view.ctx) }));
7766
+ return withLessons([renderSection(sec, "your prompt matches it", { ...res.anchor ? { anchor: res.anchor } : {}, deployed: !!sec.skill && deployEnabled(config, view.ctx) }), cardIndex(view.sections, sec, config.harness)].filter(Boolean).join("\n\n"));
7318
7767
  }
7319
7768
  const fresh = res.hint.filter((h) => !session.hinted?.includes(h.id) && !rules.some((r) => r.id === h.id)).slice(0, 3);
7320
7769
  if (!fresh.length) return withLessons("");
@@ -7343,15 +7792,20 @@ function toolPaths(input) {
7343
7792
  }
7344
7793
  return [...new Set(out)];
7345
7794
  }
7346
- async function routedText(v2, ctx, session) {
7795
+ async function routedText(v2, ctx, session, callText) {
7347
7796
  const config = ctx.store.config();
7348
- if (config.recall.router !== "claude-cli") return "";
7797
+ if (recallRouter(config) !== "claude-cli") return "";
7349
7798
  const job = readJob(v2, session.sessionId);
7350
7799
  if (!job || job.delivered || job.cancelled) return "";
7351
7800
  const answer = readAnswer(v2, session.sessionId, job.seq);
7352
7801
  if (!answer) return "";
7802
+ const checkpoint = job.kind === "checkpoint";
7353
7803
  const fallback = !!answer.error;
7354
7804
  writeJob(v2, session.sessionId, { ...job, delivered: { at: (/* @__PURE__ */ new Date()).toISOString(), ...ctx.input.tool_name ? { tool: ctx.input.tool_name } : {}, ...fallback ? { fallback } : {} } });
7805
+ if (checkpoint && fallback) {
7806
+ v2.log("v2-router-delivered", { session: session.sessionId, seq: job.seq, kind: job.kind, tool: ctx.input.tool_name, serve: null, rules: [], hint: [], fallback, error: answer.error });
7807
+ return "";
7808
+ }
7355
7809
  const seen = new Set(inContext(session));
7356
7810
  const view = localView(v2, config, ctx.cwd, session.source !== void 0 ? { source: session.source } : {});
7357
7811
  const find = async (id) => {
@@ -7363,48 +7817,98 @@ async function routedText(v2, ctx, session) {
7363
7817
  return void 0;
7364
7818
  }
7365
7819
  };
7366
- const serveId = fallback ? job.dense?.serve : answer.serve;
7820
+ const serveId = checkpoint ? void 0 : fallback ? job.dense?.serve : answer.serve;
7367
7821
  const fresh = (ids2) => [...new Set(ids2.filter((id) => !!id && !seen.has(id)))];
7368
7822
  const [doc] = await Promise.all(fresh([serveId]).map(find));
7369
7823
  const rules = (await Promise.all(fresh(fallback ? [] : answer.rules ?? []).filter((id) => id !== doc?.id).map(find))).filter((s) => !!s);
7370
- const hints = fresh(fallback ? job.dense?.hint ?? [] : answer.hint ?? []).filter((id) => id !== doc?.id && !session.hinted?.includes(id));
7824
+ const hints = checkpoint ? [] : fresh(fallback ? job.dense?.hint ?? [] : answer.hint ?? []).filter((id) => id !== doc?.id && !session.hinted?.includes(id));
7371
7825
  const hintTitles = hints.map((id) => view.sections.find((s) => s.id === id)?.title).filter((t) => !!t);
7372
- v2.log("v2-router-delivered", { session: session.sessionId, seq: job.seq, tool: ctx.input.tool_name, afterMs: Date.now() - Date.parse(job.at), serve: doc?.id ?? null, rules: rules.map((r) => r.id), hint: hints, fallback, dense: job.dense?.serve ?? null, ...answer.error ? { error: answer.error } : {} });
7826
+ v2.log("v2-router-delivered", { session: session.sessionId, seq: job.seq, ...checkpoint ? { kind: job.kind } : {}, tool: ctx.input.tool_name, afterMs: Date.now() - Date.parse(job.at), serve: doc?.id ?? null, rules: rules.map((r) => r.id), hint: hints, fallback, dense: job.dense?.serve ?? null, ...answer.error ? { error: answer.error } : {} });
7373
7827
  const ids = [...doc ? [doc.id] : [], ...rules.map((r) => r.id)];
7374
7828
  if (!ids.length && !hintTitles.length) return "";
7829
+ const judged = routerFires(rules, session.toolCalls ?? 0, callText);
7375
7830
  v2.updateSession(session.sessionId, ctx.cwd, (s) => {
7376
7831
  addUnique(s.served, ...ids, ...hints);
7377
7832
  addUnique(s.loaded, ...ids);
7378
7833
  markInContext(s, ...ids);
7379
7834
  s.hinted = s.hinted ?? [];
7380
7835
  addUnique(s.hinted, ...hints);
7836
+ if (judged.fires.length) s.fires = [...s.fires ?? [], ...judged.fires].slice(-40);
7381
7837
  });
7838
+ recordTriggers(v2, judged.updates);
7382
7839
  const why = fallback ? "your request matches it" : "the router picked it for the user's latest request";
7840
+ const ruleWhy = checkpoint ? "the router picked it for the step your work is at" : "a lesson learned before applies to this work";
7383
7841
  updateFeed(v2, session.sessionId, (f) => {
7384
- for (const r of [...rules].reverse()) addServed(f, { id: r.id, title: r.title, kind: r.kind, how: "auto", why: "a lesson learned before applies here" });
7842
+ for (const r of [...rules].reverse()) addServed(f, { id: r.id, title: r.title, kind: r.kind, how: "auto", why: checkpoint ? "the step the work is at" : "a lesson learned before applies here" });
7385
7843
  if (doc) addServed(f, { id: doc.id, title: doc.title, kind: doc.kind, ...doc.skill ? { skill: doc.skill.name } : {}, how: "auto", why });
7386
7844
  if (doc) addEvent(f, "served", `served ${label({ ...doc.skill ? { skill: doc.skill.name } : {}, title: doc.title, kind: doc.kind })} \u2014 ${fallback ? "dense (router failed)" : "router"}`);
7387
- if (rules.length) addEvent(f, "served", `lessons: ${rules.map((r) => r.title).join(", ")}`);
7845
+ if (rules.length) addEvent(f, "served", `${checkpoint ? "at this step" : "lessons"}: ${rules.map((r) => r.title).join(", ")}`);
7388
7846
  });
7389
7847
  return [
7390
7848
  doc ? renderSection(doc, why, { deployed: !!doc.skill && deployEnabled(config, view.ctx) }) : "",
7391
- ...rules.map((r) => renderSection(r, "a lesson learned before applies to this work", { deployed: false })),
7849
+ doc ? cardIndex(view.sections, doc, config.harness) : "",
7850
+ ...rules.map((r) => renderSection(r, ruleWhy, { deployed: false })),
7392
7851
  hintTitles.length ? hintLine(hintTitles, config.harness) : ""
7393
7852
  ].filter(Boolean).join("\n\n");
7394
7853
  }
7854
+ function triggerText(v2, ctx, session, tool, callText) {
7855
+ const config = ctx.store.config();
7856
+ if (config.recall.atomTriggers === false || !tool || !callText) return "";
7857
+ const view = localView(v2, config, ctx.cwd, { index: false, ...session.source !== void 0 ? { source: session.source } : {} });
7858
+ const now = v2.readSession(session.sessionId) ?? session;
7859
+ const t = triggeredAtoms(v2, view.sections, view.reader, { tool, ...ctx.input.tool_input ? { input: ctx.input.tool_input } : {}, text: callText }, inContext(now), session.toolCalls ?? 0);
7860
+ if (!t.atoms.length) return "";
7861
+ const ids = t.atoms.map((a) => a.id);
7862
+ v2.updateSession(session.sessionId, ctx.cwd, (s) => {
7863
+ addUnique(s.pushed, ...ids);
7864
+ addUnique(s.loaded, ...ids);
7865
+ addUnique(s.served, ...ids);
7866
+ markInContext(s, ...ids);
7867
+ if (t.fires.length) s.fires = [...s.fires ?? [], ...t.fires].slice(-40);
7868
+ });
7869
+ recordTriggers(v2, t.updates);
7870
+ v2.log("v2-atom-trigger", { session: session.sessionId, tool, atoms: t.atoms.map((a, i) => `${a.id} ${t.why[i]}`) });
7871
+ updateFeed(v2, session.sessionId, (f) => {
7872
+ t.atoms.forEach((a, i) => addServed(f, { id: a.id, title: a.title, kind: a.kind, how: "push", why: t.why[i] }));
7873
+ addEvent(f, "push", `at this step: ${t.atoms.map((a) => a.title).join(", ")}`);
7874
+ });
7875
+ return t.text;
7876
+ }
7877
+ function maybeCheckpoint(v2, ctx, session) {
7878
+ const config = ctx.store.config();
7879
+ if (recallRouter(config) !== "claude-cli" || !canCall(config)) return;
7880
+ const every = config.recall.checkpointEvery ?? 20;
7881
+ if (!(every > 0) || (session.toolCalls ?? 0) - (session.routeCalls ?? 0) < every) return;
7882
+ const job = readJob(v2, session.sessionId);
7883
+ if (job && !job.delivered && !job.cancelled && Date.now() - Date.parse(job.at) < 12e4) return;
7884
+ startRoute(v2, ctx, session.sessionId, (/* @__PURE__ */ new Date()).toISOString(), "checkpoint");
7885
+ }
7395
7886
  async function onPreToolUse(ctx) {
7396
7887
  const v2 = new V2Store(ctx.store);
7888
+ const tool = ctx.input.tool_name ?? "";
7889
+ const callText = toolCallText(ctx.input.tool_input);
7890
+ let judged = [];
7397
7891
  const session = touch(v2, ctx, (s) => {
7398
7892
  s.lastActivityAt = (/* @__PURE__ */ new Date()).toISOString();
7893
+ s.toolCalls = (s.toolCalls ?? 0) + 1;
7894
+ if (tool) s.actions = [...s.actions ?? [], actionLine(tool, callText)].slice(-MAX_ACTIONS);
7895
+ judged = judgeFires(s, callText, true);
7399
7896
  });
7897
+ recordTriggers(v2, judged);
7400
7898
  const live = liveUpdate(v2, ctx, session);
7401
7899
  let routed = "";
7402
7900
  try {
7403
- routed = await routedText(v2, ctx, session);
7901
+ routed = await routedText(v2, ctx, session, callText);
7902
+ } catch {
7903
+ }
7904
+ let triggered = "";
7905
+ try {
7906
+ triggered = triggerText(v2, ctx, session, tool, callText);
7907
+ maybeCheckpoint(v2, ctx, session);
7404
7908
  } catch {
7405
7909
  }
7406
7910
  const withLive = (out) => {
7407
- const text3 = [live, routed, out.hookSpecificOutput?.additionalContext ?? ""].filter(Boolean).join("\n\n");
7911
+ const text3 = [live, routed, triggered, out.hookSpecificOutput?.additionalContext ?? ""].filter(Boolean).join("\n\n");
7408
7912
  return text3 === (out.hookSpecificOutput?.additionalContext ?? "") ? out : additional("PreToolUse", text3);
7409
7913
  };
7410
7914
  const raw = toolPaths(ctx.input.tool_input);
@@ -7442,6 +7946,15 @@ function onStop(ctx) {
7442
7946
  s.lastActivityAt = now.toISOString();
7443
7947
  });
7444
7948
  const config = ctx.store.config();
7949
+ if (session.fires?.length) {
7950
+ try {
7951
+ const reply = lastReply(ctx.input.transcript_path ?? session.transcriptPath);
7952
+ let judged = [];
7953
+ if (reply) v2.updateSession(session.sessionId, ctx.cwd, (s) => void (judged = judgeFires(s, reply, false)));
7954
+ recordTriggers(v2, judged);
7955
+ } catch {
7956
+ }
7957
+ }
7445
7958
  if (ctx.input.stop_hook_active) return {};
7446
7959
  const scan = scanTranscript(ctx.input.transcript_path ?? session.transcriptPath);
7447
7960
  if (canCall(config) && checkpointDue(session, scan, now)) {
@@ -7655,9 +8168,11 @@ var init_hooks = __esm({
7655
8168
  "src/v2/hooks.ts"() {
7656
8169
  "use strict";
7657
8170
  init_v22();
8171
+ init_store();
7658
8172
  init_redact2();
7659
8173
  init_version();
7660
8174
  init_api();
8175
+ init_atoms2();
7661
8176
  init_deploy();
7662
8177
  init_live();
7663
8178
  init_reflect3();
@@ -7682,8 +8197,8 @@ var init_hooks = __esm({
7682
8197
  });
7683
8198
 
7684
8199
  // src/hooks.ts
7685
- import fs20 from "node:fs";
7686
- import path15 from "node:path";
8200
+ import fs21 from "node:fs";
8201
+ import path16 from "node:path";
7687
8202
  function normalizeEvent(raw) {
7688
8203
  return EVENT_NAMES[String(raw ?? "").trim().toLowerCase().replace(/_/g, "-")] ?? null;
7689
8204
  }
@@ -7751,17 +8266,17 @@ async function handleHook(rawEvent, input, opts = {}) {
7751
8266
  }
7752
8267
  function deferToProject(cwd, env = process.env) {
7753
8268
  if (env.BUNSHIN_HOOK_SCOPE !== "user") return false;
7754
- let dir2 = path15.resolve(cwd);
8269
+ let dir2 = path16.resolve(cwd);
7755
8270
  for (let i = 0; i < 40; i++) {
7756
8271
  for (const f of [".claude/settings.local.json", ".claude/settings.json", ".codex/hooks.json"]) {
7757
8272
  try {
7758
- const text2 = fs20.readFileSync(path15.join(dir2, f), "utf8");
8273
+ const text2 = fs21.readFileSync(path16.join(dir2, f), "utf8");
7759
8274
  if (/\bbunshin\b[^"]*\bhook\b/.test(text2) && !/BUNSHIN_HOOK_SCOPE=user/.test(text2)) return true;
7760
8275
  } catch {
7761
8276
  }
7762
8277
  }
7763
- if (fs20.existsSync(path15.join(dir2, ".git"))) return false;
7764
- const up = path15.dirname(dir2);
8278
+ if (fs21.existsSync(path16.join(dir2, ".git"))) return false;
8279
+ const up = path16.dirname(dir2);
7765
8280
  if (up === dir2) return false;
7766
8281
  dir2 = up;
7767
8282
  }
@@ -7809,11 +8324,11 @@ var init_hooks2 = __esm({
7809
8324
  });
7810
8325
 
7811
8326
  // src/project-hooks.ts
7812
- import fs21 from "node:fs";
7813
- import path16 from "node:path";
8327
+ import fs22 from "node:fs";
8328
+ import path17 from "node:path";
7814
8329
  import { execFileSync as execFileSync4 } from "node:child_process";
7815
8330
  function codexProjectHooks(cwd) {
7816
- const legacyFile = path16.join(cwd, ".codex", "hooks.json");
8331
+ const legacyFile = path17.join(cwd, ".codex", "hooks.json");
7817
8332
  const git5 = (...args) => execFileSync4("git", ["-C", cwd, "rev-parse", ...args], {
7818
8333
  encoding: "utf8",
7819
8334
  stdio: ["ignore", "pipe", "ignore"],
@@ -7827,15 +8342,15 @@ function codexProjectHooks(cwd) {
7827
8342
  } catch {
7828
8343
  return { file: legacyFile, shared: false, legacyFile };
7829
8344
  }
7830
- const linked = fs21.realpathSync(common) !== fs21.realpathSync(directory);
8345
+ const linked = fs22.realpathSync(common) !== fs22.realpathSync(directory);
7831
8346
  if (linked) {
7832
- if (path16.basename(common) !== ".git" || !fs21.statSync(common).isDirectory()) {
8347
+ if (path17.basename(common) !== ".git" || !fs22.statSync(common).isDirectory()) {
7833
8348
  throw new Error("Codex hooks in a worktree of a bare repository are not supported yet. Use a full checkout for Bunshin setup.");
7834
8349
  }
7835
- root = path16.dirname(common);
8350
+ root = path17.dirname(common);
7836
8351
  }
7837
- const file = fs21.realpathSync(root) === fs21.realpathSync(cwd) ? legacyFile : path16.join(root, ".codex", "hooks.json");
7838
- return { file, shared: linked, legacyFile };
8352
+ const file2 = fs22.realpathSync(root) === fs22.realpathSync(cwd) ? legacyFile : path17.join(root, ".codex", "hooks.json");
8353
+ return { file: file2, shared: linked, legacyFile };
7839
8354
  }
7840
8355
  var init_project_hooks = __esm({
7841
8356
  "src/project-hooks.ts"() {
@@ -7868,8 +8383,8 @@ __export(init_exports, {
7868
8383
  runInit: () => runInit
7869
8384
  });
7870
8385
  import { execFileSync as execFileSync5 } from "node:child_process";
7871
- import fs22 from "node:fs";
7872
- import path17 from "node:path";
8386
+ import fs23 from "node:fs";
8387
+ import path18 from "node:path";
7873
8388
  import { fileURLToPath as fileURLToPath2, pathToFileURL } from "node:url";
7874
8389
  function isBunshinEntry(entry) {
7875
8390
  return entry?._bunshin === true || typeof entry?.command === "string" && /\bbunshin\b.*\bhook\b/.test(entry.command);
@@ -7915,17 +8430,17 @@ function countBunshinHooks(settings) {
7915
8430
  );
7916
8431
  }
7917
8432
  function claudeSettingsPath() {
7918
- return path17.join(homeDir(), ".claude", "settings.json");
8433
+ return path18.join(homeDir(), ".claude", "settings.json");
7919
8434
  }
7920
8435
  function installPiExtension(cwd, remove = false, scope = "repo") {
7921
- const file = scope === "global" ? path17.join(homeDir(), ".pi/agent/extensions/bunshin.js") : path17.join(cwd, ".pi/extensions/bunshin.js");
8436
+ const file2 = scope === "global" ? path18.join(homeDir(), ".pi/agent/extensions/bunshin.js") : path18.join(cwd, ".pi/extensions/bunshin.js");
7922
8437
  const marker = "// Managed by Bunshin setup.";
7923
8438
  try {
7924
- const previous = fileExists(file) ? fs22.readFileSync(file, "utf8") : "";
8439
+ const previous = fileExists(file2) ? fs23.readFileSync(file2, "utf8") : "";
7925
8440
  if (previous && !previous.startsWith(marker)) throw new Error("An existing Bunshin extension file is not managed by setup; preserve or move it before continuing.");
7926
8441
  if (remove) {
7927
- if (previous) fs22.unlinkSync(file);
7928
- return { file, installed: 0, changed: !!previous };
8442
+ if (previous) fs23.unlinkSync(file2);
8443
+ return { file: file2, installed: 0, changed: !!previous };
7929
8444
  }
7930
8445
  const extension = fileURLToPath2(new URL("./pi-extension.js", import.meta.url));
7931
8446
  if (!fileExists(extension)) throw new Error("The packaged Pi extension is missing. Reinstall @bunshin-cc/bunshin.");
@@ -7933,64 +8448,64 @@ function installPiExtension(cwd, remove = false, scope = "repo") {
7933
8448
  export { default } from ${JSON.stringify(pathToFileURL(extension).href)};
7934
8449
  `;
7935
8450
  if (text2 !== previous) {
7936
- ensureDir(path17.dirname(file));
7937
- fs22.writeFileSync(file, text2);
8451
+ ensureDir(path18.dirname(file2));
8452
+ fs23.writeFileSync(file2, text2);
7938
8453
  }
7939
- return { file, installed: 1, changed: text2 !== previous };
8454
+ return { file: file2, installed: 1, changed: text2 !== previous };
7940
8455
  } catch (error) {
7941
- return { file, installed: 0, changed: false, error: error instanceof Error ? error.message : String(error) };
8456
+ return { file: file2, installed: 0, changed: false, error: error instanceof Error ? error.message : String(error) };
7942
8457
  }
7943
8458
  }
7944
- function installClaudeHooks({ file = claudeSettingsPath(), bin = "bunshin", remove = false, harness = "claude-code", user = false, allTools = false } = {}) {
8459
+ function installClaudeHooks({ file: file2 = claudeSettingsPath(), bin = "bunshin", remove = false, harness = "claude-code", user = false, allTools = false } = {}) {
7945
8460
  try {
7946
- const before = fileExists(file) ? JSON.parse(fs22.readFileSync(file, "utf8")) : {};
8461
+ const before = fileExists(file2) ? JSON.parse(fs23.readFileSync(file2, "utf8")) : {};
7947
8462
  const after = remove ? removeBunshinHooks(before) : mergeClaudeSettings(before, { bin, harness, user, allTools });
7948
8463
  const changed = JSON.stringify(before) !== JSON.stringify(after);
7949
8464
  if (changed) {
7950
- ensureDir(path17.dirname(file));
7951
- if (fileExists(file)) {
8465
+ ensureDir(path18.dirname(file2));
8466
+ if (fileExists(file2)) {
7952
8467
  try {
7953
- fs22.copyFileSync(file, `${file}.bunshin-backup`);
8468
+ fs23.copyFileSync(file2, `${file2}.bunshin-backup`);
7954
8469
  } catch {
7955
8470
  }
7956
8471
  }
7957
- writeJsonAtomic(file, after);
8472
+ writeJsonAtomic(file2, after);
7958
8473
  }
7959
- return { file, installed: countBunshinHooks(after), changed };
8474
+ return { file: file2, installed: countBunshinHooks(after), changed };
7960
8475
  } catch (err) {
7961
- return { file, installed: 0, changed: false, error: err instanceof Error ? err.message : String(err) };
8476
+ return { file: file2, installed: 0, changed: false, error: err instanceof Error ? err.message : String(err) };
7962
8477
  }
7963
8478
  }
7964
8479
  function mcpLauncher(bin) {
7965
8480
  if (!bin || /^[\w./@+-]+$/.test(bin)) return { command: bin || "bunshin", args: ["mcp"] };
7966
8481
  let script = process.argv[1] ?? "";
7967
8482
  try {
7968
- script = fs22.realpathSync(script);
8483
+ script = fs23.realpathSync(script);
7969
8484
  } catch {
7970
8485
  }
7971
8486
  return { command: process.execPath, args: [script, "mcp"] };
7972
8487
  }
7973
- function installLearnCommand({ file, remove = false, content = LEARN_COMMAND }) {
8488
+ function installLearnCommand({ file: file2, remove = false, content = LEARN_COMMAND }) {
7974
8489
  try {
7975
- const current = fileExists(file) ? fs22.readFileSync(file, "utf8") : null;
8490
+ const current = fileExists(file2) ? fs23.readFileSync(file2, "utf8") : null;
7976
8491
  const ours = current === null || current === content;
7977
8492
  if (remove) {
7978
- if (current !== null && ours) fs22.unlinkSync(file);
7979
- return { file, installed: 0, changed: current !== null && ours };
8493
+ if (current !== null && ours) fs23.unlinkSync(file2);
8494
+ return { file: file2, installed: 0, changed: current !== null && ours };
7980
8495
  }
7981
- if (!ours) return { file, installed: 0, changed: false, error: `a different ${path17.basename(file)} is already there; left as it is` };
8496
+ if (!ours) return { file: file2, installed: 0, changed: false, error: `a different ${path18.basename(file2)} is already there; left as it is` };
7982
8497
  if (current === null) {
7983
- fs22.mkdirSync(path17.dirname(file), { recursive: true });
7984
- fs22.writeFileSync(file, content);
8498
+ fs23.mkdirSync(path18.dirname(file2), { recursive: true });
8499
+ fs23.writeFileSync(file2, content);
7985
8500
  }
7986
- return { file, installed: 1, changed: current === null };
8501
+ return { file: file2, installed: 1, changed: current === null };
7987
8502
  } catch (err) {
7988
- return { file, installed: 0, changed: false, error: err instanceof Error ? err.message : String(err) };
8503
+ return { file: file2, installed: 0, changed: false, error: err instanceof Error ? err.message : String(err) };
7989
8504
  }
7990
8505
  }
7991
- function installMcpConfig({ file, launcher, remove = false }) {
8506
+ function installMcpConfig({ file: file2, launcher, remove = false }) {
7992
8507
  try {
7993
- const before = fileExists(file) ? JSON.parse(fs22.readFileSync(file, "utf8")) : {};
8508
+ const before = fileExists(file2) ? JSON.parse(fs23.readFileSync(file2, "utf8")) : {};
7994
8509
  const servers = { ...before.mcpServers ?? {} };
7995
8510
  if (remove) delete servers.bunshin;
7996
8511
  else servers.bunshin = { type: "stdio", command: launcher.command, args: launcher.args, env: { BUNSHIN_HARNESS: "claude-code" } };
@@ -7998,16 +8513,16 @@ function installMcpConfig({ file, launcher, remove = false }) {
7998
8513
  if (!Object.keys(servers).length) delete after.mcpServers;
7999
8514
  const changed = JSON.stringify(before) !== JSON.stringify(after);
8000
8515
  if (changed) {
8001
- if (!Object.keys(after).length && fileExists(file)) fs22.unlinkSync(file);
8002
- else if (Object.keys(after).length) writeJsonAtomic(file, after);
8516
+ if (!Object.keys(after).length && fileExists(file2)) fs23.unlinkSync(file2);
8517
+ else if (Object.keys(after).length) writeJsonAtomic(file2, after);
8003
8518
  }
8004
- return { file, installed: servers.bunshin ? 1 : 0, changed };
8519
+ return { file: file2, installed: servers.bunshin ? 1 : 0, changed };
8005
8520
  } catch (err) {
8006
- return { file, installed: 0, changed: false, error: err instanceof Error ? err.message : String(err) };
8521
+ return { file: file2, installed: 0, changed: false, error: err instanceof Error ? err.message : String(err) };
8007
8522
  }
8008
8523
  }
8009
8524
  function installUserMcp({ launcher, remove = false, claude = "claude" }) {
8010
- const file = path17.join(homeDir(), ".claude.json");
8525
+ const file2 = path18.join(homeDir(), ".claude.json");
8011
8526
  const run2 = (args) => execFileSync5(claude, args, { stdio: ["ignore", "pipe", "pipe"], timeout: 2e4, env: { ...process.env, BUNSHIN_CHILD: "1" } }).toString();
8012
8527
  try {
8013
8528
  let had = false;
@@ -8022,33 +8537,33 @@ function installUserMcp({ launcher, remove = false, claude = "claude" }) {
8022
8537
  } catch {
8023
8538
  }
8024
8539
  }
8025
- if (remove) return { file, installed: 0, changed: had };
8540
+ if (remove) return { file: file2, installed: 0, changed: had };
8026
8541
  run2(["mcp", "add-json", "bunshin", JSON.stringify({ type: "stdio", command: launcher.command, args: launcher.args, env: { BUNSHIN_HARNESS: "claude-code" } }), "-s", "user"]);
8027
- return { file, installed: 1, changed: true };
8542
+ return { file: file2, installed: 1, changed: true };
8028
8543
  } catch (err) {
8029
- return { file, installed: 0, changed: false, error: err instanceof Error ? err.message.split("\n")[0] : String(err) };
8544
+ return { file: file2, installed: 0, changed: false, error: err instanceof Error ? err.message.split("\n")[0] : String(err) };
8030
8545
  }
8031
8546
  }
8032
8547
  function runInit(opts = {}) {
8033
8548
  const cwd = opts.cwd ?? process.cwd();
8034
8549
  const warnings = [];
8035
8550
  const scope = opts.scope ?? "repo";
8036
- const root = scope === "global" ? path17.join(homeDir(), ".bunshin") : path17.join(cwd, ".bunshin");
8037
- if (fs22.existsSync(root) && !new Store(root).trusted && fs22.readdirSync(root).length) {
8551
+ const root = scope === "global" ? path18.join(homeDir(), ".bunshin") : path18.join(cwd, ".bunshin");
8552
+ if (fs23.existsSync(root) && !new Store(root).trusted && fs23.readdirSync(root).length) {
8038
8553
  const aside = `${root}.untrusted-${Date.now()}`;
8039
- fs22.renameSync(root, aside);
8554
+ fs23.renameSync(root, aside);
8040
8555
  warnings.push(`moved ${root} aside to ${aside}: this user did not create it`);
8041
8556
  }
8042
- const existed = fileExists(path17.join(root, "config.json"));
8557
+ const existed = fileExists(path18.join(root, "config.json"));
8043
8558
  const store = new Store(root);
8044
8559
  store.ensureLayout();
8045
- fs22.chmodSync(root, 448);
8560
+ fs23.chmodSync(root, 448);
8046
8561
  const hookScope = opts.hooks ?? (scope === "global" ? "user" : (existed && store.trusted ? store.config().hooks : void 0) ?? "project");
8047
- if (scope === "repo" && (hookScope === "project" || fileExists(path17.join(cwd, ".git")))) {
8048
- const ignore = path17.join(cwd, ".gitignore");
8049
- const current = fileExists(ignore) ? fs22.readFileSync(ignore, "utf8") : "";
8562
+ if (scope === "repo" && (hookScope === "project" || fileExists(path18.join(cwd, ".git")))) {
8563
+ const ignore = path18.join(cwd, ".gitignore");
8564
+ const current = fileExists(ignore) ? fs23.readFileSync(ignore, "utf8") : "";
8050
8565
  if (!current.split(/\r?\n/).some((line) => /^\/?\.bunshin\/?$/.test(line.trim()))) {
8051
- fs22.appendFileSync(ignore, `${current && !current.endsWith("\n") ? "\n" : ""}.bunshin/
8566
+ fs23.appendFileSync(ignore, `${current && !current.endsWith("\n") ? "\n" : ""}.bunshin/
8052
8567
  `);
8053
8568
  }
8054
8569
  }
@@ -8078,17 +8593,17 @@ function runInit(opts = {}) {
8078
8593
  }
8079
8594
  if ((opts.removeHooks || !opts.noHooks) && (config.harness === "codex" || config.harness === "claude-code")) {
8080
8595
  const projectHooks = config.harness === "codex" && hookScope === "project" && !opts.settingsFile ? codexProjectHooks(cwd) : void 0;
8081
- const file = opts.settingsFile ?? (config.harness === "codex" ? projectHooks?.file ?? path17.join(process.env.CODEX_HOME ?? path17.join(homeDir(), ".codex"), "hooks.json") : hookScope === "project" ? path17.join(cwd, ".claude", "settings.local.json") : claudeSettingsPath());
8082
- hooks = installClaudeHooks({ file, bin: opts.bin, remove: opts.removeHooks, harness: config.harness, user: hookScope === "user" && !opts.settingsFile, allTools: config.recall.router === "claude-cli" });
8596
+ const file2 = opts.settingsFile ?? (config.harness === "codex" ? projectHooks?.file ?? path18.join(process.env.CODEX_HOME ?? path18.join(homeDir(), ".codex"), "hooks.json") : hookScope === "project" ? path18.join(cwd, ".claude", "settings.local.json") : claudeSettingsPath());
8597
+ hooks = installClaudeHooks({ file: file2, bin: opts.bin, remove: opts.removeHooks, harness: config.harness, user: hookScope === "user" && !opts.settingsFile, allTools: recallRouter(config) === "claude-cli" });
8083
8598
  if (!opts.removeHooks && !opts.settingsFile && hookScope === "user" && config.harness === "claude-code") {
8084
- const local = path17.join(cwd, ".claude", "settings.local.json");
8085
- if (fileExists(local) && path17.resolve(local) !== path17.resolve(file)) installClaudeHooks({ file: local, remove: true });
8599
+ const local = path18.join(cwd, ".claude", "settings.local.json");
8600
+ if (fileExists(local) && path18.resolve(local) !== path18.resolve(file2)) installClaudeHooks({ file: local, remove: true });
8086
8601
  }
8087
8602
  if (projectHooks?.shared) {
8088
8603
  hooks.sharedWithWorktrees = true;
8089
- if (!hooks.error && !opts.removeHooks) ensureDir(path17.dirname(projectHooks.legacyFile));
8604
+ if (!hooks.error && !opts.removeHooks) ensureDir(path18.dirname(projectHooks.legacyFile));
8090
8605
  }
8091
- if (!hooks.error && projectHooks && projectHooks.file !== projectHooks.legacyFile && fileExists(projectHooks.legacyFile) && fs22.realpathSync(projectHooks.file) !== fs22.realpathSync(projectHooks.legacyFile)) {
8606
+ if (!hooks.error && projectHooks && projectHooks.file !== projectHooks.legacyFile && fileExists(projectHooks.legacyFile) && fs23.realpathSync(projectHooks.file) !== fs23.realpathSync(projectHooks.legacyFile)) {
8092
8607
  const old = installClaudeHooks({ file: projectHooks.legacyFile, remove: true, harness: "codex" });
8093
8608
  if (old.error) hooks.error = `Could not remove old Bunshin hooks from ${old.file}: ${old.error}`;
8094
8609
  }
@@ -8098,17 +8613,17 @@ function runInit(opts = {}) {
8098
8613
  let learnCommand;
8099
8614
  if ((opts.removeHooks || !opts.noHooks) && config.harness === "claude-code") {
8100
8615
  const user = hookScope === "user";
8101
- mcp = user ? installUserMcp({ launcher: opts.mcp ?? mcpLauncher(opts.bin), remove: opts.removeHooks }) : installMcpConfig({ file: path17.join(cwd, ".mcp.json"), launcher: opts.mcp ?? mcpLauncher(opts.bin), remove: opts.removeHooks });
8616
+ mcp = user ? installUserMcp({ launcher: opts.mcp ?? mcpLauncher(opts.bin), remove: opts.removeHooks }) : installMcpConfig({ file: path18.join(cwd, ".mcp.json"), launcher: opts.mcp ?? mcpLauncher(opts.bin), remove: opts.removeHooks });
8102
8617
  if (mcp.error) warnings.push(`could not update ${mcp.file}: ${mcp.error}`);
8103
- learnCommand = installLearnCommand({ file: path17.join(user ? path17.join(homeDir(), ".claude") : path17.join(cwd, ".claude"), "commands", "learn.md"), remove: opts.removeHooks });
8618
+ learnCommand = installLearnCommand({ file: path18.join(user ? path18.join(homeDir(), ".claude") : path18.join(cwd, ".claude"), "commands", "learn.md"), remove: opts.removeHooks });
8104
8619
  if (learnCommand.error) warnings.push(`/learn not installed at ${learnCommand.file}: ${learnCommand.error}`);
8105
8620
  }
8106
8621
  let borrowCommand;
8107
8622
  if (opts.removeHooks || !opts.noHooks) {
8108
8623
  const user = hookScope === "user";
8109
- const file = config.harness === "claude-code" ? path17.join(user ? path17.join(homeDir(), ".claude") : path17.join(cwd, ".claude"), "commands", "borrow.md") : config.harness === "codex" ? path17.join(process.env.CODEX_HOME ?? path17.join(homeDir(), ".codex"), "prompts", "borrow.md") : config.harness === "pi" ? user ? path17.join(homeDir(), ".pi", "agent", "prompts", "borrow.md") : path17.join(cwd, ".pi", "prompts", "borrow.md") : null;
8110
- if (file) {
8111
- borrowCommand = installLearnCommand({ file, remove: opts.removeHooks, content: BORROW_COMMAND });
8624
+ const file2 = config.harness === "claude-code" ? path18.join(user ? path18.join(homeDir(), ".claude") : path18.join(cwd, ".claude"), "commands", "borrow.md") : config.harness === "codex" ? path18.join(process.env.CODEX_HOME ?? path18.join(homeDir(), ".codex"), "prompts", "borrow.md") : config.harness === "pi" ? user ? path18.join(homeDir(), ".pi", "agent", "prompts", "borrow.md") : path18.join(cwd, ".pi", "prompts", "borrow.md") : null;
8625
+ if (file2) {
8626
+ borrowCommand = installLearnCommand({ file: file2, remove: opts.removeHooks, content: BORROW_COMMAND });
8112
8627
  if (borrowCommand.error) warnings.push(`/borrow not installed at ${borrowCommand.file}: ${borrowCommand.error}`);
8113
8628
  }
8114
8629
  }
@@ -8264,8 +8779,8 @@ __export(commands_exports, {
8264
8779
  setupRobot: () => setupRobot,
8265
8780
  v2Status: () => v2Status
8266
8781
  });
8267
- import fs23 from "node:fs";
8268
- import path18 from "node:path";
8782
+ import fs24 from "node:fs";
8783
+ import path19 from "node:path";
8269
8784
  import { createHash as createHash6, randomBytes as randomBytes4 } from "node:crypto";
8270
8785
  function cmdReview(store, args, cwd, out, err) {
8271
8786
  const v2 = new V2Store(store);
@@ -8436,13 +8951,13 @@ function cmdSuggest(store, args, cwd, out, err) {
8436
8951
  err('bunshin suggest: usage: bunshin suggest --code <harness-relative path> [--file <local file>] [--rationale "<text>"]\n');
8437
8952
  return 1;
8438
8953
  }
8439
- const harnessDir = path18.resolve(cwd, str3(args.flags["harness-dir"]) ?? ".");
8440
- const file = str3(args.flags.file) ? path18.resolve(cwd, str3(args.flags.file)) : path18.join(harnessDir, rel);
8954
+ const harnessDir = path19.resolve(cwd, str3(args.flags["harness-dir"]) ?? ".");
8955
+ const file2 = str3(args.flags.file) ? path19.resolve(cwd, str3(args.flags.file)) : path19.join(harnessDir, rel);
8441
8956
  let content;
8442
8957
  try {
8443
- content = fs23.readFileSync(file, "utf8");
8958
+ content = fs24.readFileSync(file2, "utf8");
8444
8959
  } catch {
8445
- err(`bunshin suggest: cannot read ${file}
8960
+ err(`bunshin suggest: cannot read ${file2}
8446
8961
  `);
8447
8962
  return 1;
8448
8963
  }
@@ -8561,26 +9076,26 @@ async function cmdQuestions(store, args, out, err) {
8561
9076
  return 0;
8562
9077
  }
8563
9078
  function saveCredential(storeRoot, apiUrl, apiKey, id) {
8564
- const dir2 = path18.join(homeDir(), ".config/bunshin/credentials");
8565
- fs23.mkdirSync(dir2, { recursive: true, mode: 448 });
8566
- fs23.chmodSync(dir2, 448);
8567
- const file = path18.join(dir2, `${createHash6("sha256").update(`${storeRoot}
9079
+ const dir2 = path19.join(homeDir(), ".config/bunshin/credentials");
9080
+ fs24.mkdirSync(dir2, { recursive: true, mode: 448 });
9081
+ fs24.chmodSync(dir2, 448);
9082
+ const file2 = path19.join(dir2, `${createHash6("sha256").update(`${storeRoot}
8568
9083
  ${apiUrl}
8569
9084
  ${id}`).digest("hex")}.json`);
8570
- const tmp = `${file}.${randomBytes4(4).toString("hex")}.tmp`;
8571
- fs23.writeFileSync(tmp, JSON.stringify({ apiUrl, apiKey }) + "\n", { mode: 384, flag: "wx" });
8572
- fs23.renameSync(tmp, file);
8573
- return file;
9085
+ const tmp = `${file2}.${randomBytes4(4).toString("hex")}.tmp`;
9086
+ fs24.writeFileSync(tmp, JSON.stringify({ apiUrl, apiKey }) + "\n", { mode: 384, flag: "wx" });
9087
+ fs24.renameSync(tmp, file2);
9088
+ return file2;
8574
9089
  }
8575
9090
  async function setupRobot(opts) {
8576
9091
  if (!/^[A-Za-z0-9._-]{1,100}$/.test(opts.robotId)) throw new Error("--robot-id must be letters, digits, '.', '_' or '-'");
8577
9092
  const existing = Store.discover(opts.cwd);
8578
9093
  let store;
8579
9094
  const harness = opts.harness ?? "other";
8580
- if (existing && path18.resolve(path18.dirname(existing.root)) === path18.resolve(opts.cwd) && harness === "other") store = existing;
9095
+ if (existing && path19.resolve(path19.dirname(existing.root)) === path19.resolve(opts.cwd) && harness === "other") store = existing;
8581
9096
  else {
8582
9097
  runInit({ cwd: opts.cwd, harness, noHooks: harness === "other", ...opts.apiUrl ? { apiUrl: opts.apiUrl } : {} });
8583
- store = new Store(path18.join(opts.cwd, ".bunshin"));
9098
+ store = new Store(path19.join(opts.cwd, ".bunshin"));
8584
9099
  }
8585
9100
  let config = store.config();
8586
9101
  const apiUrl = (opts.apiUrl ?? config.apiUrl ?? "").replace(/\/$/, "");
@@ -8734,16 +9249,16 @@ __export(setup_exports, {
8734
9249
  setupProject: () => setupProject,
8735
9250
  shellQuote: () => shellQuote
8736
9251
  });
8737
- import fs24 from "node:fs";
8738
- import path19 from "node:path";
9252
+ import fs25 from "node:fs";
9253
+ import path20 from "node:path";
8739
9254
  import { createHash as createHash7, randomBytes as randomBytes5 } from "node:crypto";
8740
9255
  function executable(name) {
8741
- const directories = [...(process.env.PATH ?? "").split(path19.delimiter), path19.join(homeDir(), ".local/bin")];
9256
+ const directories = [...(process.env.PATH ?? "").split(path20.delimiter), path20.join(homeDir(), ".local/bin")];
8742
9257
  for (const directory of directories) {
8743
- const file = path19.resolve(directory, name);
9258
+ const file2 = path20.resolve(directory, name);
8744
9259
  try {
8745
- fs24.accessSync(file, fs24.constants.X_OK);
8746
- if (fs24.statSync(file).isFile()) return file;
9260
+ fs25.accessSync(file2, fs25.constants.X_OK);
9261
+ if (fs25.statSync(file2).isFile()) return file2;
8747
9262
  } catch {
8748
9263
  }
8749
9264
  }
@@ -8751,8 +9266,8 @@ function executable(name) {
8751
9266
  }
8752
9267
  function hookBinary(harness) {
8753
9268
  const agent = executable(harness === "claude-code" ? "claude" : harness);
8754
- const directories = [.../* @__PURE__ */ new Set([path19.dirname(process.execPath), path19.join(homeDir(), ".local/bin"), ...agent ? [path19.dirname(agent)] : []])];
8755
- return `PATH=${shellQuote(directories.join(path19.delimiter))}:"$PATH" ${shellQuote(process.execPath)} ${shellQuote(fs24.realpathSync(process.argv[1]))}`;
9269
+ const directories = [.../* @__PURE__ */ new Set([path20.dirname(process.execPath), path20.join(homeDir(), ".local/bin"), ...agent ? [path20.dirname(agent)] : []])];
9270
+ return `PATH=${shellQuote(directories.join(path20.delimiter))}:"$PATH" ${shellQuote(process.execPath)} ${shellQuote(fs25.realpathSync(process.argv[1]))}`;
8756
9271
  }
8757
9272
  function apiAddress(raw) {
8758
9273
  const url = new URL(raw);
@@ -8822,23 +9337,23 @@ async function setupProject(opts) {
8822
9337
  const apiKey = opts.apiKey.trim();
8823
9338
  if (!apiKey || /\s/.test(apiKey)) throw new Error("Paste the complete agent key from your Bunshin workspace.");
8824
9339
  const profile = await connectionProfile(apiUrl, apiKey);
8825
- const root = path19.join(opts.cwd, ".bunshin");
9340
+ const root = path20.join(opts.cwd, ".bunshin");
8826
9341
  const store = new Store(root);
8827
9342
  const previous = store.config();
8828
9343
  if ((previous.orgId !== profile.orgId || previous.userId !== profile.userId) && (store.listLessons().length || store.allTraces().length || store.listRecallLessons().length)) {
8829
9344
  throw new Error("This project has lessons or activity from another profile. Use a fresh project to connect this workspace.");
8830
9345
  }
8831
- const credentialDirectory = path19.join(homeDir(), ".config/bunshin/credentials");
8832
- fs24.mkdirSync(credentialDirectory, { recursive: true, mode: 448 });
8833
- fs24.chmodSync(credentialDirectory, 448);
9346
+ const credentialDirectory = path20.join(homeDir(), ".config/bunshin/credentials");
9347
+ fs25.mkdirSync(credentialDirectory, { recursive: true, mode: 448 });
9348
+ fs25.chmodSync(credentialDirectory, 448);
8834
9349
  const name = createHash7("sha256").update(`${root}
8835
9350
  ${apiUrl}
8836
9351
  ${profile.orgId}
8837
9352
  ${profile.userId}`).digest("hex");
8838
- const credentialFile = path19.join(credentialDirectory, `${name}.json`);
9353
+ const credentialFile = path20.join(credentialDirectory, `${name}.json`);
8839
9354
  const temporary = `${credentialFile}.${randomBytes5(4).toString("hex")}.tmp`;
8840
- fs24.writeFileSync(temporary, JSON.stringify({ apiUrl, apiKey }) + "\n", { mode: 384, flag: "wx" });
8841
- fs24.renameSync(temporary, credentialFile);
9355
+ fs25.writeFileSync(temporary, JSON.stringify({ apiUrl, apiKey }) + "\n", { mode: 384, flag: "wx" });
9356
+ fs25.renameSync(temporary, credentialFile);
8842
9357
  const result = runInit({
8843
9358
  cwd: opts.cwd,
8844
9359
  harness: opts.harness,
@@ -9191,8 +9706,8 @@ __export(sync_exports2, {
9191
9706
  runSync: () => runSync
9192
9707
  });
9193
9708
  import { createHash as createHash8 } from "node:crypto";
9194
- import path20 from "node:path";
9195
- import fs25 from "node:fs";
9709
+ import path21 from "node:path";
9710
+ import fs26 from "node:fs";
9196
9711
  async function api(config, method, route, body, timeoutMs = 1e4) {
9197
9712
  const ctrl = new AbortController();
9198
9713
  const timer = setTimeout(() => ctrl.abort(), timeoutMs);
@@ -9230,22 +9745,22 @@ async function mothershipLookup(config, ids, timeoutMs = 8e3) {
9230
9745
  }
9231
9746
  }
9232
9747
  async function runSync(store) {
9233
- const lock = path20.join(store.root, "sync.lock");
9748
+ const lock = path21.join(store.root, "sync.lock");
9234
9749
  const deadline = Date.now() + 12e4;
9235
9750
  for (; ; ) {
9236
9751
  try {
9237
- fs25.writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 });
9752
+ fs26.writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 });
9238
9753
  break;
9239
9754
  } catch (error) {
9240
9755
  if (error.code !== "EEXIST") throw error;
9241
9756
  try {
9242
- const owner = Number(fs25.readFileSync(lock, "utf8"));
9757
+ const owner = Number(fs26.readFileSync(lock, "utf8"));
9243
9758
  if (Number.isInteger(owner) && owner > 0) {
9244
9759
  try {
9245
9760
  process.kill(owner, 0);
9246
9761
  } catch (error2) {
9247
9762
  if (error2.code === "ESRCH") {
9248
- fs25.unlinkSync(lock);
9763
+ fs26.unlinkSync(lock);
9249
9764
  continue;
9250
9765
  }
9251
9766
  }
@@ -9264,7 +9779,7 @@ async function runSync(store) {
9264
9779
  return await syncStore(store);
9265
9780
  } finally {
9266
9781
  try {
9267
- fs25.unlinkSync(lock);
9782
+ fs26.unlinkSync(lock);
9268
9783
  } catch {
9269
9784
  }
9270
9785
  }
@@ -9292,7 +9807,7 @@ async function syncStore(store) {
9292
9807
  result.errors.push(String(e instanceof Error ? e.message : e));
9293
9808
  }
9294
9809
  }
9295
- const acknowledgementsFile = path20.join(store.root, "synced-traces.json");
9810
+ const acknowledgementsFile = path21.join(store.root, "synced-traces.json");
9296
9811
  const acknowledgements = readJson(acknowledgementsFile, {});
9297
9812
  const fingerprint2 = (trace) => createHash8("sha256").update(JSON.stringify(trace)).digest("hex");
9298
9813
  const traces = store.allTraces().filter((t) => acknowledgements[t.id] !== fingerprint2(t)).slice(0, 50);
@@ -9547,31 +10062,31 @@ __export(demo_exports, {
9547
10062
  runDemo: () => runDemo
9548
10063
  });
9549
10064
  import assert from "node:assert/strict";
9550
- import fs26 from "node:fs";
10065
+ import fs27 from "node:fs";
9551
10066
  import os4 from "node:os";
9552
- import path21 from "node:path";
10067
+ import path22 from "node:path";
9553
10068
  async function runDemo(write) {
9554
- const root = fs26.mkdtempSync(path21.join(os4.tmpdir(), "bunshin-demo-"));
10069
+ const root = fs27.mkdtempSync(path22.join(os4.tmpdir(), "bunshin-demo-"));
9555
10070
  try {
9556
- const store = Store.init(root, { ...APR_ENGINEER, apiUrl: "" });
9557
- const { lessons, constraint, workflow } = aprScenario();
10071
+ const store = Store.init(root, { ...DEMO_ENGINEER, apiUrl: "" });
10072
+ const { lessons, constraint, workflow } = demoScenario();
9558
10073
  for (const lesson of lessons) store.saveLesson(lesson);
9559
- const result = await runRecall(store, { sessionId: "demo", prompt: APR_TASK, dryRun: true, offline: true });
9560
- assert(result.trace.served.includes(constraint.id), "Collections constraint was missed");
9561
- assert(result.trace.served.includes(workflow.id), "Closure workflow was missed");
10074
+ const result = await runRecall(store, { sessionId: "demo", prompt: DEMO_TASK, dryRun: true, offline: true });
10075
+ assert(result.trace.served.includes(constraint.id), "Legal hold constraint was missed");
10076
+ assert(result.trace.served.includes(workflow.id), "Deletion workflow was missed");
9562
10077
  assert(result.trace.candidates.every((c) => !["l_00000003", "l_00000005", "l_00000006"].includes(c.lessonId)), "Restricted or superseded knowledge entered the candidate list");
9563
- write(`Bunshin APR demo \u2014 synthetic data, offline scoring
10078
+ write(`Bunshin demo \u2014 synthetic data, offline scoring
9564
10079
 
9565
- Task: ${APR_TASK}
10080
+ Task: ${DEMO_TASK}
9566
10081
 
9567
10082
  `);
9568
10083
  write(result.text);
9569
- write("\nPASS: Collections constraint and workflow recalled; C-suite, other-company, and superseded lessons excluded.\n");
10084
+ write("\nPASS: Legal hold constraint and deletion workflow recalled; C-suite, other-company, and superseded lessons excluded.\n");
9570
10085
  } finally {
9571
- fs26.rmSync(root, { recursive: true, force: true });
10086
+ fs27.rmSync(root, { recursive: true, force: true });
9572
10087
  }
9573
10088
  }
9574
- var init_demo = __esm({
10089
+ var init_demo2 = __esm({
9575
10090
  "src/demo.ts"() {
9576
10091
  "use strict";
9577
10092
  init_src();
@@ -9581,21 +10096,21 @@ var init_demo = __esm({
9581
10096
  });
9582
10097
 
9583
10098
  // src/v2/gitremote.ts
9584
- import fs27 from "node:fs";
9585
- import path22 from "node:path";
10099
+ import fs28 from "node:fs";
10100
+ import path23 from "node:path";
9586
10101
  import { createHash as createHash9 } from "node:crypto";
9587
10102
  function saveGitCredential(apiUrl, apiKey) {
9588
- const file = gitCredentialFile();
9589
- fs27.mkdirSync(path22.dirname(file), { recursive: true, mode: 448 });
10103
+ const file2 = gitCredentialFile();
10104
+ fs28.mkdirSync(path23.dirname(file2), { recursive: true, mode: 448 });
9590
10105
  let all = {};
9591
10106
  try {
9592
- all = JSON.parse(fs27.readFileSync(file, "utf8"));
10107
+ all = JSON.parse(fs28.readFileSync(file2, "utf8"));
9593
10108
  } catch {
9594
10109
  }
9595
10110
  all[apiUrl.replace(/\/$/, "")] = apiKey;
9596
- const tmp = `${file}.${process.pid}.tmp`;
9597
- fs27.writeFileSync(tmp, JSON.stringify(all, null, 2) + "\n", { mode: 384 });
9598
- fs27.renameSync(tmp, file);
10111
+ const tmp = `${file2}.${process.pid}.tmp`;
10112
+ fs28.writeFileSync(tmp, JSON.stringify(all, null, 2) + "\n", { mode: 384 });
10113
+ fs28.renameSync(tmp, file2);
9599
10114
  }
9600
10115
  function resolveGitKey(apiUrl) {
9601
10116
  const base = apiUrl.replace(/\/$/, "");
@@ -9603,20 +10118,20 @@ function resolveGitKey(apiUrl) {
9603
10118
  const origin = urlOrigin(base);
9604
10119
  if (process.env.BUNSHIN_API_KEY && origin && trustedOrigins().has(origin)) return process.env.BUNSHIN_API_KEY;
9605
10120
  try {
9606
- const all = JSON.parse(fs27.readFileSync(gitCredentialFile(), "utf8"));
10121
+ const all = JSON.parse(fs28.readFileSync(gitCredentialFile(), "utf8"));
9607
10122
  if (all[base]) return all[base];
9608
10123
  } catch {
9609
10124
  }
9610
- const dir2 = path22.join(homeDir(), ".config/bunshin/credentials");
10125
+ const dir2 = path23.join(homeDir(), ".config/bunshin/credentials");
9611
10126
  let files = [];
9612
10127
  try {
9613
- files = fs27.readdirSync(dir2).filter((f) => f.endsWith(".json"));
10128
+ files = fs28.readdirSync(dir2).filter((f) => f.endsWith(".json"));
9614
10129
  } catch {
9615
10130
  return void 0;
9616
10131
  }
9617
10132
  for (const f of files.sort()) {
9618
10133
  try {
9619
- const c = JSON.parse(fs27.readFileSync(path22.join(dir2, f), "utf8"));
10134
+ const c = JSON.parse(fs28.readFileSync(path23.join(dir2, f), "utf8"));
9620
10135
  if (c.apiKey && c.apiUrl?.replace(/\/$/, "") === base) return c.apiKey;
9621
10136
  } catch {
9622
10137
  }
@@ -9637,7 +10152,7 @@ var init_gitremote = __esm({
9637
10152
  ZERO_SHA = "0".repeat(40);
9638
10153
  REMOTE_PATH = "/v1/git/repos/";
9639
10154
  remoteUrl = (apiUrl, repo) => `bunshin::${apiUrl.replace(/\/$/, "")}${REMOTE_PATH}${repo}`;
9640
- gitCredentialFile = () => path22.join(homeDir(), ".config/bunshin/git-credentials.json");
10155
+ gitCredentialFile = () => path23.join(homeDir(), ".config/bunshin/git-credentials.json");
9641
10156
  GitApiError = class extends Error {
9642
10157
  constructor(status, message, body = null) {
9643
10158
  super(message);
@@ -9729,8 +10244,8 @@ __export(gitrepo_exports, {
9729
10244
  githubReferences: () => githubReferences,
9730
10245
  repoFromUrl: () => repoFromUrl
9731
10246
  });
9732
- import fs28 from "node:fs";
9733
- import path23 from "node:path";
10247
+ import fs29 from "node:fs";
10248
+ import path24 from "node:path";
9734
10249
  import { spawnSync as spawnSync2 } from "node:child_process";
9735
10250
  function git3(cwd, args, opts = {}) {
9736
10251
  const r = spawnSync2("git", ["-C", cwd, ...args], { encoding: "utf8", stdio: opts.inherit ? ["ignore", "inherit", "inherit"] : ["ignore", "pipe", "pipe"], maxBuffer: 256 * 1024 * 1024 });
@@ -9739,9 +10254,9 @@ function git3(cwd, args, opts = {}) {
9739
10254
  return res;
9740
10255
  }
9741
10256
  function onPath(name) {
9742
- for (const dir2 of (process.env.PATH ?? "").split(path23.delimiter)) {
10257
+ for (const dir2 of (process.env.PATH ?? "").split(path24.delimiter)) {
9743
10258
  try {
9744
- fs28.accessSync(path23.join(dir2, name), fs28.constants.X_OK);
10259
+ fs29.accessSync(path24.join(dir2, name), fs29.constants.X_OK);
9745
10260
  return true;
9746
10261
  } catch {
9747
10262
  }
@@ -9825,11 +10340,11 @@ function switchOrigin(root, url, out) {
9825
10340
  }
9826
10341
  async function cmdImport(args, cwd, out, err) {
9827
10342
  requireHelper();
9828
- const root = toplevel(path23.resolve(str4(args.flags.path) ?? args._[1] ?? cwd));
10343
+ const root = toplevel(path24.resolve(str4(args.flags.path) ?? args._[1] ?? cwd));
9829
10344
  if (git3(root, ["rev-parse", "--is-shallow-repository"]).out.trim() === "true") throw new Error("this clone is shallow; fetch the full history first: git fetch --unshallow");
9830
10345
  const rs = remotes(root);
9831
10346
  const originUrl = rs.get("origin");
9832
- const name = str4(args.flags.name) ?? (originUrl && !originUrl.startsWith("bunshin::") ? repoFromUrl(originUrl) : null) ?? `${path23.basename(path23.dirname(root))}/${path23.basename(root)}`;
10347
+ const name = str4(args.flags.name) ?? (originUrl && !originUrl.startsWith("bunshin::") ? repoFromUrl(originUrl) : null) ?? `${path24.basename(path24.dirname(root))}/${path24.basename(root)}`;
9833
10348
  const client = await connect(args, cwd);
9834
10349
  const url = remoteUrl(client.apiUrl, name);
9835
10350
  const fromOrigin = !!originUrl && !originUrl.startsWith("bunshin::") && !bool3(args.flags.local);
@@ -9905,7 +10420,7 @@ ${refsToGithub.length} line${refsToGithub.length === 1 ? "" : "s"} in the reposi
9905
10420
  if (refsToGithub.length > 40) out(` \u2026 and ${refsToGithub.length - 40} more (git grep for ${name})
9906
10421
  `);
9907
10422
  }
9908
- if (fs28.existsSync(path23.join(root, ".github"))) out(`
10423
+ if (fs29.existsSync(path24.join(root, ".github"))) out(`
9909
10424
  Note: .github/ (Actions, CODEOWNERS, templates) only works on GitHub; Bunshin does not run it.
9910
10425
  `);
9911
10426
  out(`
@@ -9916,7 +10431,7 @@ New machines clone with: bunshin repo clone ${name}
9916
10431
  }
9917
10432
  async function cmdAttach(args, cwd, out, err) {
9918
10433
  requireHelper();
9919
- const root = toplevel(path23.resolve(str4(args.flags.path) ?? cwd));
10434
+ const root = toplevel(path24.resolve(str4(args.flags.path) ?? cwd));
9920
10435
  const rs = remotes(root);
9921
10436
  const originUrl = rs.get("origin");
9922
10437
  const name = str4(args.flags.name) ?? args._[1] ?? (originUrl ? repoFromUrl(originUrl) : null);
@@ -9964,12 +10479,12 @@ async function cmdClone(args, cwd, out) {
9964
10479
  const dir2 = args._[2] ?? name.split("/")[1];
9965
10480
  const r = spawnSync2("git", ["clone", remoteUrl(client.apiUrl, name), dir2], { cwd, stdio: "inherit" });
9966
10481
  if (r.status !== 0) return r.status ?? 1;
9967
- out(`Cloned ${name} into ${path23.resolve(cwd, dir2)}
10482
+ out(`Cloned ${name} into ${path24.resolve(cwd, dir2)}
9968
10483
  `);
9969
10484
  return 0;
9970
10485
  }
9971
10486
  async function cmdVerify(args, cwd, out, err) {
9972
- const root = toplevel(path23.resolve(str4(args.flags.path) ?? cwd));
10487
+ const root = toplevel(path24.resolve(str4(args.flags.path) ?? cwd));
9973
10488
  const rs = remotes(root);
9974
10489
  const originUrl = rs.get("origin") ?? "";
9975
10490
  if (!originUrl.startsWith("bunshin::")) throw new Error("origin is not a Bunshin repository (run bunshin repo attach)");
@@ -10132,22 +10647,22 @@ __export(runner_exports, {
10132
10647
  setupText: () => setupText
10133
10648
  });
10134
10649
  import { spawnSync as spawnSync3 } from "node:child_process";
10135
- import fs29 from "node:fs";
10650
+ import fs30 from "node:fs";
10136
10651
  import os5 from "node:os";
10137
- import path24 from "node:path";
10652
+ import path25 from "node:path";
10138
10653
  function runnerHome(home = process.env.BUNSHIN_RUNNER_HOME || os5.homedir()) {
10139
- return path24.join(home, ".bunshin", "runner");
10654
+ return path25.join(home, ".bunshin", "runner");
10140
10655
  }
10141
10656
  function readInstalled(home) {
10142
10657
  try {
10143
- return JSON.parse(fs29.readFileSync(path24.join(runnerHome(home), "config.json"), "utf8"));
10658
+ return JSON.parse(fs30.readFileSync(path25.join(runnerHome(home), "config.json"), "utf8"));
10144
10659
  } catch {
10145
10660
  return null;
10146
10661
  }
10147
10662
  }
10148
10663
  function connection(args, cwd) {
10149
10664
  const saved = readInstalled();
10150
- const store = saved && path24.resolve(cwd).startsWith(runnerHome()) ? null : Store.discover(cwd);
10665
+ const store = saved && path25.resolve(cwd).startsWith(runnerHome()) ? null : Store.discover(cwd);
10151
10666
  const config = store?.config();
10152
10667
  const key = str5(args.flags.key) || process.env.BUNSHIN_RUNNER_KEY || process.env.BUNSHIN_API_KEY || config?.apiKey || saved?.key || "";
10153
10668
  const apiUrl = (str5(args.flags["api-url"]) || process.env.BUNSHIN_API_URL || config?.apiUrl || saved?.apiUrl || DEFAULT_API).replace(/\/$/, "");
@@ -10207,9 +10722,9 @@ async function runOnce(c, args, out, err) {
10207
10722
  const [job] = await lease(c, args);
10208
10723
  if (!job) break;
10209
10724
  const started = Date.now();
10210
- const scratch = fs29.mkdtempSync(path24.join(os5.tmpdir(), "bunshin-job-"));
10725
+ const scratch = fs30.mkdtempSync(path25.join(os5.tmpdir(), "bunshin-job-"));
10211
10726
  const res = await askJson(config, { system: job.system, user: job.prompt, schema: job.schema, enforceSchema: false, timeoutMs: 15 * 6e4, maxTokens: 16e3, cwd: scratch }).finally(
10212
- () => fs29.rmSync(scratch, { recursive: true, force: true })
10727
+ () => fs30.rmSync(scratch, { recursive: true, force: true })
10213
10728
  );
10214
10729
  const model = config.backend === "codex-cli" ? config.codexModel ?? "codex default" : config.backend === "pi-cli" ? config.piModel ?? "pi default" : config.model;
10215
10730
  if (!res.ok) {
@@ -10299,24 +10814,24 @@ function renderCheck(id, c) {
10299
10814
  }
10300
10815
  function logAnswer(entry) {
10301
10816
  try {
10302
- fs29.mkdirSync(runnerHome(), { recursive: true });
10303
- fs29.appendFileSync(path24.join(runnerHome(), "log.jsonl"), `${JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), ...entry })}
10817
+ fs30.mkdirSync(runnerHome(), { recursive: true });
10818
+ fs30.appendFileSync(path25.join(runnerHome(), "log.jsonl"), `${JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), ...entry })}
10304
10819
  `);
10305
10820
  } catch {
10306
10821
  }
10307
10822
  }
10308
10823
  function which(name) {
10309
- for (const d of [...(process.env.PATH || "").split(path24.delimiter), path24.join(os5.homedir(), ".local", "bin")]) {
10310
- if (d && fs29.existsSync(path24.join(d, name))) return path24.join(d, name);
10824
+ for (const d of [...(process.env.PATH || "").split(path25.delimiter), path25.join(os5.homedir(), ".local", "bin")]) {
10825
+ if (d && fs30.existsSync(path25.join(d, name))) return path25.join(d, name);
10311
10826
  }
10312
10827
  return null;
10313
10828
  }
10314
10829
  function scheduledCommand(backend) {
10315
- const node = path24.dirname(process.execPath);
10316
- const npx = fs29.existsSync(path24.join(node, "npx")) ? path24.join(node, "npx") : which("npx") ?? "npx";
10830
+ const node = path25.dirname(process.execPath);
10831
+ const npx = fs30.existsSync(path25.join(node, "npx")) ? path25.join(node, "npx") : which("npx") ?? "npx";
10317
10832
  const bin = BIN_OF[backend] ? which(BIN_OF[backend]) : null;
10318
- const dirs = [.../* @__PURE__ */ new Set([node, ...bin ? [path24.dirname(bin)] : [], path24.join(os5.homedir(), ".local", "bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"])];
10319
- return { argv: [npx, "-y", PKG2, "runner", "--once"], path: dirs.join(path24.delimiter) };
10833
+ const dirs = [.../* @__PURE__ */ new Set([node, ...bin ? [path25.dirname(bin)] : [], path25.join(os5.homedir(), ".local", "bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"])];
10834
+ return { argv: [npx, "-y", PKG2, "runner", "--once"], path: dirs.join(path25.delimiter) };
10320
10835
  }
10321
10836
  function launchdPlist(backend, everyMinutes, home = runnerHome()) {
10322
10837
  const cmd = scheduledCommand(backend);
@@ -10331,8 +10846,8 @@ function launchdPlist(backend, everyMinutes, home = runnerHome()) {
10331
10846
  <dict><key>PATH</key><string>${xml(cmd.path)}</string></dict>
10332
10847
  <key>WorkingDirectory</key><string>${xml(home)}</string>
10333
10848
  <key>StartInterval</key><integer>${everyMinutes * 60}</integer>
10334
- <key>StandardOutPath</key><string>${xml(path24.join(home, "runner.log"))}</string>
10335
- <key>StandardErrorPath</key><string>${xml(path24.join(home, "runner.log"))}</string>
10849
+ <key>StandardOutPath</key><string>${xml(path25.join(home, "runner.log"))}</string>
10850
+ <key>StandardErrorPath</key><string>${xml(path25.join(home, "runner.log"))}</string>
10336
10851
  <key>ProcessType</key><string>Background</string>
10337
10852
  <key>LowPriorityIO</key><true/>
10338
10853
  </dict>
@@ -10343,19 +10858,19 @@ function cronLine(backend, everyMinutes, home = runnerHome()) {
10343
10858
  const cmd = scheduledCommand(backend);
10344
10859
  const when = everyMinutes >= 60 ? `17 */${Math.max(1, Math.round(everyMinutes / 60))} * * *` : `*/${everyMinutes} * * * *`;
10345
10860
  const q = (v) => `'${v.replace(/'/g, `'\\''`)}'`;
10346
- return `${when} cd ${q(home)} && PATH=${q(cmd.path)} ${cmd.argv.map(q).join(" ")} >> ${q(path24.join(home, "runner.log"))} 2>&1 ${CRON_MARK}`;
10861
+ return `${when} cd ${q(home)} && PATH=${q(cmd.path)} ${cmd.argv.map(q).join(" ")} >> ${q(path25.join(home, "runner.log"))} 2>&1 ${CRON_MARK}`;
10347
10862
  }
10348
10863
  function launchAgentsDir(opts) {
10349
- return opts.launchAgents ?? path24.join(process.env.BUNSHIN_RUNNER_HOME || os5.homedir(), "Library", "LaunchAgents");
10864
+ return opts.launchAgents ?? path25.join(process.env.BUNSHIN_RUNNER_HOME || os5.homedir(), "Library", "LaunchAgents");
10350
10865
  }
10351
10866
  function installSchedule(backend, everyMinutes, opts = {}) {
10352
10867
  const platform = opts.platform ?? process.platform;
10353
10868
  const run2 = opts.run ?? realRun;
10354
10869
  if (platform === "darwin") {
10355
10870
  const dir2 = launchAgentsDir(opts);
10356
- const plist = path24.join(dir2, `${LAUNCHD_LABEL}.plist`);
10357
- fs29.mkdirSync(dir2, { recursive: true });
10358
- fs29.writeFileSync(plist, launchdPlist(backend, everyMinutes));
10871
+ const plist = path25.join(dir2, `${LAUNCHD_LABEL}.plist`);
10872
+ fs30.mkdirSync(dir2, { recursive: true });
10873
+ fs30.writeFileSync(plist, launchdPlist(backend, everyMinutes));
10359
10874
  const domain = `gui/${process.getuid?.() ?? 501}`;
10360
10875
  run2("launchctl", ["bootout", `${domain}/${LAUNCHD_LABEL}`]);
10361
10876
  const r = run2("launchctl", ["bootstrap", domain, plist]);
@@ -10375,10 +10890,10 @@ function removeSchedule(opts = {}) {
10375
10890
  const platform = opts.platform ?? process.platform;
10376
10891
  const run2 = opts.run ?? realRun;
10377
10892
  if (platform === "darwin") {
10378
- const plist = path24.join(launchAgentsDir(opts), `${LAUNCHD_LABEL}.plist`);
10893
+ const plist = path25.join(launchAgentsDir(opts), `${LAUNCHD_LABEL}.plist`);
10379
10894
  run2("launchctl", ["bootout", `gui/${process.getuid?.() ?? 501}/${LAUNCHD_LABEL}`]);
10380
- if (!fs29.existsSync(plist)) return "no schedule";
10381
- fs29.rmSync(plist, { force: true });
10895
+ if (!fs30.existsSync(plist)) return "no schedule";
10896
+ fs30.rmSync(plist, { force: true });
10382
10897
  return `removed ${plist}`;
10383
10898
  }
10384
10899
  const current = run2("crontab", ["-l"]);
@@ -10405,10 +10920,10 @@ async function install(args, cwd, out, err, opts = {}) {
10405
10920
  }
10406
10921
  const every = Math.max(15, Number(str5(args.flags.every) ?? 60) || 60);
10407
10922
  const home = runnerHome();
10408
- fs29.mkdirSync(home, { recursive: true, mode: 448 });
10923
+ fs30.mkdirSync(home, { recursive: true, mode: 448 });
10409
10924
  const saved = { apiUrl: c.apiUrl, key: c.key, backend, ...config.model && str5(args.flags.model) ? { model: config.model } : {}, name: c.name, every };
10410
- fs29.writeFileSync(path24.join(home, "config.json"), JSON.stringify(saved, null, 2) + "\n", { mode: 384 });
10411
- fs29.chmodSync(path24.join(home, "config.json"), 384);
10925
+ fs30.writeFileSync(path25.join(home, "config.json"), JSON.stringify(saved, null, 2) + "\n", { mode: 384 });
10926
+ fs30.chmodSync(path25.join(home, "config.json"), 384);
10412
10927
  let schedule;
10413
10928
  try {
10414
10929
  schedule = installSchedule(backend, every, opts);
@@ -10421,7 +10936,7 @@ Run it yourself: npx -y ${PKG2} runner --once
10421
10936
  out(`\u2713 Runner "${c.name}" answers ${c.apiUrl}'s model jobs with ${BACKEND_NAME[backend] ?? backend} on this computer.
10422
10937
  `);
10423
10938
  out(schedule.kind === "none" ? ` No scheduler here: run \`npx -y ${PKG2} runner --once\` on a schedule yourself.
10424
- ` : ` Every ${every} minutes while this computer is on (${schedule.kind}). Log: ${path24.join(home, "runner.log")}
10939
+ ` : ` Every ${every} minutes while this computer is on (${schedule.kind}). Log: ${path25.join(home, "runner.log")}
10425
10940
  `);
10426
10941
  out(` Stop: npx -y ${PKG2} runner uninstall
10427
10942
  `);
@@ -10438,10 +10953,10 @@ Answering what waits now\u2026
10438
10953
  function uninstall(out, opts = {}) {
10439
10954
  out(`${removeSchedule(opts)}
10440
10955
  `);
10441
- const file = path24.join(runnerHome(), "config.json");
10442
- if (fs29.existsSync(file)) {
10443
- fs29.rmSync(file, { force: true });
10444
- out(`removed ${file} (revoke the key in the console: Agent keys)
10956
+ const file2 = path25.join(runnerHome(), "config.json");
10957
+ if (fs30.existsSync(file2)) {
10958
+ fs30.rmSync(file2, { force: true });
10959
+ out(`removed ${file2} (revoke the key in the console: Agent keys)
10445
10960
  `);
10446
10961
  }
10447
10962
  return 0;
@@ -10615,17 +11130,17 @@ async function cmdRunner(args, cwd, out, err, opts = {}) {
10615
11130
  }
10616
11131
  const cmd = invocation();
10617
11132
  const text2 = renderJob(job, cmd);
10618
- const file = str5(args.flags.out);
10619
- if (!file) {
11133
+ const file2 = str5(args.flags.out);
11134
+ if (!file2) {
10620
11135
  out(text2);
10621
11136
  return 0;
10622
11137
  }
10623
- fs29.writeFileSync(file, text2, { mode: 384 });
11138
+ fs30.writeFileSync(file2, text2, { mode: 384 });
10624
11139
  const left = Math.round((Date.parse(job.leaseUntil) - Date.now()) / 6e4);
10625
11140
  out(
10626
11141
  [
10627
11142
  `JOB ${job.id} (${job.kind}), attempt ${job.attempts}, answer before ${job.leaseUntil} (${left} min left)`,
10628
- `written to ${file}: ${text2.split("\n").length.toLocaleString("en")} lines`,
11143
+ `written to ${file2}: ${text2.split("\n").length.toLocaleString("en")} lines`,
10629
11144
  `size and effort: ${effortOf(job)}`,
10630
11145
  ...jobIndex(text2).map((l) => ` ${l}`),
10631
11146
  `when done: ${cmd} runner validate ${job.id} <answer.json> && ${cmd} runner submit ${job.id} <answer.json>`,
@@ -10636,18 +11151,18 @@ async function cmdRunner(args, cwd, out, err, opts = {}) {
10636
11151
  }
10637
11152
  if (sub === "validate" || sub === "check") {
10638
11153
  const id = args._[2];
10639
- const file = args._[3] ?? "-";
11154
+ const file2 = args._[3] ?? "-";
10640
11155
  if (!id) throw new Error("usage: bunshin runner validate <job id> <file|->");
10641
- const text2 = file === "-" ? fs29.readFileSync(0, "utf8") : fs29.readFileSync(file, "utf8");
11156
+ const text2 = file2 === "-" ? fs30.readFileSync(0, "utf8") : fs30.readFileSync(file2, "utf8");
10642
11157
  const r = await call(c, "POST", `/jobs/${id}/check`, { answer: text2, runner: c.name }, 12e4);
10643
11158
  out(renderCheck(id, r.body));
10644
11159
  return r.body.ok ? 0 : 1;
10645
11160
  }
10646
11161
  if (sub === "submit") {
10647
11162
  const id = args._[2];
10648
- const file = args._[3] ?? "-";
11163
+ const file2 = args._[3] ?? "-";
10649
11164
  if (!id) throw new Error("usage: bunshin runner submit <job id> <file|-> [--force]");
10650
- const text2 = file === "-" ? fs29.readFileSync(0, "utf8") : fs29.readFileSync(file, "utf8");
11165
+ const text2 = file2 === "-" ? fs30.readFileSync(0, "utf8") : fs30.readFileSync(file2, "utf8");
10651
11166
  const check = await call(c, "POST", `/jobs/${id}/check`, { answer: text2, runner: c.name }, 12e4).catch(() => null);
10652
11167
  if (check?.body && (check.status < 400 || check.body.problems)) {
10653
11168
  out(renderCheck(id, check.body));
@@ -10671,7 +11186,7 @@ async function cmdRunner(args, cwd, out, err, opts = {}) {
10671
11186
  const since = Date.parse(str5(args.flags.since) ?? "") || Date.now() - 12 * 36e5;
10672
11187
  const entries = (() => {
10673
11188
  try {
10674
- return fs29.readFileSync(path24.join(runnerHome(), "log.jsonl"), "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l)).filter((e) => Date.parse(e.at) >= since);
11189
+ return fs30.readFileSync(path25.join(runnerHome(), "log.jsonl"), "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l)).filter((e) => Date.parse(e.at) >= since);
10675
11190
  } catch {
10676
11191
  return [];
10677
11192
  }
@@ -10741,8 +11256,8 @@ var init_runner = __esm({
10741
11256
 
10742
11257
  // src/v2/importer.ts
10743
11258
  import { execFileSync as execFileSync6 } from "node:child_process";
10744
- import fs30 from "node:fs";
10745
- import path25 from "node:path";
11259
+ import fs31 from "node:fs";
11260
+ import path26 from "node:path";
10746
11261
  function rewriteRepoPaths(text2, repoName2, pack) {
10747
11262
  const re = new RegExp(`(?<=^|[\\s\`'"(=:])(?:~|\\$\\{?[A-Za-z_][A-Za-z0-9_]*\\}?)?(?:/[\\w.@+-]+)*/${escapeRe(repoName2)}(?=[/\\s\`'")\\]]|[.,;:](?:\\s|$)|$)`, "gm");
10748
11263
  return text2.replace(re, `~/.bunshin/library/${pack}`);
@@ -10781,7 +11296,7 @@ function buildDocs(files, opts) {
10781
11296
  const main2 = `${dir2}/SKILL.md`;
10782
11297
  const text2 = rw(files.get(main2).content);
10783
11298
  const fm = frontmatterDescription(text2);
10784
- const name = path25.posix.basename(dir2);
11299
+ const name = path26.posix.basename(dir2);
10785
11300
  const bundle = {};
10786
11301
  for (const p of all.filter((x) => x.startsWith(`${dir2}/`))) {
10787
11302
  claimed.add(p);
@@ -10879,22 +11394,22 @@ function isGitRepo(root) {
10879
11394
  function workingTreeFiles(root) {
10880
11395
  const out = /* @__PURE__ */ new Map();
10881
11396
  const list2 = isGitRepo(root) ? git4(root, ["ls-files", "-z"]).split("\0").filter(Boolean) : (function walk(dir2, base = "") {
10882
- return fs30.readdirSync(dir2, { withFileTypes: true }).flatMap((e) => {
11397
+ return fs31.readdirSync(dir2, { withFileTypes: true }).flatMap((e) => {
10883
11398
  if (e.name === ".git" || e.name === "node_modules") return [];
10884
11399
  const rel = base ? `${base}/${e.name}` : e.name;
10885
- return e.isDirectory() ? walk(path25.join(dir2, e.name), rel) : e.isFile() ? [rel] : [];
11400
+ return e.isDirectory() ? walk(path26.join(dir2, e.name), rel) : e.isFile() ? [rel] : [];
10886
11401
  });
10887
11402
  })(root);
10888
11403
  for (const rel of list2) {
10889
- const abs = path25.join(root, rel);
11404
+ const abs = path26.join(root, rel);
10890
11405
  let buf;
10891
11406
  try {
10892
- buf = fs30.readFileSync(abs);
11407
+ buf = fs31.readFileSync(abs);
10893
11408
  } catch {
10894
11409
  continue;
10895
11410
  }
10896
11411
  if (!isText(buf)) continue;
10897
- const exec = (fs30.statSync(abs).mode & 73) !== 0;
11412
+ const exec = (fs31.statSync(abs).mode & 73) !== 0;
10898
11413
  out.set(rel, { content: buf.toString("utf8"), ...exec ? { mode: "x" } : {} });
10899
11414
  }
10900
11415
  return out;
@@ -10928,7 +11443,7 @@ function diffDocs(prev, next) {
10928
11443
  return { docs: next.filter((d) => before.get(d.path) !== fingerprint(d)), removed: [...before.keys()].filter((p) => !after.has(p)) };
10929
11444
  }
10930
11445
  function readSkillSystem(root, opts) {
10931
- const repoName2 = path25.basename(path25.resolve(root));
11446
+ const repoName2 = path26.basename(path26.resolve(root));
10932
11447
  const build = (files2) => buildDocs(files2, { pack: opts.pack, repoName: repoName2, ...opts.rewrite === false ? { rewrite: false } : {} });
10933
11448
  const tree = build(workingTreeFiles(root));
10934
11449
  if (!opts.history || !isGitRepo(root)) return { versions: [{ summary: `import ${opts.pack}`, docs: tree, removed: [], complete: true }], docs: tree };
@@ -11005,7 +11520,7 @@ var init_importer = __esm({
11005
11520
  escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
11006
11521
  looksGenerated = (text2) => /generated by|do not edit( by hand)?/i.test(text2.slice(0, 600));
11007
11522
  isStopHook = (text2) => /"decision"\s*:\s*"block"|decision.{0,4}block/.test(text2) && /REASON=/.test(text2);
11008
- isUpdateHook = (p, text2) => /auto-?update/i.test(path25.basename(p)) || /git (pull|fetch)/.test(text2) && /SessionStart|session start/i.test(text2);
11523
+ isUpdateHook = (p, text2) => /auto-?update/i.test(path26.basename(p)) || /git (pull|fetch)/.test(text2) && /SessionStart|session start/i.test(text2);
11009
11524
  fingerprint = (d) => JSON.stringify(d);
11010
11525
  REWRITE_SYSTEM = `You adapt a company's skill documents after its skill system moved into Bunshin.
11011
11526
 
@@ -11041,8 +11556,8 @@ __export(skills_exports, {
11041
11556
  cmdSkill: () => cmdSkill,
11042
11557
  parsePin: () => parsePin
11043
11558
  });
11044
- import fs31 from "node:fs";
11045
- import path26 from "node:path";
11559
+ import fs32 from "node:fs";
11560
+ import path27 from "node:path";
11046
11561
  function requireOnline(store, what) {
11047
11562
  if (!canCall(store.config())) throw new Error(`${what} needs the hosted library: run \`bunshin setup\` first`);
11048
11563
  }
@@ -11051,9 +11566,9 @@ async function cmdImport2(store, args, cwd, out, err) {
11051
11566
  err("usage: bunshin import skills <dir> [--pack <name>] [--layer org|team:<unit>] [--owner-team <unit>] [--no-history] [--dry-run] [--propose-rewrites]\n");
11052
11567
  return 1;
11053
11568
  }
11054
- const root = path26.resolve(cwd, args._[2]);
11055
- if (!fs31.existsSync(root)) throw new Error(`${root} does not exist`);
11056
- const pack = str6(args.flags.pack) ?? path26.basename(root);
11569
+ const root = path27.resolve(cwd, args._[2]);
11570
+ if (!fs32.existsSync(root)) throw new Error(`${root} does not exist`);
11571
+ const pack = str6(args.flags.pack) ?? path27.basename(root);
11057
11572
  const history = args.flags.history !== false && !bool4(args.flags["no-history"]);
11058
11573
  const read = readSkillSystem(root, { pack, history, ...str6(args.flags.since) ? { since: str6(args.flags.since) } : {} });
11059
11574
  const kinds = /* @__PURE__ */ new Map();
@@ -11088,7 +11603,7 @@ async function cmdImport2(store, args, cwd, out, err) {
11088
11603
  const propose = args.flags["propose-rewrites"];
11089
11604
  if (propose) {
11090
11605
  const only = typeof propose === "string" && propose !== "true" ? propose.split(",").map((x) => x.trim()).filter(Boolean) : [];
11091
- await proposeRewrites(store, read.docs.filter((d) => !only.length || only.some((o) => d.path.includes(o))), pack, path26.basename(root), out, err);
11606
+ await proposeRewrites(store, read.docs.filter((d) => !only.length || only.some((o) => d.path.includes(o))), pack, path27.basename(root), out, err);
11092
11607
  }
11093
11608
  out("Run `bunshin sync` on each machine (it runs at session start) to install the skills, instructions and files.\n");
11094
11609
  return 0;
@@ -11228,7 +11743,7 @@ ${report.skills} skills, ${report.references} references, ${report.errors.length
11228
11743
  }
11229
11744
  const graph = str6(args.flags.graph) ?? (bool4(args.flags.graph) ? "SKILLS-GRAPH.md" : void 0);
11230
11745
  if (graph) {
11231
- fs31.writeFileSync(path26.resolve(cwd, graph), renderSkillGraph(report));
11746
+ fs32.writeFileSync(path27.resolve(cwd, graph), renderSkillGraph(report));
11232
11747
  out(`graph written to ${graph}
11233
11748
  `);
11234
11749
  }
@@ -11250,12 +11765,138 @@ ${report.skills} skills, ${report.references} references, ${report.errors.length
11250
11765
  `);
11251
11766
  return r.errors.length ? 1 : 0;
11252
11767
  }
11768
+ case "split":
11769
+ return await splitSkill(store, args, byName(args._[2]), args._[2], out, err);
11253
11770
  default:
11254
- err(`bunshin skill: unknown subcommand "${sub}" (list, show, log, lint, push)
11771
+ err(`bunshin skill: unknown subcommand "${sub}" (list, show, log, lint, push, split)
11255
11772
  `);
11256
11773
  return 1;
11257
11774
  }
11258
11775
  }
11776
+ function splitPreview(f, sourceWords) {
11777
+ const u = f.plan.units;
11778
+ const count = (k) => u.filter((x) => x.kind === k).length;
11779
+ return [
11780
+ `# Split of \`${f.name}\` (v${f.version})`,
11781
+ "",
11782
+ `${sourceWords} words \u2192 spine ${words3(f.plan.spine.body)} words + ${u.length} atoms (${count("card")} cards, ${count("fact")} facts, ${count("rule")} rules).`,
11783
+ f.coverage.missing.length ? `**Not lossless: ${f.coverage.missing.length} of ${f.coverage.lines} source lines are in no unit** (listed at the end).` : `Lossless: all ${f.coverage.lines} source lines are in some unit.`,
11784
+ "",
11785
+ "Edit the .json next to this file to change anything, then send it with `bunshin skill split " + f.name + " --submit`.",
11786
+ "",
11787
+ "## Spine",
11788
+ "",
11789
+ f.plan.spine.body,
11790
+ "",
11791
+ ...u.flatMap((x) => [
11792
+ `## ${x.kind}: ${x.title}`,
11793
+ "",
11794
+ `- when: ${x.when}`,
11795
+ ...x.step ? [`- step: ${x.step}`] : [],
11796
+ ...x.triggers?.length ? [`- triggers: ${x.triggers.map((t) => `${t.tool} /${t.match}/`).join(", ")}`] : [],
11797
+ ...x.from ? [`- from: ${x.from}`] : [],
11798
+ "",
11799
+ x.body,
11800
+ ""
11801
+ ]),
11802
+ ...f.coverage.missing.length ? ["## Lines in no unit", "", ...f.coverage.missing.map((l) => `- ${l}`)] : []
11803
+ ].join("\n");
11804
+ }
11805
+ async function splitSkill(store, args, skill, name, out, err) {
11806
+ if (!name) {
11807
+ err("usage: bunshin skill split <name> [--submit] [--force]\n");
11808
+ return 1;
11809
+ }
11810
+ if (!skill?.skill) throw new Error(`no skill ${name}`);
11811
+ const v2 = new V2Store(store);
11812
+ const config = store.config();
11813
+ const files = splitPaths(v2, skill.skill.name);
11814
+ const sourceWords = words3(skill.body.slice(parseFrontmatter2(skill.body).bodyStart));
11815
+ if (bool4(args.flags.submit)) {
11816
+ if (!fs32.existsSync(files.json)) throw new Error(`no split of ${skill.skill.name} yet: run \`bunshin skill split ${skill.skill.name}\` first`);
11817
+ const f2 = JSON.parse(fs32.readFileSync(files.json, "utf8"));
11818
+ if (f2.version !== skill.version) throw new Error(`${skill.skill.name} changed since the split (v${f2.version} \u2192 v${skill.version}): split it again`);
11819
+ const plan2 = parseSplit(f2.plan);
11820
+ if (!plan2) throw new Error(`${files.json} holds no spine`);
11821
+ const coverage2 = splitCoverage(skill.body, [plan2.spine, ...plan2.units]);
11822
+ if (coverage2.missing.length && !bool4(args.flags.force)) {
11823
+ for (const l of coverage2.missing.slice(0, 20)) err(` in no unit: ${l}
11824
+ `);
11825
+ throw new Error(`the split loses ${coverage2.missing.length} of ${coverage2.lines} lines of the skill; fix ${files.json} (or send it anyway with --force)`);
11826
+ }
11827
+ const made = splitSuggestions(v2, config, skill, plan2);
11828
+ fs32.rmSync(files.json, { force: true });
11829
+ if (!canCall(config)) {
11830
+ out(`${made} suggestions queued (${plan2.units.length} atoms and the spine); they leave with the next sync and wait for owner review.
11831
+ `);
11832
+ return 0;
11833
+ }
11834
+ const r = await syncV2(store, { deploy: false });
11835
+ out(`${made} suggestion${made === 1 ? "" : "s"} written (${plan2.units.length} atoms and the spine); ${r.uploadedSuggestions} sent. They wait for owner review in the nightly${r.errors.length ? ` (errors: ${r.errors.join("; ")})` : ""}.
11836
+ `);
11837
+ return r.errors.length ? 1 : 0;
11838
+ }
11839
+ out(`Splitting ${skill.skill.name} (${sourceWords} words) into a spine and atoms; a long skill takes a few minutes\u2026
11840
+ `);
11841
+ const res = await askJson(config, {
11842
+ system: "You split agent skills into a workflow spine and atoms, losslessly. Output JSON only.",
11843
+ user: buildSplitPrompt({ name: skill.skill.name, description: skill.skill.description, body: skill.body }),
11844
+ schema: SPLIT_SCHEMA,
11845
+ maxTokens: 64e3,
11846
+ timeoutMs: 9e5
11847
+ });
11848
+ if (!res.ok) throw new Error(res.error);
11849
+ const plan = parseSplit(res.value);
11850
+ if (!plan) throw new Error("the model's answer holds no spine");
11851
+ const coverage = splitCoverage(skill.body, [plan.spine, ...plan.units]);
11852
+ const f = { skill: skill.id, name: skill.skill.name, version: skill.version, at: (/* @__PURE__ */ new Date()).toISOString(), plan, coverage };
11853
+ fs32.mkdirSync(path27.dirname(files.json), { recursive: true });
11854
+ fs32.writeFileSync(files.json, JSON.stringify(f, null, 2));
11855
+ fs32.writeFileSync(files.md, splitPreview(f, sourceWords));
11856
+ out(`spine ${words3(plan.spine.body)} words, ${plan.units.length} atoms; ${coverage.missing.length ? `NOT lossless: ${coverage.missing.length} of ${coverage.lines} lines are in no unit` : `lossless (${coverage.lines} lines)`}
11857
+ `);
11858
+ out(`Read ${files.md}; edit ${files.json} if needed; then send it with \`bunshin skill split ${skill.skill.name} --submit\`.
11859
+ `);
11860
+ return 0;
11861
+ }
11862
+ function splitSuggestions(v2, config, skill, plan) {
11863
+ const ctx = contextFor(v2, config);
11864
+ const name = skill.skill.name;
11865
+ const outline = outlineOf(plan.spine.body);
11866
+ const anchorOf2 = (step) => {
11867
+ if (!step) return void 0;
11868
+ const t = step.replace(/^[§#]\s*/, "").trim().toLowerCase();
11869
+ return (outline.find((h) => h.anchor === t || h.title.toLowerCase() === t) ?? outline.find((h) => h.anchor === slugify(t)))?.anchor;
11870
+ };
11871
+ const now = (/* @__PURE__ */ new Date()).toISOString();
11872
+ const base = { orgId: config.orgId, contextId: ctx.id, authorUserId: ctx.userId, evidenceEpisodeIds: [], trial: { uses: 0, successes: 0, failures: 0 }, origin: "import", urgency: "normal", status: "submitted", createdAt: now };
11873
+ let n = 0;
11874
+ for (const u of plan.units) {
11875
+ const step = anchorOf2(u.step);
11876
+ const s = {
11877
+ ...base,
11878
+ id: hexId("g"),
11879
+ target: { layer: skill.layer },
11880
+ op: { op: "create", section: { kind: u.kind, title: u.title, body: u.body, when: u.when, ...u.triggers?.length ? { toolTriggers: u.triggers } : {}, from: `${name}${u.from ? ` \xA7 ${u.from}` : ""}`, partOf: skill.id, ...step ? { step } : {} } },
11881
+ rationale: `split of ${name}: ${u.kind} from ${u.from ?? "the skill"}`,
11882
+ summary: `split ${name}: ${u.kind} "${u.title}"`
11883
+ };
11884
+ v2.writeSuggestion(s);
11885
+ n++;
11886
+ }
11887
+ const fm = skill.body.slice(0, parseFrontmatter2(skill.body).bodyStart);
11888
+ v2.writeSuggestion({
11889
+ ...base,
11890
+ id: hexId("g"),
11891
+ target: { sectionId: skill.id },
11892
+ op: { op: "rewrite", text: `${fm}${plan.spine.body.trim()}
11893
+ ` },
11894
+ baseVersion: skill.version,
11895
+ rationale: `split of ${name}: the skill becomes its spine; the detail moved into ${plan.units.length} atoms`,
11896
+ summary: `split ${name}: spine`
11897
+ });
11898
+ return n + 1;
11899
+ }
11259
11900
  function sinceCutoff(since) {
11260
11901
  const m = /^(\d+)\.?(day|days|week|weeks|month|months|year|years)$/.exec(since.replace(/\s+/g, ""));
11261
11902
  if (m) {
@@ -11316,12 +11957,12 @@ async function cmdLibrary(store, args, cwd, out, err) {
11316
11957
  const res = await v2api(config, "GET", "/library?limit=1");
11317
11958
  const line = `bunshin: lib@${res.version}
11318
11959
  `;
11319
- const file = str6(args.flags.write) ?? (bool4(args.flags.write) ? ".claude/skills-version" : void 0);
11320
- if (file) {
11321
- const abs = path26.resolve(cwd, file);
11322
- fs31.mkdirSync(path26.dirname(abs), { recursive: true });
11323
- fs31.writeFileSync(abs, line);
11324
- out(`${file}: ${line}`);
11960
+ const file2 = str6(args.flags.write) ?? (bool4(args.flags.write) ? ".claude/skills-version" : void 0);
11961
+ if (file2) {
11962
+ const abs = path27.resolve(cwd, file2);
11963
+ fs32.mkdirSync(path27.dirname(abs), { recursive: true });
11964
+ fs32.writeFileSync(abs, line);
11965
+ out(`${file2}: ${line}`);
11325
11966
  } else out(line);
11326
11967
  return 0;
11327
11968
  }
@@ -11330,12 +11971,12 @@ async function cmdLibrary(store, args, cwd, out, err) {
11330
11971
  const to = str6(args.flags.to);
11331
11972
  if (!to) throw new Error("--to <dir> is required");
11332
11973
  const pinFile = str6(args.flags.pin);
11333
- const pin = str6(args.flags.git) ? { git: str6(args.flags.git) } : pinFile ? parsePin(fs31.readFileSync(path26.resolve(cwd, pinFile), "utf8")) : parsePin(args._[2] ?? "");
11974
+ const pin = str6(args.flags.git) ? { git: str6(args.flags.git) } : pinFile ? parsePin(fs32.readFileSync(path27.resolve(cwd, pinFile), "utf8")) : parsePin(args._[2] ?? "");
11334
11975
  const q = pin.git ? `git=${pin.git}` : pin.version ? `version=${pin.version}` : "";
11335
11976
  if (!q) throw new Error("name a version: lib@N, --git <sha>, or --pin <file>");
11336
11977
  const snap = await v2api(config, "GET", `/library/snapshot?${q}`, void 0, { timeoutMs: 12e4 });
11337
- const dir2 = path26.resolve(cwd, to);
11338
- if (fs31.existsSync(dir2) && fs31.readdirSync(dir2).length && !bool4(args.flags.force)) throw new Error(`${dir2} is not empty (use --force)`);
11978
+ const dir2 = path27.resolve(cwd, to);
11979
+ if (fs32.existsSync(dir2) && fs32.readdirSync(dir2).length && !bool4(args.flags.force)) throw new Error(`${dir2} is not empty (use --force)`);
11339
11980
  const pack = str6(args.flags.pack);
11340
11981
  const docs = snap.sections.filter((s) => !pack || s.pack === pack);
11341
11982
  const res = materialize(docs, dir2);
@@ -11349,7 +11990,7 @@ async function cmdLibrary(store, args, cwd, out, err) {
11349
11990
  return 1;
11350
11991
  }
11351
11992
  }
11352
- var str6, bool4, skillsOf;
11993
+ var str6, bool4, skillsOf, words3, splitPaths;
11353
11994
  var init_skills = __esm({
11354
11995
  "src/v2/skills.ts"() {
11355
11996
  "use strict";
@@ -11364,6 +12005,11 @@ var init_skills = __esm({
11364
12005
  str6 = (v) => typeof v === "string" ? v : void 0;
11365
12006
  bool4 = (v) => v === true || v === "true";
11366
12007
  skillsOf = (sections) => sections.filter((s) => s.skill && (s.status === "active" || s.status === "stale"));
12008
+ words3 = (t) => t.split(/\s+/).filter(Boolean).length;
12009
+ splitPaths = (v2, name) => {
12010
+ const base = path27.join(v2.dir, "split", name.replace(/[^\w.-]/g, "_"));
12011
+ return { json: `${base}.json`, md: `${base}.md` };
12012
+ };
11367
12013
  }
11368
12014
  });
11369
12015
 
@@ -11374,27 +12020,27 @@ __export(reflect_exports, {
11374
12020
  buildLesson: () => buildLesson,
11375
12021
  runReflection: () => runReflection
11376
12022
  });
11377
- import fs32 from "node:fs";
11378
- import path27 from "node:path";
12023
+ import fs33 from "node:fs";
12024
+ import path28 from "node:path";
11379
12025
  import { createHash as createHash10 } from "node:crypto";
11380
12026
  async function runReflection(store, opts) {
11381
12027
  const empty = { lessonIds: [], used: [], missed: [], attribution: [] };
11382
- const lock = path27.join(store.root, `reflect-${createHash10("sha256").update(opts.sessionId).digest("hex")}.lock`);
12028
+ const lock = path28.join(store.root, `reflect-${createHash10("sha256").update(opts.sessionId).digest("hex")}.lock`);
11383
12029
  const deadline = Date.now() + 66e4;
11384
12030
  for (; ; ) {
11385
12031
  try {
11386
- fs32.writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 });
12032
+ fs33.writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 });
11387
12033
  break;
11388
12034
  } catch (error) {
11389
12035
  if (error.code !== "EEXIST") throw error;
11390
12036
  try {
11391
- const owner = Number(fs32.readFileSync(lock, "utf8"));
12037
+ const owner = Number(fs33.readFileSync(lock, "utf8"));
11392
12038
  if (Number.isInteger(owner) && owner > 0) {
11393
12039
  try {
11394
12040
  process.kill(owner, 0);
11395
12041
  } catch (error2) {
11396
12042
  if (error2.code === "ESRCH") {
11397
- fs32.unlinkSync(lock);
12043
+ fs33.unlinkSync(lock);
11398
12044
  continue;
11399
12045
  }
11400
12046
  }
@@ -11409,7 +12055,7 @@ async function runReflection(store, opts) {
11409
12055
  return await reflectSession(store, opts);
11410
12056
  } finally {
11411
12057
  try {
11412
- fs32.unlinkSync(lock);
12058
+ fs33.unlinkSync(lock);
11413
12059
  } catch {
11414
12060
  }
11415
12061
  }
@@ -11749,10 +12395,11 @@ __export(cli_exports, {
11749
12395
  HELP: () => HELP2,
11750
12396
  main: () => main,
11751
12397
  parseArgs: () => parseArgs,
12398
+ setupMod: () => setupMod,
11752
12399
  version: () => version
11753
12400
  });
11754
- import fs33 from "node:fs";
11755
- import path28 from "node:path";
12401
+ import fs34 from "node:fs";
12402
+ import path29 from "node:path";
11756
12403
  function parseArgs(argv) {
11757
12404
  const out = { _: [], flags: {} };
11758
12405
  const valueless = /* @__PURE__ */ new Set(["json", "quiet", "force", "sync", "global", "help", "version", "dry-run", "offline", "apply", "no-hooks", "remove-hooks", "key-stdin", "debug", "verbose", "robot", "fork", "upload", "index", "all", "legacy", "depth", "local", "skip-github", "propose-rewrites", "clear", "watch", "once", "allow-codex-shell", "retrace", "across"]);
@@ -11852,7 +12499,7 @@ async function main(argv, opts = {}) {
11852
12499
  if (harness !== "codex" && harness !== "claude-code" && harness !== "pi") throw new Error("Choose your agent: bunshin setup --harness codex, claude-code, or pi.");
11853
12500
  const agent = harness === "claude-code" ? "claude" : harness;
11854
12501
  if (!executable2(agent)) throw new Error(`${agent} was not found. Install and sign in to your agent, then run setup again.`);
11855
- const prior = new Store(path28.join(cwd, ".bunshin"));
12502
+ const prior = new Store(path29.join(cwd, ".bunshin"));
11856
12503
  const existing = prior.trusted ? prior.config() : { apiUrl: "", apiKey: void 0 };
11857
12504
  const apiUrl = str7(args.flags["api-url"]);
11858
12505
  const key = bool5(args.flags["key-stdin"]) ? await new Promise((resolve, reject) => {
@@ -11881,7 +12528,7 @@ async function main(argv, opts = {}) {
11881
12528
  });
11882
12529
  if (result.config.hooks === "user" && !only && !exclude && !bool5(args.flags.all) && process.stdin.isTTY && !bool5(args.flags["key-stdin"])) {
11883
12530
  const { askSources: askSources2 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
11884
- await askSources2(new Store(path28.join(cwd, ".bunshin")), out);
12531
+ await askSources2(new Store(path29.join(cwd, ".bunshin")), out);
11885
12532
  }
11886
12533
  out(`Connected as ${result.profile.role}${result.profile.orgUnit ? ` in ${result.profile.orgUnit}` : " (company-wide)"}.
11887
12534
  `);
@@ -11899,6 +12546,7 @@ Key saved privately outside the project.
11899
12546
  `);
11900
12547
  else if (result.learnCommand?.error) out(`/learn not installed: ${result.learnCommand.error} (${result.learnCommand.file})
11901
12548
  `);
12549
+ if (harness === "claude-code" && result.hooks) out(await setupMod(result.config));
11902
12550
  if (result.hooks?.sharedWithWorktrees) out("Codex shares these hooks with the repository\u2019s linked worktrees. Each connected worktree keeps its own Bunshin store.\n");
11903
12551
  if (harness === "codex" && result.hooks) out("Run codex interactively in this project. Review and accept project trust, then run /hooks and review and trust the five Bunshin hooks.\n");
11904
12552
  else if (harness === "pi" && result.hooks) out("Open Pi in this project and approve its project extension. Check it with /bunshin status.\n");
@@ -11918,11 +12566,11 @@ Key saved privately outside the project.
11918
12566
  if (cmd === "mcp") {
11919
12567
  const { runMcpServer: runMcpServer2 } = await Promise.resolve().then(() => (init_mcp(), mcp_exports));
11920
12568
  const root = str7(args.flags.root);
11921
- await runMcpServer2({ cwd, ...root ? { store: new Store(path28.resolve(root)) } : {}, version: version() });
12569
+ await runMcpServer2({ cwd, ...root ? { store: new Store(path29.resolve(root)) } : {}, version: version() });
11922
12570
  return 0;
11923
12571
  }
11924
12572
  if (cmd === "demo") {
11925
- const { runDemo: runDemo2 } = await Promise.resolve().then(() => (init_demo(), demo_exports));
12573
+ const { runDemo: runDemo2 } = await Promise.resolve().then(() => (init_demo2(), demo_exports));
11926
12574
  await runDemo2(out);
11927
12575
  return 0;
11928
12576
  }
@@ -12010,6 +12658,8 @@ Key saved privately outside the project.
12010
12658
  return await (await Promise.resolve().then(() => (init_skills(), skills_exports))).cmdSkill(store, args, cwd, out, err);
12011
12659
  case "library":
12012
12660
  return await (await Promise.resolve().then(() => (init_skills(), skills_exports))).cmdLibrary(store, args, cwd, out, err);
12661
+ case "atoms":
12662
+ return (await Promise.resolve().then(() => (init_atoms2(), atoms_exports))).cmdAtoms(store, args, out);
12013
12663
  case "ui":
12014
12664
  return await (await Promise.resolve().then(() => (init_uicmd(), uicmd_exports))).cmdUi(store, args, out, err, version());
12015
12665
  case "sources":
@@ -12030,7 +12680,7 @@ ${HELP2}`);
12030
12680
  function openStore(args, cwd) {
12031
12681
  const root = str7(args.flags.root);
12032
12682
  if (root) {
12033
- const store = new Store(path28.resolve(root));
12683
+ const store = new Store(path29.resolve(root));
12034
12684
  store.ensureLayout();
12035
12685
  return store;
12036
12686
  }
@@ -12046,7 +12696,7 @@ async function cmdInit(args, cwd, out, err) {
12046
12696
  orgId: str7(args.flags["org-id"]),
12047
12697
  userId: str7(args.flags["user-id"]),
12048
12698
  apiUrl: str7(args.flags["api-url"]),
12049
- apiKey: bool5(args.flags["key-stdin"]) ? fs33.readFileSync(0, "utf8").trim() || void 0 : str7(args.flags["api-key"]),
12699
+ apiKey: bool5(args.flags["key-stdin"]) ? fs34.readFileSync(0, "utf8").trim() || void 0 : str7(args.flags["api-key"]),
12050
12700
  scope: bool5(args.flags.global) ? "global" : str7(args.flags.scope),
12051
12701
  harness,
12052
12702
  noHooks: args.flags.hooks === false || bool5(args.flags["no-hooks"]),
@@ -12089,14 +12739,14 @@ function cmdStatus(store, args, out, v2) {
12089
12739
  const conflicts = store.listConflicts().filter((c) => c.status === "open");
12090
12740
  const metrics = store.readMetrics(void 0);
12091
12741
  const last50 = metrics?.windows?.find((w) => w.name === "last50");
12092
- const hookFiles = config.harness === "codex" ? [.../* @__PURE__ */ new Set([path28.join(process.env.CODEX_HOME ?? path28.join(homeDir(), ".codex"), "hooks.json"), codexProjectHooks(path28.dirname(store.root)).file])] : config.harness === "claude-code" ? [path28.join(homeDir(), ".claude", "settings.json"), path28.join(path28.dirname(store.root), ".claude", "settings.local.json")] : config.harness === "pi" ? [path28.join(homeDir(), ".pi/agent/extensions/bunshin.js"), path28.join(path28.dirname(store.root), ".pi/extensions/bunshin.js")] : [];
12093
- const hooks = config.harness === "pi" ? hookFiles.filter((file) => {
12742
+ const hookFiles = config.harness === "codex" ? [.../* @__PURE__ */ new Set([path29.join(process.env.CODEX_HOME ?? path29.join(homeDir(), ".codex"), "hooks.json"), codexProjectHooks(path29.dirname(store.root)).file])] : config.harness === "claude-code" ? [path29.join(homeDir(), ".claude", "settings.json"), path29.join(path29.dirname(store.root), ".claude", "settings.local.json")] : config.harness === "pi" ? [path29.join(homeDir(), ".pi/agent/extensions/bunshin.js"), path29.join(path29.dirname(store.root), ".pi/extensions/bunshin.js")] : [];
12743
+ const hooks = config.harness === "pi" ? hookFiles.filter((file2) => {
12094
12744
  try {
12095
- return fs33.readFileSync(file, "utf8").startsWith("// Managed by Bunshin setup.");
12745
+ return fs34.readFileSync(file2, "utf8").startsWith("// Managed by Bunshin setup.");
12096
12746
  } catch {
12097
12747
  return false;
12098
12748
  }
12099
- }).length : hookFiles.reduce((total, file) => total + hookCount(file), 0);
12749
+ }).length : hookFiles.reduce((total, file2) => total + hookCount(file2), 0);
12100
12750
  const served = lessons.reduce((n, l) => n + l.stats.served, 0);
12101
12751
  const used = lessons.reduce((n, l) => n + l.stats.used, 0);
12102
12752
  const status = {
@@ -12109,8 +12759,9 @@ function cmdStatus(store, args, out, v2) {
12109
12759
  conflictsOpen: conflicts.length,
12110
12760
  mothership: config.apiUrl ? { apiUrl: config.apiUrl, key: config.apiKey ? "set" : "missing", lastSyncAt: config.lastSyncAt ?? null } : null,
12111
12761
  llmBackend: resolveBackend(config) ?? "none (set ANTHROPIC_API_KEY or install the claude/codex CLI)",
12762
+ recallRouter: recallRouter(config),
12112
12763
  hooks: { [config.harness]: hooks },
12113
- hookFiles: hookFiles.filter((file) => fs33.existsSync(file)),
12764
+ hookFiles: hookFiles.filter((file2) => fs34.existsSync(file2)),
12114
12765
  recallQuality: last50 ? { precision: last50.precision, recall: last50.recall, f1: last50.f1, traces: last50.traces } : null,
12115
12766
  v2
12116
12767
  };
@@ -12144,6 +12795,8 @@ function cmdStatus(store, args, out, v2) {
12144
12795
  out(`mothership ${config.apiUrl ? `${config.apiUrl} (key ${config.apiKey ? "set" : "MISSING"}, last sync ${config.lastSyncAt ?? "never"})` : "local only"}
12145
12796
  `);
12146
12797
  out(`llm backend ${status.llmBackend}
12798
+ `);
12799
+ out(`recall router ${status.recallRouter === "claude-cli" ? `claude-cli (${config.recall.routerModel || process.env.BUNSHIN_ROUTER_MODEL || "claude-haiku-5-5"} on your Claude Code sign-in)` : "server"}
12147
12800
  `);
12148
12801
  out(`hooks ${config.harness}: ${hooks > 0 ? `${hooks} configured` : "not detected"}${config.harness === "codex" ? " (requires Codex hook trust)" : ""}
12149
12802
  `);
@@ -12151,9 +12804,9 @@ function cmdStatus(store, args, out, v2) {
12151
12804
  `);
12152
12805
  return 0;
12153
12806
  }
12154
- function hookCount(file) {
12807
+ function hookCount(file2) {
12155
12808
  try {
12156
- const raw = JSON.parse(fs33.readFileSync(file, "utf8"));
12809
+ const raw = JSON.parse(fs34.readFileSync(file2, "utf8"));
12157
12810
  let n = 0;
12158
12811
  for (const groups of Object.values(raw.hooks ?? {})) {
12159
12812
  for (const g of groups ?? []) {
@@ -12168,7 +12821,7 @@ function hookCount(file) {
12168
12821
  async function cmdRecall2(store, args, cwd, out, err) {
12169
12822
  const task = args._.slice(1).join(" ").trim() || str7(args.flags.task) || "";
12170
12823
  if (!task) {
12171
- err('bunshin recall: a task is required, e.g. bunshin recall "close an account with a negative balance"\n');
12824
+ err('bunshin recall: a task is required, e.g. bunshin recall "delete a workspace after its subscription is cancelled"\n');
12172
12825
  return 1;
12173
12826
  }
12174
12827
  const { runRecall: runRecall2 } = await Promise.resolve().then(() => (init_recall3(), recall_exports));
@@ -12267,13 +12920,13 @@ ${lessons.length} lesson(s). \`bunshin lessons show <id>\` for the full body.
12267
12920
  function cmdLessonAdd(store, args, out, err) {
12268
12921
  const title = str7(args.flags.title);
12269
12922
  if (!title) {
12270
- err('bunshin lessons add: --title is required (e.g. --title "Collections closes negative balances by hand")\n');
12923
+ err('bunshin lessons add: --title is required (e.g. --title "Legal releases held workspaces by hand")\n');
12271
12924
  return 1;
12272
12925
  }
12273
12926
  let content = str7(args.flags.content) ?? "";
12274
12927
  if (!content || content === "-" || args._.includes("-")) {
12275
12928
  try {
12276
- content = fs33.readFileSync(0, "utf8");
12929
+ content = fs34.readFileSync(0, "utf8");
12277
12930
  } catch {
12278
12931
  }
12279
12932
  }
@@ -12339,7 +12992,7 @@ async function cmdReflect(store, args, cwd, out, err) {
12339
12992
  }
12340
12993
  const { runReflection: runReflection2 } = await Promise.resolve().then(() => (init_reflect4(), reflect_exports));
12341
12994
  const result = await runReflection2(store, {
12342
- sessionId: str7(args.flags.session) ?? path28.basename(transcript).replace(/\.jsonl?$/, ""),
12995
+ sessionId: str7(args.flags.session) ?? path29.basename(transcript).replace(/\.jsonl?$/, ""),
12343
12996
  transcriptPath: transcript,
12344
12997
  cwd,
12345
12998
  force: bool5(args.flags.force)
@@ -12445,6 +13098,30 @@ async function cmdConflict(store, args, out, err) {
12445
13098
  function store0HasKey(store) {
12446
13099
  return !!store.config().apiKey;
12447
13100
  }
13101
+ async function setupMod(config) {
13102
+ const { uiMode: uiMode2 } = await Promise.resolve().then(() => (init_ui(), ui_exports));
13103
+ if (uiMode2(config, "claude-code") === "off" || process.env.BUNSHIN_UI_AUTOINSTALL === "0") return "";
13104
+ const { installMod: installMod2, installedModVersion: installedModVersion2, modHome: modHome2, modSource: modSource2 } = await Promise.resolve().then(() => (init_uicmd(), uicmd_exports));
13105
+ const v = version();
13106
+ if (!modSource2()) return "";
13107
+ if (installedModVersion2() === v) return `Bunshin UI: bunshin-ui ${v} is installed (a band above the prompt, /bunshin).
13108
+ `;
13109
+ try {
13110
+ fs34.mkdirSync(modHome2(), { recursive: true });
13111
+ fs34.writeFileSync(path29.join(modHome2(), `.attempted-${v}`), nowIso());
13112
+ const res = installMod2(v);
13113
+ if (res.steps.some((st) => st.ok && /plugin (install|update)/.test(st.command))) {
13114
+ return `Bunshin UI: bunshin-ui ${v} installed (a band above the prompt, /bunshin). It needs Claude Code mods on your account.
13115
+ `;
13116
+ }
13117
+ const why = res.steps.filter((st) => !st.ok).map((st) => st.output.split("\n")[0]).filter(Boolean).pop();
13118
+ return `Bunshin UI not installed${why ? `: ${why}` : ""}. It needs Claude Code 2.1.287+ with mods on your account. Try: bunshin ui install
13119
+ `;
13120
+ } catch (e) {
13121
+ return `Bunshin UI not installed: ${e instanceof Error ? e.message : String(e)}. Try: bunshin ui install
13122
+ `;
13123
+ }
13124
+ }
12448
13125
  var str7, bool5, HELP2, untrustedNote;
12449
13126
  var init_cli = __esm({
12450
13127
  "src/cli.ts"() {
@@ -12502,6 +13179,11 @@ Usage: bunshin <command> [options]
12502
13179
  tools, history) into the library; the repository can then go
12503
13180
  skill list|show <name>|log [name] [--since 3.months]|lint [--graph [file]]|push [name] [--layer L]
12504
13181
  the deployed skills; push proposes local edits / a new skill now
13182
+ skill split <name> [--submit] [--force]
13183
+ a long skill \u2192 its spine plus atoms (cards, facts, rules), checked
13184
+ lossless and written here for review; --submit sends it
13185
+ atoms [--json] atom triggers on this machine: fires, how often what they brought
13186
+ was used, and which are muted for firing without helping
12505
13187
  library version|log|status|pin [--write [file]]|checkout <lib@N> --to <dir> [--git <sha>] [--pin <file>]
12506
13188
  library versions (lib@N), history, and exact reproductions
12507
13189
  library workspace (retired: each workspace keeps its own skills and links them into
@@ -12532,7 +13214,7 @@ Usage: bunshin <command> [options]
12532
13214
  reflect <transcript> [--session <id>] [--force] [--sync] [--json] (legacy lessons)
12533
13215
  recall --legacy "<task>" [--offline] legacy lesson recall
12534
13216
  conflict list [--json] | conflict resolve <id> "<answer>" [--note <n>]
12535
- demo run the synthetic APR scenario offline in a temporary store
13217
+ demo run a synthetic cross-team scenario offline in a temporary store
12536
13218
 
12537
13219
  hook <event> read hook JSON on stdin, write hook JSON on stdout
12538
13220
  events: session-start | user-prompt-submit | pre-tool-use |
@@ -12542,7 +13224,7 @@ Global: --root <dir> (use this .bunshin store) --version --help
12542
13224
  Env: BUNSHIN_API_KEY, BUNSHIN_HARNESS, BUNSHIN_DISABLE, BUNSHIN_CHILD, BUNSHIN_CLAUDE_BIN,
12543
13225
  CLAUDE_CODE_SESSION_ID (learn / mcp session), ANTHROPIC_API_KEY (non-fork reflection)
12544
13226
  `;
12545
- untrustedNote = (root) => `${root} was not created by you (e.g. it is committed to the repository), so Bunshin ignores it. If it is yours, run \`bunshin setup\` (or \`bunshin init\`) in ${path28.dirname(root)} to trust it.`;
13227
+ untrustedNote = (root) => `${root} was not created by you (e.g. it is committed to the repository), so Bunshin ignores it. If it is yours, run \`bunshin setup\` (or \`bunshin init\`) in ${path29.dirname(root)} to trust it.`;
12546
13228
  }
12547
13229
  });
12548
13230