@bunshin-cc/bunshin 0.10.4 → 0.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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;
@@ -1200,10 +1203,10 @@ function isLocalLayer(layer) {
1200
1203
  return kind === "user" || kind === "robot";
1201
1204
  }
1202
1205
  function withScope(layers, scope) {
1203
- const path29 = scopePath(scope?.tree, scope?.source);
1204
- if (!path29.length) return layers;
1206
+ const path30 = scopePath(scope?.tree, scope?.source);
1207
+ if (!path30.length) return layers;
1205
1208
  const i = layers.findIndex((l) => isLocalLayer(l));
1206
- return i < 0 ? [...layers, ...path29] : [...layers.slice(0, i), ...path29, ...layers.slice(i)];
1209
+ return i < 0 ? [...layers, ...path30] : [...layers.slice(0, i), ...path30, ...layers.slice(i)];
1207
1210
  }
1208
1211
  function readerFor(ctx, ownerClearance, scope) {
1209
1212
  if (ctx.kind === "robot" && !scope?.source) scope = { ...scope, source: `robot:${ctx.id}` };
@@ -1250,11 +1253,11 @@ function baseAffinity(section, reader) {
1250
1253
  const kind = layerKind(section.layer);
1251
1254
  if (kind === "group" || kind === "source") {
1252
1255
  if (!reader.layers.includes(section.layer)) return 0.05;
1253
- const path29 = reader.layers.filter((l) => {
1256
+ const path30 = reader.layers.filter((l) => {
1254
1257
  const k = layerKind(l);
1255
1258
  return k === "group" || k === "source";
1256
1259
  });
1257
- return 0.6 + 0.4 * ((path29.indexOf(section.layer) + 1) / path29.length);
1260
+ return 0.6 + 0.4 * ((path30.indexOf(section.layer) + 1) / path30.length);
1258
1261
  }
1259
1262
  if (isLocalLayer(section.layer)) return reader.layers.includes(section.layer) ? 1 : 0;
1260
1263
  return 0.5;
@@ -1454,17 +1457,17 @@ var init_document = __esm({
1454
1457
  function repoLayer(repo) {
1455
1458
  return `source:${repo.includes("/") ? "repo" : "folder"}:${repo}`;
1456
1459
  }
1457
- function repoSectionId(repo, path29, anchor = "") {
1458
- return anchor ? `repo:${repo}/${path29}#${anchor}` : `repo:${repo}/${path29}`;
1460
+ function repoSectionId(repo, path30, anchor = "") {
1461
+ return anchor ? `repo:${repo}/${path30}#${anchor}` : `repo:${repo}/${path30}`;
1459
1462
  }
1460
- function docKind(path29) {
1461
- const base = path29.split("/").pop()?.toLowerCase() ?? "";
1463
+ function docKind(path30) {
1464
+ const base = path30.split("/").pop()?.toLowerCase() ?? "";
1462
1465
  if (base === "testing.md") return "verification";
1463
1466
  if (base === "skill.md") return "skill";
1464
1467
  return "spec";
1465
1468
  }
1466
- function defaultPaths(path29) {
1467
- const dir2 = path29.split("/").slice(0, -1).join("/");
1469
+ function defaultPaths(path30) {
1470
+ const dir2 = path30.split("/").slice(0, -1).join("/");
1468
1471
  if (!dir2 || dir2.startsWith(".claude/") || dir2.startsWith(".codex/")) return [];
1469
1472
  return [`${dir2}/**`];
1470
1473
  }
@@ -1609,11 +1612,11 @@ function lintSkills(sections) {
1609
1612
  }
1610
1613
  const state = /* @__PURE__ */ new Map();
1611
1614
  const cycles = /* @__PURE__ */ new Set();
1612
- const dfs = (n, path29) => {
1615
+ const dfs = (n, path30) => {
1613
1616
  state.set(n, 1);
1614
1617
  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]);
1618
+ if (state.get(d) === 1) cycles.add([...path30.slice(path30.indexOf(d)), d].join(" -> "));
1619
+ else if (!state.get(d)) dfs(d, [...path30, d]);
1617
1620
  }
1618
1621
  state.set(n, 2);
1619
1622
  };
@@ -1700,8 +1703,8 @@ function parsePythonSkills(text2) {
1700
1703
  }
1701
1704
  return { skills, constants };
1702
1705
  }
1703
- function harnessSectionId(path29, symbol) {
1704
- return `harness:${path29}#${symbol}`;
1706
+ function harnessSectionId(path30, symbol) {
1707
+ return `harness:${path30}#${symbol}`;
1705
1708
  }
1706
1709
  var DEF_RE;
1707
1710
  var init_python = __esm({
@@ -1827,9 +1830,11 @@ function globToRegExp(glob) {
1827
1830
  globCache.set(glob, out);
1828
1831
  return out;
1829
1832
  }
1830
- function matchesGlob(path29, glob) {
1831
- const p = path29.replace(/^\.\//, "").replace(/\\/g, "/");
1832
- return globToRegExp(glob.replace(/^\.\//, "")).test(p);
1833
+ function normalPath(path30) {
1834
+ return path30.replace(/\\/g, "/").split("/").filter((s) => s !== "" && s !== ".").join("/");
1835
+ }
1836
+ function matchesGlob(path30, glob) {
1837
+ return globToRegExp(glob.replace(/^\.\//, "")).test(normalPath(path30));
1833
1838
  }
1834
1839
  var DEFAULT_EMBEDDERS, globCache;
1835
1840
  var init_text_index = __esm({
@@ -1920,10 +1925,10 @@ function push(sections, reader, query) {
1920
1925
  for (const s of recallable(sections, reader).filter((x) => reachesReader(x, reader))) {
1921
1926
  const triggers = [...(s.triggers ?? []).filter((t) => t.anchor), { anchor: "", paths: s.paths, entities: s.entities, skills: s.skills }];
1922
1927
  for (const t of triggers) {
1923
- const path29 = paths.find((p) => t.paths.some((g) => matchesGlob(p, g)));
1924
- const entity = path29 ? void 0 : t.entities.find((e) => entities.has(e) || text2 && text2.includes(e));
1925
- const skill = path29 || entity ? void 0 : skills.find((k) => t.skills.includes(k));
1926
- const trigger = path29 ? `path:${path29}` : entity ? `entity:${entity}` : skill ? `skill:${skill}` : "";
1928
+ const path30 = paths.find((p) => t.paths.some((g) => matchesGlob(p, g)));
1929
+ const entity = path30 ? void 0 : t.entities.find((e) => entities.has(e) || text2 && text2.includes(e));
1930
+ const skill = path30 || entity ? void 0 : skills.find((k) => t.skills.includes(k));
1931
+ const trigger = path30 ? `path:${path30}` : entity ? `entity:${entity}` : skill ? `skill:${skill}` : "";
1927
1932
  if (trigger) {
1928
1933
  hits.set(s.id, { section: s, trigger, anchor: t.anchor });
1929
1934
  break;
@@ -2038,8 +2043,8 @@ function renderSection(s, trigger, opts = {}) {
2038
2043
  return [
2039
2044
  ...head,
2040
2045
  "",
2041
- `The \`${s.skill.name}\` skill applies: ${s.skill.description}`,
2042
- `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}"` : ""}.`
2046
+ `The \`${s.skill.name}\` skill may apply: ${s.skill.description}`,
2047
+ `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}")` : ""}.`
2043
2048
  ].join("\n");
2044
2049
  }
2045
2050
  if (s.body.length <= max) return [...head, "", s.body.trim()].join("\n");
@@ -2078,6 +2083,230 @@ var init_engine = __esm({
2078
2083
  }
2079
2084
  });
2080
2085
 
2086
+ // ../core/src/v2/atoms.ts
2087
+ function compileTrigger(t) {
2088
+ if (compiled.has(t.match)) return compiled.get(t.match);
2089
+ let re = null;
2090
+ if (t.match && t.match.length <= MAX_PATTERN && !NESTED_QUANTIFIER.test(t.match)) {
2091
+ try {
2092
+ re = new RegExp(t.match, "i");
2093
+ } catch {
2094
+ re = null;
2095
+ }
2096
+ }
2097
+ if (compiled.size > 5e3) compiled.clear();
2098
+ compiled.set(t.match, re);
2099
+ return re;
2100
+ }
2101
+ function validTrigger(raw) {
2102
+ if (!raw || typeof raw !== "object") return null;
2103
+ const o = raw;
2104
+ const tool = typeof o.tool === "string" && o.tool.trim() ? o.tool.trim().slice(0, 120) : "*";
2105
+ const match = typeof o.match === "string" ? o.match.trim() : "";
2106
+ return match && compileTrigger({ match }) ? { tool, match } : null;
2107
+ }
2108
+ function toolCallText(input) {
2109
+ if (!input || typeof input !== "object") return "";
2110
+ if (typeof input.command === "string") return input.command.slice(0, TEXT_CHARS);
2111
+ const out = [];
2112
+ const walk = (v, depth) => {
2113
+ if (typeof v === "string") out.push(v.slice(0, TEXT_CHARS));
2114
+ else if (depth < 3 && Array.isArray(v)) v.forEach((x) => walk(x, depth + 1));
2115
+ else if (depth < 3 && v && typeof v === "object") Object.values(v).forEach((x) => walk(x, depth + 1));
2116
+ };
2117
+ walk(input, 0);
2118
+ return out.join("\n").slice(0, TEXT_CHARS);
2119
+ }
2120
+ function toolTriggerHits(sections, reader, call2, opts = {}) {
2121
+ const text2 = toolCallText(call2.input);
2122
+ if (!text2 || !call2.tool) return [];
2123
+ const skip = new Set(opts.exclude ?? []);
2124
+ const hits = [];
2125
+ for (const s of recallable(sections, reader)) {
2126
+ if (!s.toolTriggers?.length || skip.has(s.id) || !isAtom(s) || !reachesReader(s, reader)) continue;
2127
+ for (const [index, t] of s.toolTriggers.entries()) {
2128
+ if (!toolMatches(t.tool, call2.tool)) continue;
2129
+ const key = triggerKey(s, index);
2130
+ if (opts.muted?.has(key)) continue;
2131
+ const m = compileTrigger(t)?.exec(text2);
2132
+ if (!m) continue;
2133
+ hits.push({ section: s, index, trigger: t, match: m[0].slice(0, 120), key });
2134
+ break;
2135
+ }
2136
+ }
2137
+ const rank = (k) => ["guardrail", "rule", "fact", "card"].indexOf(k);
2138
+ 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);
2139
+ }
2140
+ function usageCues(s) {
2141
+ const out = /* @__PURE__ */ new Set();
2142
+ const body = s.body.replace(/_\(learned \d{4}-[^)]*\)_/g, "");
2143
+ for (const m of body.matchAll(/`([^`\n]{2,80})`/g)) out.add(m[1].trim().toLowerCase());
2144
+ for (const c of s.cues ?? []) if (c.trim().length >= 3) out.add(c.trim().toLowerCase());
2145
+ for (const m of body.matchAll(/(?:^|[\s(])((?:--?[a-z][\w-]{1,30})|(?:[\w.-]*[_/.][\w./-]*\w))(?=$|[\s),.:;])/gim)) {
2146
+ const w = m[1].toLowerCase();
2147
+ if (w.length >= 3 && !STOP.has(w) && !/^\d+(\.\d+)*$/.test(w)) out.add(w);
2148
+ }
2149
+ return [...out].filter((c) => c.length >= 2).slice(0, 40);
2150
+ }
2151
+ function cardsOf(spine, sections) {
2152
+ const order = new Map((spine.outline ?? []).map((h, i) => [h.anchor, i]));
2153
+ 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));
2154
+ }
2155
+ function renderCardIndex(spine, cards, opts = {}) {
2156
+ if (!cards.length) return "";
2157
+ const stepTitle = new Map((spine.outline ?? []).map((h) => [h.anchor, h.title]));
2158
+ const oneLine = (t) => t.replace(/\s+/g, " ").trim().slice(0, 240);
2159
+ 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)}`);
2160
+ const load = opts.mcp ? `bunshin_load {"section_id": "<id>"}` : "`bunshin load <id>`";
2161
+ return [
2162
+ `### CARDS of ${spine.skill ? `the \`${spine.skill.name}\` skill` : spine.title}`,
2163
+ `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.`,
2164
+ "",
2165
+ ...lines
2166
+ ].join("\n");
2167
+ }
2168
+ function normalizeLine(line) {
2169
+ 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();
2170
+ }
2171
+ function splitCoverage(source, units) {
2172
+ const body = source.slice(parseFrontmatter2(source).bodyStart);
2173
+ const held = units.map((u) => ` ${u.body.split("\n").map(normalizeLine).filter(Boolean).join(" ")} `);
2174
+ const missing = [];
2175
+ let lines = 0;
2176
+ for (const raw of body.split("\n")) {
2177
+ if (/^\s*(```|~~~)/.test(raw)) continue;
2178
+ const n = normalizeLine(raw);
2179
+ if (trivial(n)) continue;
2180
+ lines++;
2181
+ if (!held.some((h) => h.includes(n))) missing.push(raw.trim());
2182
+ }
2183
+ return { lines, missing };
2184
+ }
2185
+ function buildSplitPrompt(skill) {
2186
+ return `You split one long agent skill into a SPINE and ATOMS. Agents will get the spine when they
2187
+ start the workflow, and each atom only when their work reaches it (a tool call that matches its
2188
+ trigger, or a router that sees what they are doing), or when they ask a narrow question it answers.
2189
+
2190
+ The skill: ${skill.name}
2191
+ What it is for: ${skill.description}
2192
+
2193
+ <skill>
2194
+ ${skill.body.slice(parseFrontmatter2(skill.body).bodyStart)}
2195
+ </skill>
2196
+
2197
+ Units:
2198
+ - "spine" (exactly one): the workflow's map. Its headings in order, and under each step the one or
2199
+ two lines that say what the step is and when it is done. At most about 1000 words. A step whose
2200
+ detail moved into cards keeps its heading.
2201
+ - "card": the detail of one step or one situation within the workflow (how to do it, the commands,
2202
+ the checks). "step" names the spine heading it belongs under, as written there.
2203
+ - "fact": something that is true regardless of the step (a tool's quirk, an environment fact, a trap
2204
+ and what works instead, another team's process).
2205
+ - "rule": a correction or preference someone taught ("never \u2026", "always \u2026", "the user wants \u2026").
2206
+
2207
+ Rules for the split:
2208
+ - LOSSLESS. Every line of the skill goes into some unit, word for word. You may move lines, regroup
2209
+ them, and rewrap a paragraph; never reword, shorten, summarise or drop one. A line two units need
2210
+ may appear in both.
2211
+ - One atom is one thing: a fact, a rule, or one step's detail. Most are 30-300 words.
2212
+ - "title" names the thing; "when" says the moment an agent needs it, in the words of that moment
2213
+ ("before rerunning a failed CI job", "when a staging customer id is needed"), not a topic label.
2214
+ - "triggers": only when a tool call reliably marks that moment: [{"tool": "Bash", "match": "<regex>"}],
2215
+ a case-insensitive regular expression over the call's input (the shell command for Bash, else the
2216
+ call's strings). Specific enough that it rarely fires when the atom is not needed: a command
2217
+ together with the subcommand or flag the atom is about, not a bare program name. None is fine.
2218
+ - "from": the heading path in the skill the lines came from.
2219
+
2220
+ Return one JSON object and nothing else:
2221
+ {"spine": {"title": string, "when": string, "body": string},
2222
+ "units": [{"kind": "card"|"fact"|"rule", "title": string, "when": string, "body": string,
2223
+ "step"?: string, "triggers"?: [{"tool": string, "match": string}], "from"?: string}]}`;
2224
+ }
2225
+ function parseSplit(raw) {
2226
+ if (!raw || typeof raw !== "object") return null;
2227
+ const o = raw;
2228
+ const str8 = (v) => typeof v === "string" ? v.trim() : "";
2229
+ const spineBody = str8(o.spine?.body);
2230
+ if (!spineBody) return null;
2231
+ const units = [];
2232
+ for (const u of Array.isArray(o.units) ? o.units : []) {
2233
+ const x = u ?? {};
2234
+ const kind = x.kind === "card" || x.kind === "fact" || x.kind === "rule" ? x.kind : null;
2235
+ const title = str8(x.title);
2236
+ const body = str8(x.body);
2237
+ if (!kind || !title || !body) continue;
2238
+ const triggers = (Array.isArray(x.triggers) ? x.triggers : []).map(validTrigger).filter((t) => !!t).slice(0, 4);
2239
+ 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) } : {} });
2240
+ }
2241
+ return { spine: { kind: "spine", title: str8(o.spine?.title), when: str8(o.spine?.when), body: spineBody }, units };
2242
+ }
2243
+ function withSpineAtoms(chosen, sections, max = 30) {
2244
+ const have = new Set(chosen.map((s) => s.id));
2245
+ const byId = new Map(sections.map((s) => [s.id, s]));
2246
+ const extra = [];
2247
+ for (const c of chosen) {
2248
+ const s = byId.get(c.id);
2249
+ if (!s?.skill) continue;
2250
+ for (const a of cardsOf(s, sections)) if (!have.has(a.id) && extra.length < max) have.add(a.id), extra.push(a);
2251
+ }
2252
+ return [...chosen, ...extra];
2253
+ }
2254
+ 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;
2255
+ var init_atoms = __esm({
2256
+ "../core/src/v2/atoms.ts"() {
2257
+ "use strict";
2258
+ init_layers();
2259
+ init_engine();
2260
+ init_document();
2261
+ ATOM_KINDS = /* @__PURE__ */ new Set(["rule", "fact", "card", "guardrail"]);
2262
+ ATOM_CHARS = 4e3;
2263
+ isAtom = (s) => ATOM_KINDS.has(s.kind) && s.body.length <= ATOM_CHARS;
2264
+ MAX_PATTERN = 300;
2265
+ TEXT_CHARS = 8e3;
2266
+ compiled = /* @__PURE__ */ new Map();
2267
+ NESTED_QUANTIFIER = /\((?:[^()\\]|\\.)*[+*}](?:[^()\\]|\\.)*\)\s*[+*{]/;
2268
+ toolMatches = (pattern, tool) => {
2269
+ const p = pattern.toLowerCase();
2270
+ const t = tool.toLowerCase();
2271
+ return p === "*" || p === t || p.endsWith("*") && t.startsWith(p.slice(0, -1));
2272
+ };
2273
+ triggerKey = (s, index) => `${s.id}#${index}@v${s.version}`;
2274
+ STOP = /* @__PURE__ */ new Set(["the", "and", "for", "with", "this", "that", "then", "when", "from", "into", "only", "never", "always", "use", "run", "not"]);
2275
+ cuesIn = (cues, text2) => {
2276
+ const t = text2.toLowerCase();
2277
+ return cues.filter((c) => t.includes(c));
2278
+ };
2279
+ TRIGGER_FLOOR = 0.4;
2280
+ TRIGGER_MIN_JUDGED = 8;
2281
+ triggerPrecision = (t) => t.judged ? t.used / t.judged : null;
2282
+ triggerMuted = (t) => !!t && t.judged >= TRIGGER_MIN_JUDGED && t.used / t.judged < TRIGGER_FLOOR;
2283
+ trivial = (n) => n.length < 3 || /^[-=:\s]+$/.test(n);
2284
+ SPLIT_SCHEMA = {
2285
+ type: "object",
2286
+ required: ["spine", "units"],
2287
+ properties: {
2288
+ spine: { type: "object", required: ["title", "when", "body"], properties: { title: { type: "string" }, when: { type: "string" }, body: { type: "string" } } },
2289
+ units: {
2290
+ type: "array",
2291
+ items: {
2292
+ type: "object",
2293
+ required: ["kind", "title", "when", "body"],
2294
+ properties: {
2295
+ kind: { type: "string", enum: ["card", "fact", "rule"] },
2296
+ title: { type: "string" },
2297
+ when: { type: "string" },
2298
+ body: { type: "string" },
2299
+ step: { type: "string" },
2300
+ from: { type: "string" },
2301
+ triggers: { type: "array", items: { type: "object", required: ["match"], properties: { tool: { type: "string" }, match: { type: "string" } } } }
2302
+ }
2303
+ }
2304
+ }
2305
+ }
2306
+ };
2307
+ }
2308
+ });
2309
+
2081
2310
  // ../core/src/v2/recall/router.ts
2082
2311
  function routerMessage(prompt, ctx, inContext2) {
2083
2312
  const lines = ["Session context:"];
@@ -2093,6 +2322,20 @@ ${prompt.slice(0, 6e3)}
2093
2322
  >>>
2094
2323
  Return the JSON line.`;
2095
2324
  }
2325
+ function checkpointMessage(ctx, actions, inContext2) {
2326
+ const lines = ["Checkpoint during the work (no new prompt). Session context:"];
2327
+ if (ctx.first) lines.push(`- First prompt of this session: ${ctx.first.slice(0, 600)}`);
2328
+ if (ctx.latest && ctx.latest !== ctx.first) lines.push(`- Latest user prompt: ${ctx.latest.slice(0, 600)}`);
2329
+ if (ctx.reply) lines.push(`- Agent's last reply: ${ctx.reply.slice(0, 1e3)}`);
2330
+ lines.push(`- Already in the agent's context: ${inContext2.length ? inContext2.join(", ") : "nothing from the library"}`);
2331
+ const recent = actions.slice(-20).map((a) => ` \xB7 ${a.replace(/\s+/g, " ").slice(0, 240)}`);
2332
+ return `${lines.join("\n")}
2333
+
2334
+ The agent's recent tool calls, oldest first:
2335
+ ${recent.join("\n") || " (none)"}
2336
+
2337
+ 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.`;
2338
+ }
2096
2339
  function parseRouterAnswer(text2, items, skip = []) {
2097
2340
  const m = /\{[\s\S]*\}/.exec(text2);
2098
2341
  if (!m) return null;
@@ -2114,14 +2357,15 @@ var MAX_RULES, RULES;
2114
2357
  var init_router = __esm({
2115
2358
  "../core/src/v2/recall/router.ts"() {
2116
2359
  "use strict";
2360
+ init_atoms();
2117
2361
  MAX_RULES = 3;
2118
- 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.
2362
+ 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).
2119
2363
 
2120
- - "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.
2121
- - "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.
2364
+ - "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.
2365
+ - "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.
2122
2366
  - "hints": up to 2 other possibly relevant document ids, shown as titles only.
2123
2367
 
2124
- Only use ids from the library. Output exactly one line of JSON and nothing else: {"serve": "<id or null>", "rules": ["<lesson id>", ...], "hints": ["<id>", ...]}`;
2368
+ Only use ids from the library. Output exactly one line of JSON and nothing else: {"serve": "<id or null>", "rules": ["<atom id>", ...], "hints": ["<id>", ...]}`;
2125
2369
  }
2126
2370
  });
2127
2371
 
@@ -2815,17 +3059,27 @@ A lesson is read by agents on other tasks, months from now. Write the rule, not
2815
3059
 
2816
3060
  ## Where it goes
2817
3061
 
2818
- Every entry is a whole document (a skill, a spec, a policy). Prefer editing an existing document
2819
- over creating one, and aim the edit: "anchor" names the heading (from its headings list) the text
2820
- belongs under, so it lands in the right part of the document.
2821
-
2822
- Steering and approach lessons (a, e) are the exception: each is its own short lesson. Use op
2823
- "create" with kind "rule": a title naming the behaviour, a "when" naming the situations it applies
2824
- in (as the user would phrase a request there, even one that never mentions it), and a body of at
2825
- most about 120 words: the rule, why, and when it was learned. Do not append such a lesson inside a
2826
- long skill or procedure: a rule buried in a long document goes unfollowed even when the document is
2827
- loaded, and the user ends up repeating it. If a short rule in the list below already says it, append
2828
- to that rule instead. Traps, procedures and facts (b, c, d) still go into the document they belong to.
3062
+ A lesson is an ATOM: one short item of its own, served on its own when the work reaches the moment
3063
+ it is about. Never append a lesson, a trap or a fact to a long skill or procedure: a line buried in a
3064
+ long document goes unfollowed even when the document is loaded, and every narrow question then loads
3065
+ the whole document. Use op "create" with:
3066
+ - kind "rule" for steering and approach lessons (a, e);
3067
+ - kind "fact" for how something is: a trap and what worked instead, a tool's or API's quirk,
3068
+ another team's process (b, c);
3069
+ - kind "card" for the detail of one step of a workflow a skill describes (how a step is done, what
3070
+ it needs), with "partOf" the skill's id and "step" the skill's heading anchor (d, or a step that
3071
+ went wrong and how it is done right).
3072
+ Each atom: a title naming the thing; a "when" naming the moment an agent needs it, as it would show
3073
+ in the work or in a request there (even one that never mentions it), not a topic label; a body of
3074
+ at most about 150 words: what to do or know, and why. Add "triggers" only when a tool call reliably
3075
+ marks that moment: [{"tool": "Bash", "match": "<regex>"}], a case-insensitive regular expression over
3076
+ the call's input (the shell command for Bash, else its strings), specific enough that it rarely
3077
+ fires when the atom is not needed (the command with the subcommand or flag it is about, never a bare
3078
+ program name).
3079
+ If an atom in the list below already says it, edit that atom instead (op "append" or "replace" on
3080
+ its id): one atom per thing. Edit a skill or other long document only when its workflow itself
3081
+ changes (a step is added, removed or reordered, or a step's one-line summary is wrong), and aim the
3082
+ edit: "anchor" names the heading (from its headings list) it belongs under.
2829
3083
 
2830
3084
  Library documents relevant to this session:
2831
3085
  ${index}
@@ -2872,8 +3126,10 @@ At most ${max} suggestions. Schema:
2872
3126
  "suggestions": [{"target": {"sectionId"?: string, "layer"?: string},
2873
3127
  "op": {"op": "append", "text": string, "condition"?: string, "anchor"?: string}
2874
3128
  | {"op": "replace", "find": string, "text": string, "anchor"?: string}
2875
- | {"op": "create", "section": {"kind": "skill"|"procedure"|"spec"|"verification"|"rule"|"guardrail"|"reference",
3129
+ | {"op": "create", "section": {"kind": "rule"|"fact"|"card"|"skill"|"procedure"|"spec"|"verification"|"guardrail"|"reference",
2876
3130
  "title": string, "body": string, "when": string,
3131
+ "triggers"?: [{"tool": string, "match": string}],
3132
+ "partOf"?: string, "step"?: string,
2877
3133
  "paths"?: string[], "entities"?: string[], "skills"?: string[]}}
2878
3134
  | {"op": "param", "key": string, "value": string|number|boolean}
2879
3135
  | {"op": "situation", "text": string},
@@ -2975,9 +3231,24 @@ function parseOp(raw) {
2975
3231
  const body = clean(s.body);
2976
3232
  const when = clean(s.when);
2977
3233
  if (!title || !body) return null;
3234
+ const atom = isAtom({ kind, body });
3235
+ const toolTriggers = atom ? (Array.isArray(s.triggers) ? s.triggers : []).map(validTrigger).filter((t) => !!t).slice(0, 4) : [];
3236
+ const partOf2 = atom ? clean(s.partOf) : "";
3237
+ const step = partOf2 ? clean(s.step).replace(/^[§#]/, "") : "";
2978
3238
  return {
2979
3239
  op: "create",
2980
- section: { kind, title, body, when: when || title, paths: strList(s.paths), entities: strList(s.entities).map((e) => e.toLowerCase()), skills: strList(s.skills) }
3240
+ section: {
3241
+ kind,
3242
+ title,
3243
+ body,
3244
+ when: when || title,
3245
+ paths: strList(s.paths),
3246
+ entities: strList(s.entities).map((e) => e.toLowerCase()),
3247
+ skills: strList(s.skills),
3248
+ ...toolTriggers.length ? { toolTriggers } : {},
3249
+ ...partOf2 ? { partOf: partOf2 } : {},
3250
+ ...step ? { step } : {}
3251
+ }
2981
3252
  };
2982
3253
  }
2983
3254
  case "situation": {
@@ -3009,6 +3280,10 @@ function parseReflection(raw, opts = { layers: [] }) {
3009
3280
  let sectionId = typeof t.sectionId === "string" && t.sectionId.trim() ? t.sectionId.trim() : void 0;
3010
3281
  if (op.op !== "create" && op.op !== "param" && (!sectionId || opts.knownSectionIds && !opts.knownSectionIds.has(sectionId))) continue;
3011
3282
  if (op.op === "create") sectionId = void 0;
3283
+ if (op.op === "create" && op.section.partOf && opts.knownSectionIds && !opts.knownSectionIds.has(op.section.partOf)) {
3284
+ const { partOf: _p, step: _s, ...rest } = op.section;
3285
+ op.section = rest;
3286
+ }
3012
3287
  const layerRaw = typeof t.layer === "string" ? t.layer.trim() : "";
3013
3288
  const layer = opts.layers.includes(layerRaw) ? layerRaw : void 0;
3014
3289
  out.push({
@@ -3044,6 +3319,7 @@ var REFLECT_MARKER, ENVIRONMENT_RECHECK_DAYS, SIGNAL_WORDS, REFLECT_SCHEMA, KIND
3044
3319
  var init_reflect = __esm({
3045
3320
  "../core/src/v2/reflect.ts"() {
3046
3321
  "use strict";
3322
+ init_atoms();
3047
3323
  init_guidelines();
3048
3324
  init_redact();
3049
3325
  init_types();
@@ -3078,7 +3354,7 @@ var init_reflect = __esm({
3078
3354
  }
3079
3355
  }
3080
3356
  };
3081
- KINDS = ["skill", "procedure", "spec", "verification", "rule", "guardrail", "reference", "tool"];
3357
+ KINDS = ["skill", "procedure", "spec", "verification", "rule", "guardrail", "reference", "tool", "fact", "card"];
3082
3358
  anchorOf = (v) => {
3083
3359
  const a = typeof v === "string" ? clean(v).replace(/^§/, "").replace(/^#/, "") : "";
3084
3360
  return a ? { anchor: a } : {};
@@ -3209,6 +3485,7 @@ var init_v2 = __esm({
3209
3485
  init_text_index();
3210
3486
  init_engine();
3211
3487
  init_router();
3488
+ init_atoms();
3212
3489
  init_reflect();
3213
3490
  init_digest();
3214
3491
  init_reflect_context();
@@ -3249,8 +3526,8 @@ import fs5 from "node:fs";
3249
3526
  function version() {
3250
3527
  for (const rel of ["../package.json", "../../package.json"]) {
3251
3528
  try {
3252
- const file = new URL(rel, import.meta.url);
3253
- const pkg = JSON.parse(fs5.readFileSync(file, "utf8"));
3529
+ const file2 = new URL(rel, import.meta.url);
3530
+ const pkg = JSON.parse(fs5.readFileSync(file2, "utf8"));
3254
3531
  if (pkg.name === "@bunshin-cc/bunshin" && pkg.version) return pkg.version;
3255
3532
  } catch {
3256
3533
  }
@@ -3320,334 +3597,52 @@ var init_api = __esm({
3320
3597
  }
3321
3598
  });
3322
3599
 
3323
- // src/v2/repo.ts
3324
- import fs6 from "node:fs";
3325
- import path5 from "node:path";
3326
- import { execFileSync } from "node:child_process";
3327
- function git(cwd, args, timeout = 1500) {
3328
- try {
3329
- return execFileSync("git", ["-C", cwd, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout, maxBuffer: 64 * 1024 * 1024 });
3330
- } catch {
3331
- return null;
3332
- }
3333
- }
3334
- function repoRoot(cwd, storeRoot) {
3335
- const key = `${cwd}
3336
- ${storeRoot ?? ""}`;
3337
- const hit = rootCache.get(key);
3338
- if (hit) return hit;
3339
- const top = git(cwd, ["rev-parse", "--show-toplevel"])?.trim();
3340
- let root = top || "";
3341
- if (!root && storeRoot && path5.basename(storeRoot) === ".bunshin") {
3342
- const parent = path5.dirname(storeRoot);
3343
- if (path5.resolve(cwd).startsWith(path5.resolve(parent))) root = parent;
3344
- }
3345
- root = root || path5.resolve(cwd);
3346
- rootCache.set(key, root);
3347
- return root;
3348
- }
3349
- function parseRemote(url) {
3350
- const clean2 = url.trim().replace(/\.git$/, "").replace(/\/+$/, "");
3351
- if (!clean2) return null;
3352
- const scp = clean2.match(/^[^@/\s]+@[^:/\s]+:(.+)$/);
3353
- const pathPart = scp ? scp[1] : (() => {
3354
- try {
3355
- return new URL(clean2).pathname;
3356
- } catch {
3357
- return clean2;
3358
- }
3359
- })();
3360
- const segs = pathPart.split("/").filter(Boolean);
3361
- if (segs.length >= 2) return `${segs[segs.length - 2]}/${segs[segs.length - 1]}`;
3362
- return segs[0] ?? null;
3363
- }
3364
- function repoName(root) {
3365
- const url = git(root, ["remote", "get-url", "origin"]);
3366
- return url && parseRemote(url) || path5.basename(root);
3367
- }
3368
- function repoCommit(root) {
3369
- return git(root, ["rev-parse", "HEAD"])?.trim() || void 0;
3370
- }
3371
- function listDocs(root) {
3372
- const listed = git(root, ["ls-files", "-co", "--exclude-standard", "-z"], 3e3);
3373
- 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();
3374
- const out = [];
3375
- let visited = 0;
3376
- const walk = (dir2, rel, depth) => {
3377
- if (depth > 8 || visited++ > 2e4) return;
3378
- let entries;
3379
- try {
3380
- entries = fs6.readdirSync(dir2, { withFileTypes: true });
3381
- } catch {
3382
- return;
3383
- }
3384
- for (const e of entries) {
3385
- if (e.isDirectory()) {
3386
- 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);
3387
- } else if (e.isFile()) {
3388
- const r = rel ? `${rel}/${e.name}` : e.name;
3389
- if (isDoc(r) && !deployedSkill(root, r)) out.push(r);
3390
- }
3391
- }
3392
- };
3393
- walk(root, "", 0);
3394
- return out.sort();
3395
- }
3396
- function indexWorkingTree(v2, config, cwd, opts = {}) {
3397
- const root = repoRoot(cwd, v2.store.root);
3398
- const now = opts.now ?? Date.now();
3399
- const cached = v2.readRepoIndex(root);
3400
- const ownerTeam = config.ownerTeam || config.orgUnit || "unknown";
3401
- const source = sourceFor(root, v2.store.root);
3402
- const sameRepo = cached && cached.ownerTeam === ownerTeam && cached.format === INDEX_FORMAT;
3403
- const repo = sameRepo && cached.repo && !opts.force ? cached.repo : repoName(root);
3404
- const fresh = sameRepo && cached.repo === repo && cached.paths && cached.listedAt && now - Date.parse(cached.listedAt) < LIST_TTL_MS && !opts.force;
3405
- const paths = fresh ? cached.paths : listDocs(root);
3406
- let changed = !fresh || !sameRepo || cached.repo !== repo;
3407
- const files = {};
3408
- for (const rel of paths) {
3409
- const abs = path5.join(root, rel);
3410
- let stat;
3411
- try {
3412
- stat = fs6.statSync(abs);
3413
- } catch {
3414
- changed = true;
3415
- continue;
3416
- }
3417
- const prev = sameRepo && cached.repo === repo ? cached.files[rel] : void 0;
3418
- if (prev && prev.mtimeMs === stat.mtimeMs && prev.size === stat.size) {
3419
- files[rel] = prev;
3420
- continue;
3421
- }
3422
- changed = true;
3423
- try {
3424
- const text2 = fs6.readFileSync(abs, "utf8");
3425
- files[rel] = { mtimeMs: stat.mtimeMs, size: stat.size, sections: parseRepoDoc({ repo, path: rel, text: text2 }, { orgId: config.orgId, ownerTeam, layer: source ? sourceLayer(source) : "org" }) };
3426
- } catch {
3427
- }
3428
- }
3429
- const index = {
3430
- format: INDEX_FORMAT,
3431
- repo,
3432
- ownerTeam,
3433
- listedAt: fresh ? cached.listedAt : new Date(now).toISOString(),
3434
- paths,
3435
- files
3436
- };
3437
- if (changed) {
3438
- try {
3439
- v2.writeRepoIndex(root, index);
3440
- } catch {
3441
- }
3600
+ // ../core/src/types.ts
3601
+ var init_types2 = __esm({
3602
+ "../core/src/types.ts"() {
3603
+ "use strict";
3442
3604
  }
3443
- return { root, index, sections: Object.values(files).flatMap((f) => f.sections) };
3444
- }
3445
- function relativeToRoot(root, file, cwd = root) {
3446
- if (!file) return null;
3447
- const abs = path5.isAbsolute(file) ? file : path5.resolve(cwd, file);
3448
- let real = abs;
3449
- let realRoot = root;
3450
- try {
3451
- realRoot = fs6.realpathSync(root);
3452
- } catch {
3605
+ });
3606
+
3607
+ // ../core/src/gate.ts
3608
+ var CURRENT_CHAT_PREFIX, ANAPHORIC_QUESTION;
3609
+ var init_gate = __esm({
3610
+ "../core/src/gate.ts"() {
3611
+ "use strict";
3612
+ CURRENT_CHAT_PREFIX = "(?:(?:so\\s+)?(?:in|within)\\s+(?:this|the)\\s+(?:chat|conversation|session)\\s*,?\\s*)?";
3613
+ ANAPHORIC_QUESTION = new RegExp(
3614
+ "^" + 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.*)$",
3615
+ "i"
3616
+ );
3453
3617
  }
3454
- try {
3455
- real = fs6.realpathSync(abs);
3456
- } catch {
3457
- try {
3458
- real = path5.join(fs6.realpathSync(path5.dirname(abs)), path5.basename(abs));
3459
- } catch {
3460
- }
3618
+ });
3619
+
3620
+ // ../core/src/metrics.ts
3621
+ var init_metrics = __esm({
3622
+ "../core/src/metrics.ts"() {
3623
+ "use strict";
3461
3624
  }
3462
- for (const [r, f] of [
3463
- [realRoot, real],
3464
- [root, abs]
3465
- ]) {
3466
- const rel = path5.relative(r, f);
3467
- if (rel && !rel.startsWith("..") && !path5.isAbsolute(rel)) return rel.split(path5.sep).join("/");
3625
+ });
3626
+
3627
+ // ../core/src/lesson/id.ts
3628
+ var init_id = __esm({
3629
+ "../core/src/lesson/id.ts"() {
3630
+ "use strict";
3468
3631
  }
3469
- return null;
3470
- }
3471
- var DOC_NAMES, SKIP_DIRS, LIST_TTL_MS, rootCache, isDoc, deployedSkill, INDEX_FORMAT;
3472
- var init_repo = __esm({
3473
- "src/v2/repo.ts"() {
3632
+ });
3633
+
3634
+ // ../core/src/lesson/markdown.ts
3635
+ var init_markdown2 = __esm({
3636
+ "../core/src/lesson/markdown.ts"() {
3474
3637
  "use strict";
3475
- init_v22();
3476
- init_source();
3477
- DOC_NAMES = /* @__PURE__ */ new Set(["spec.md", "testing.md", "skill.md"]);
3478
- SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", "dist", ".bunshin"]);
3479
- LIST_TTL_MS = 6e4;
3480
- rootCache = /* @__PURE__ */ new Map();
3481
- isDoc = (rel) => {
3482
- const parts = rel.split("/");
3483
- if (parts.some((p) => SKIP_DIRS.has(p))) return false;
3484
- return DOC_NAMES.has(parts[parts.length - 1].toLowerCase());
3485
- };
3486
- deployedSkill = (root, rel) => /(^|\/)SKILL\.md$/i.test(rel) && fs6.existsSync(path5.join(root, path5.posix.dirname(rel), ".bunshin.json"));
3487
- INDEX_FORMAT = 2;
3488
3638
  }
3489
3639
  });
3490
3640
 
3491
- // src/v2/source.ts
3492
- var source_exports = {};
3493
- __export(source_exports, {
3494
- cwdInPool: () => cwdInPool,
3495
- inPool: () => inPool,
3496
- listFolders: () => listFolders,
3497
- projectRootFor: () => projectRootFor,
3498
- select: () => select,
3499
- sourceFor: () => sourceFor,
3500
- storeHome: () => storeHome,
3501
- topFolder: () => topFolder
3502
- });
3503
- import fs7 from "node:fs";
3504
- import path6 from "node:path";
3505
- import { execFileSync as execFileSync2 } from "node:child_process";
3506
- function storeHome(storeRoot) {
3507
- return path6.dirname(path6.resolve(storeRoot));
3508
- }
3509
- function topFolder(cwd, storeRoot) {
3510
- const rel = path6.relative(storeHome(storeRoot), path6.resolve(cwd));
3511
- if (!rel || rel.startsWith("..") || path6.isAbsolute(rel)) return "";
3512
- return rel.split(path6.sep)[0] ?? "";
3513
- }
3514
- function inPool(selection, folder) {
3515
- if (!folder || !selection) return true;
3516
- if (selection.exclude?.includes(folder)) return false;
3517
- return selection.only ? selection.only.includes(folder) : true;
3518
- }
3519
- function cwdInPool(config, cwd, storeRoot) {
3520
- return inPool(config.sources, topFolder(cwd, storeRoot));
3521
- }
3522
- function git2(cwd, args) {
3523
- try {
3524
- return execFileSync2("git", ["-C", cwd, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 1500 }).trim() || null;
3525
- } catch {
3526
- return null;
3527
- }
3528
- }
3529
- function sourceFor(cwd, storeRoot, ctx) {
3530
- if (ctx?.kind === "robot") return sourceId("robot", ctx.id);
3531
- const key = `${path6.resolve(cwd)}
3532
- ${storeRoot}`;
3533
- if (sourceCache.has(key)) return sourceCache.get(key);
3534
- const found = findSource(cwd, storeRoot);
3535
- sourceCache.set(key, found);
3536
- return found;
3537
- }
3538
- function findSource(cwd, storeRoot) {
3539
- const home = storeHome(storeRoot);
3540
- const top = git2(cwd, ["rev-parse", "--show-toplevel"]);
3541
- if (top) {
3542
- const remote = git2(top, ["remote", "get-url", "origin"]);
3543
- const named = remote ? parseRemote(remote) : null;
3544
- if (named) return sourceId("repo", named);
3545
- const rel = path6.relative(home, top);
3546
- return sourceId("folder", rel && !rel.startsWith("..") && !path6.isAbsolute(rel) ? rel.split(path6.sep).join("/") : path6.basename(top));
3547
- }
3548
- const folder = topFolder(cwd, storeRoot);
3549
- return folder ? sourceId("folder", folder) : void 0;
3550
- }
3551
- function projectRootFor(cwd, storeRoot) {
3552
- const home = storeHome(storeRoot);
3553
- const top = git2(cwd, ["rev-parse", "--show-toplevel"]);
3554
- if (top) {
3555
- const rel = path6.relative(home, top);
3556
- if (!rel.startsWith("..") && !path6.isAbsolute(rel)) return top;
3557
- }
3558
- const folder = topFolder(cwd, storeRoot);
3559
- return folder ? path6.join(home, folder) : home;
3560
- }
3561
- function listFolders(storeRoot, selection, opts = {}) {
3562
- const home = storeHome(storeRoot);
3563
- let names = [];
3564
- try {
3565
- names = fs7.readdirSync(home, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name).sort((a, b) => a.localeCompare(b));
3566
- } catch {
3567
- }
3568
- return names.map((folder) => ({
3569
- folder,
3570
- included: inPool(selection, folder),
3571
- ...opts.sources ? { source: sourceFor(path6.join(home, folder), storeRoot) } : {}
3572
- }));
3573
- }
3574
- function select(current, action, folders) {
3575
- const uniq = (xs) => [...new Set(xs)].sort((a, b) => a.localeCompare(b));
3576
- const only = current?.only;
3577
- const exclude = current?.exclude ?? [];
3578
- let next;
3579
- switch (action) {
3580
- case "all":
3581
- return void 0;
3582
- case "only":
3583
- next = { only: uniq(folders) };
3584
- break;
3585
- case "include":
3586
- next = { ...only ? { only: uniq([...only, ...folders]) } : {}, exclude: exclude.filter((f) => !folders.includes(f)) };
3587
- break;
3588
- case "exclude":
3589
- next = { ...only ? { only: only.filter((f) => !folders.includes(f)) } : {}, exclude: uniq([...exclude, ...folders]) };
3590
- break;
3591
- }
3592
- if (!next.exclude?.length) delete next.exclude;
3593
- return next.only || next.exclude ? next : void 0;
3594
- }
3595
- var sourceCache;
3596
- var init_source = __esm({
3597
- "src/v2/source.ts"() {
3598
- "use strict";
3599
- init_v22();
3600
- init_repo();
3601
- sourceCache = /* @__PURE__ */ new Map();
3602
- }
3603
- });
3604
-
3605
- // ../core/src/types.ts
3606
- var init_types2 = __esm({
3607
- "../core/src/types.ts"() {
3608
- "use strict";
3609
- }
3610
- });
3611
-
3612
- // ../core/src/gate.ts
3613
- var CURRENT_CHAT_PREFIX, ANAPHORIC_QUESTION;
3614
- var init_gate = __esm({
3615
- "../core/src/gate.ts"() {
3616
- "use strict";
3617
- CURRENT_CHAT_PREFIX = "(?:(?:so\\s+)?(?:in|within)\\s+(?:this|the)\\s+(?:chat|conversation|session)\\s*,?\\s*)?";
3618
- ANAPHORIC_QUESTION = new RegExp(
3619
- "^" + 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.*)$",
3620
- "i"
3621
- );
3622
- }
3623
- });
3624
-
3625
- // ../core/src/metrics.ts
3626
- var init_metrics = __esm({
3627
- "../core/src/metrics.ts"() {
3628
- "use strict";
3629
- }
3630
- });
3631
-
3632
- // ../core/src/lesson/id.ts
3633
- var init_id = __esm({
3634
- "../core/src/lesson/id.ts"() {
3635
- "use strict";
3636
- }
3637
- });
3638
-
3639
- // ../core/src/lesson/markdown.ts
3640
- var init_markdown2 = __esm({
3641
- "../core/src/lesson/markdown.ts"() {
3642
- "use strict";
3643
- }
3644
- });
3645
-
3646
- // ../core/src/lesson/index.ts
3647
- var init_lesson = __esm({
3648
- "../core/src/lesson/index.ts"() {
3649
- "use strict";
3650
- }
3641
+ // ../core/src/lesson/index.ts
3642
+ var init_lesson = __esm({
3643
+ "../core/src/lesson/index.ts"() {
3644
+ "use strict";
3645
+ }
3651
3646
  });
3652
3647
 
3653
3648
  // ../core/src/serve/score.ts
@@ -4130,8 +4125,8 @@ __export(store_exports, {
4130
4125
  hexId: () => hexId,
4131
4126
  normalizeSession: () => normalizeSession
4132
4127
  });
4133
- import fs8 from "node:fs";
4134
- import path7 from "node:path";
4128
+ import fs6 from "node:fs";
4129
+ import path5 from "node:path";
4135
4130
  import { createHash as createHash2, randomBytes as randomBytes3 } from "node:crypto";
4136
4131
  function hexId(prefix) {
4137
4132
  return `${prefix}_${randomBytes3(6).toString("hex")}`;
@@ -4165,12 +4160,12 @@ var init_store2 = __esm({
4165
4160
  V2Store = class {
4166
4161
  constructor(store) {
4167
4162
  this.store = store;
4168
- this.dir = path7.join(store.root, "v2");
4163
+ this.dir = path5.join(store.root, "v2");
4169
4164
  }
4170
4165
  store;
4171
4166
  dir;
4172
4167
  p(...parts) {
4173
- return path7.join(this.dir, ...parts);
4168
+ return path5.join(this.dir, ...parts);
4174
4169
  }
4175
4170
  // ── context / bundle / params ──
4176
4171
  readContext() {
@@ -4251,9 +4246,9 @@ var init_store2 = __esm({
4251
4246
  const dir2 = this.p("sessions");
4252
4247
  if (!fileExists(dir2)) return [];
4253
4248
  const out = [];
4254
- for (const f of fs8.readdirSync(dir2)) {
4249
+ for (const f of fs6.readdirSync(dir2)) {
4255
4250
  if (!f.endsWith(".json") || f === "current.json") continue;
4256
- const raw = readJson(path7.join(dir2, f), null);
4251
+ const raw = readJson(path5.join(dir2, f), null);
4257
4252
  if (raw?.sessionId) out.push(normalizeSession(raw.sessionId, raw));
4258
4253
  }
4259
4254
  return out;
@@ -4281,7 +4276,7 @@ var init_store2 = __esm({
4281
4276
  let at = raw.at;
4282
4277
  if (!at) {
4283
4278
  try {
4284
- at = fs8.statSync(this.p("outcome", `${fileSafe(sessionId)}.json`)).mtime.toISOString();
4279
+ at = fs6.statSync(this.p("outcome", `${fileSafe(sessionId)}.json`)).mtime.toISOString();
4285
4280
  } catch {
4286
4281
  at = (/* @__PURE__ */ new Date()).toISOString();
4287
4282
  }
@@ -4307,14 +4302,14 @@ var init_store2 = __esm({
4307
4302
  }
4308
4303
  /** Exclusive lock file; returns a release function, or null when another process holds it. */
4309
4304
  tryLock(name, staleMs = 10 * 6e4) {
4310
- const file = this.p("locks", `${fileSafe(name)}.lock`);
4311
- ensureDir(path7.dirname(file));
4305
+ const file2 = this.p("locks", `${fileSafe(name)}.lock`);
4306
+ ensureDir(path5.dirname(file2));
4312
4307
  for (let attempt = 0; attempt < 2; attempt++) {
4313
4308
  try {
4314
- fs8.writeFileSync(file, String(process.pid), { flag: "wx" });
4309
+ fs6.writeFileSync(file2, String(process.pid), { flag: "wx" });
4315
4310
  return () => {
4316
4311
  try {
4317
- fs8.unlinkSync(file);
4312
+ fs6.unlinkSync(file2);
4318
4313
  } catch {
4319
4314
  }
4320
4315
  };
@@ -4322,8 +4317,8 @@ var init_store2 = __esm({
4322
4317
  if (err.code !== "EEXIST") return null;
4323
4318
  let stale = false;
4324
4319
  try {
4325
- const owner = Number(fs8.readFileSync(file, "utf8"));
4326
- const age = Date.now() - fs8.statSync(file).mtimeMs;
4320
+ const owner = Number(fs6.readFileSync(file2, "utf8"));
4321
+ const age = Date.now() - fs6.statSync(file2).mtimeMs;
4327
4322
  if (age > staleMs) stale = true;
4328
4323
  else if (Number.isInteger(owner) && owner > 0) {
4329
4324
  try {
@@ -4337,7 +4332,7 @@ var init_store2 = __esm({
4337
4332
  }
4338
4333
  if (!stale) return null;
4339
4334
  try {
4340
- fs8.unlinkSync(file);
4335
+ fs6.unlinkSync(file2);
4341
4336
  } catch {
4342
4337
  }
4343
4338
  }
@@ -4354,31 +4349,447 @@ var init_store2 = __esm({
4354
4349
  const dir2 = this.p(name);
4355
4350
  if (!fileExists(dir2)) return [];
4356
4351
  const out = [];
4357
- for (const f of fs8.readdirSync(dir2)) {
4352
+ for (const f of fs6.readdirSync(dir2)) {
4358
4353
  if (!f.endsWith(".json")) continue;
4359
- const v = readJson(path7.join(dir2, f), null);
4354
+ const v = readJson(path5.join(dir2, f), null);
4360
4355
  if (v) out.push(v);
4361
4356
  }
4362
4357
  return out;
4363
4358
  }
4364
4359
  };
4365
- rootKey = (root) => createHash2("sha256").update(path7.resolve(root)).digest("hex").slice(0, 16);
4360
+ rootKey = (root) => createHash2("sha256").update(path5.resolve(root)).digest("hex").slice(0, 16);
4366
4361
  addUnique = (list2, ...ids) => {
4367
4362
  for (const id of ids) if (id && !list2.includes(id)) list2.push(id);
4368
4363
  };
4369
4364
  }
4370
4365
  });
4371
4366
 
4367
+ // src/v2/atoms.ts
4368
+ var atoms_exports = {};
4369
+ __export(atoms_exports, {
4370
+ JUDGE_WINDOW: () => JUDGE_WINDOW,
4371
+ MAX_ACTIONS: () => MAX_ACTIONS,
4372
+ MAX_TRIGGERED: () => MAX_TRIGGERED,
4373
+ actionLine: () => actionLine,
4374
+ cmdAtoms: () => cmdAtoms,
4375
+ judgeFires: () => judgeFires,
4376
+ mutedTriggers: () => mutedTriggers,
4377
+ openFire: () => openFire,
4378
+ readTriggers: () => readTriggers,
4379
+ recordTriggers: () => recordTriggers,
4380
+ routerFires: () => routerFires,
4381
+ triggeredAtoms: () => triggeredAtoms
4382
+ });
4383
+ import fs7 from "node:fs";
4384
+ import path6 from "node:path";
4385
+ function readTriggers(v2) {
4386
+ try {
4387
+ const t = JSON.parse(fs7.readFileSync(file(v2), "utf8"));
4388
+ if (t?.v === 1 && t.triggers) return t;
4389
+ } catch {
4390
+ }
4391
+ return { v: 1, triggers: {} };
4392
+ }
4393
+ function mutedTriggers(v2) {
4394
+ return new Set(Object.entries(readTriggers(v2).triggers).filter(([, t]) => triggerMuted(t)).map(([k]) => k));
4395
+ }
4396
+ function recordTriggers(v2, updates, now = (/* @__PURE__ */ new Date()).toISOString()) {
4397
+ if (!updates.length) return;
4398
+ let release = null;
4399
+ for (let i = 0; i < 4 && !(release = v2.tryLock("atom-triggers", 1e4)); i++) {
4400
+ const until = Date.now() + 25;
4401
+ while (Date.now() < until) {
4402
+ }
4403
+ }
4404
+ if (!release) return;
4405
+ try {
4406
+ const t = readTriggers(v2);
4407
+ for (const u of updates) {
4408
+ const r = t.triggers[u.key] ??= { fires: 0, judged: 0, used: 0 };
4409
+ if (u.title) r.title = u.title.slice(0, 120);
4410
+ if (u.fired) {
4411
+ r.fires++;
4412
+ r.lastAt = now;
4413
+ }
4414
+ if (u.used !== void 0) {
4415
+ r.judged++;
4416
+ if (u.used) r.used++;
4417
+ }
4418
+ }
4419
+ writeJsonAtomic(file(v2), t);
4420
+ } catch {
4421
+ } finally {
4422
+ release();
4423
+ }
4424
+ }
4425
+ function actionLine(tool, text2) {
4426
+ return `${tool}: ${redact2(text2).replace(/\s+/g, " ").trim().slice(0, 240)}`;
4427
+ }
4428
+ function judgeFires(s, text2, expire) {
4429
+ const open = s.fires ?? [];
4430
+ if (!open.length) return [];
4431
+ const calls = s.toolCalls ?? 0;
4432
+ const out = [];
4433
+ const keep = [];
4434
+ for (const f of open) {
4435
+ if (text2 && cuesIn(f.cues, text2).length) out.push({ key: f.key, used: true });
4436
+ else if (expire && calls - f.call >= JUDGE_WINDOW) out.push({ key: f.key, used: false });
4437
+ else keep.push(f);
4438
+ }
4439
+ s.fires = keep;
4440
+ return out;
4441
+ }
4442
+ function openFire(atom, key, call2, firingText) {
4443
+ const cues = usageCues(atom).filter((c) => !firingText.toLowerCase().includes(c));
4444
+ return cues.length ? { key, id: atom.id, call: call2, cues } : null;
4445
+ }
4446
+ function triggeredAtoms(v2, sections, reader, call2, inContext2, callNo) {
4447
+ const hits = toolTriggerHits(sections, reader, call2, { exclude: inContext2, muted: mutedTriggers(v2), max: MAX_TRIGGERED });
4448
+ const why = hits.map((h) => `a ${call2.tool} call matched its trigger (${h.match})`);
4449
+ return {
4450
+ atoms: hits.map((h) => h.section),
4451
+ text: hits.map((h, i) => renderSection(h.section, why[i], { deployed: false })).join("\n\n"),
4452
+ updates: hits.map((h) => ({ key: h.key, title: h.section.title, fired: true })),
4453
+ fires: hits.map((h) => openFire(h.section, h.key, callNo, call2.text)).filter((f) => !!f),
4454
+ why
4455
+ };
4456
+ }
4457
+ function routerFires(atoms, callNo, firingText) {
4458
+ const short = atoms.filter(isAtom);
4459
+ const key = (s) => `${s.id}#router@v${s.version}`;
4460
+ return {
4461
+ updates: short.map((s) => ({ key: key(s), title: s.title, fired: true })),
4462
+ fires: short.map((s) => openFire(s, key(s), callNo, firingText)).filter((f) => !!f)
4463
+ };
4464
+ }
4465
+ function cmdAtoms(store, args, out) {
4466
+ const rows = Object.entries(readTriggers(new V2Store(store)).triggers).map(([key, t]) => ({ key, ...t, precision: triggerPrecision(t), muted: triggerMuted(t) }));
4467
+ rows.sort((a, b) => (a.precision ?? 2) - (b.precision ?? 2) || b.fires - a.fires);
4468
+ if (args.flags.json === true) {
4469
+ out(`${JSON.stringify(rows, null, 2)}
4470
+ `);
4471
+ return 0;
4472
+ }
4473
+ if (!rows.length) {
4474
+ out("No atom has fired on this machine yet.\n");
4475
+ return 0;
4476
+ }
4477
+ for (const r of rows) {
4478
+ const p = r.precision === null ? " \u2014" : `${String(Math.round(r.precision * 100)).padStart(3)}%`;
4479
+ 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}` : ""}
4480
+ `);
4481
+ }
4482
+ 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.
4483
+ `);
4484
+ return 0;
4485
+ }
4486
+ var JUDGE_WINDOW, MAX_TRIGGERED, MAX_ACTIONS, file;
4487
+ var init_atoms2 = __esm({
4488
+ "src/v2/atoms.ts"() {
4489
+ "use strict";
4490
+ init_v22();
4491
+ init_redact2();
4492
+ init_util();
4493
+ init_store2();
4494
+ JUDGE_WINDOW = 8;
4495
+ MAX_TRIGGERED = 2;
4496
+ MAX_ACTIONS = 20;
4497
+ file = (v2) => path6.join(v2.dir, "atoms", "triggers.json");
4498
+ }
4499
+ });
4500
+
4501
+ // src/v2/repo.ts
4502
+ import fs8 from "node:fs";
4503
+ import path7 from "node:path";
4504
+ import { execFileSync } from "node:child_process";
4505
+ function git(cwd, args, timeout = 1500) {
4506
+ try {
4507
+ return execFileSync("git", ["-C", cwd, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout, maxBuffer: 64 * 1024 * 1024 });
4508
+ } catch {
4509
+ return null;
4510
+ }
4511
+ }
4512
+ function repoRoot(cwd, storeRoot) {
4513
+ const key = `${cwd}
4514
+ ${storeRoot ?? ""}`;
4515
+ const hit = rootCache.get(key);
4516
+ if (hit) return hit;
4517
+ const top = git(cwd, ["rev-parse", "--show-toplevel"])?.trim();
4518
+ let root = top || "";
4519
+ if (!root && storeRoot && path7.basename(storeRoot) === ".bunshin") {
4520
+ const parent = path7.dirname(storeRoot);
4521
+ if (path7.resolve(cwd).startsWith(path7.resolve(parent))) root = parent;
4522
+ }
4523
+ root = root || path7.resolve(cwd);
4524
+ rootCache.set(key, root);
4525
+ return root;
4526
+ }
4527
+ function parseRemote(url) {
4528
+ const clean2 = url.trim().replace(/\.git$/, "").replace(/\/+$/, "");
4529
+ if (!clean2) return null;
4530
+ const scp = clean2.match(/^[^@/\s]+@[^:/\s]+:(.+)$/);
4531
+ const pathPart = scp ? scp[1] : (() => {
4532
+ try {
4533
+ return new URL(clean2).pathname;
4534
+ } catch {
4535
+ return clean2;
4536
+ }
4537
+ })();
4538
+ const segs = pathPart.split("/").filter(Boolean);
4539
+ if (segs.length >= 2) return `${segs[segs.length - 2]}/${segs[segs.length - 1]}`;
4540
+ return segs[0] ?? null;
4541
+ }
4542
+ function repoName(root) {
4543
+ const url = git(root, ["remote", "get-url", "origin"]);
4544
+ return url && parseRemote(url) || path7.basename(root);
4545
+ }
4546
+ function repoCommit(root) {
4547
+ return git(root, ["rev-parse", "HEAD"])?.trim() || void 0;
4548
+ }
4549
+ function listDocs(root) {
4550
+ const listed = git(root, ["ls-files", "-co", "--exclude-standard", "-z"], 3e3);
4551
+ 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();
4552
+ const out = [];
4553
+ let visited = 0;
4554
+ const walk = (dir2, rel, depth) => {
4555
+ if (depth > 8 || visited++ > 2e4) return;
4556
+ let entries;
4557
+ try {
4558
+ entries = fs8.readdirSync(dir2, { withFileTypes: true });
4559
+ } catch {
4560
+ return;
4561
+ }
4562
+ for (const e of entries) {
4563
+ if (e.isDirectory()) {
4564
+ 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);
4565
+ } else if (e.isFile()) {
4566
+ const r = rel ? `${rel}/${e.name}` : e.name;
4567
+ if (isDoc(r) && !deployedSkill(root, r)) out.push(r);
4568
+ }
4569
+ }
4570
+ };
4571
+ walk(root, "", 0);
4572
+ return out.sort();
4573
+ }
4574
+ function indexWorkingTree(v2, config, cwd, opts = {}) {
4575
+ const root = repoRoot(cwd, v2.store.root);
4576
+ const now = opts.now ?? Date.now();
4577
+ const cached = v2.readRepoIndex(root);
4578
+ const ownerTeam = config.ownerTeam || config.orgUnit || "unknown";
4579
+ const source = sourceFor(root, v2.store.root);
4580
+ const sameRepo = cached && cached.ownerTeam === ownerTeam && cached.format === INDEX_FORMAT;
4581
+ const repo = sameRepo && cached.repo && !opts.force ? cached.repo : repoName(root);
4582
+ const fresh = sameRepo && cached.repo === repo && cached.paths && cached.listedAt && now - Date.parse(cached.listedAt) < LIST_TTL_MS && !opts.force;
4583
+ const paths = fresh ? cached.paths : listDocs(root);
4584
+ let changed = !fresh || !sameRepo || cached.repo !== repo;
4585
+ const files = {};
4586
+ for (const rel of paths) {
4587
+ const abs = path7.join(root, rel);
4588
+ let stat;
4589
+ try {
4590
+ stat = fs8.statSync(abs);
4591
+ } catch {
4592
+ changed = true;
4593
+ continue;
4594
+ }
4595
+ const prev = sameRepo && cached.repo === repo ? cached.files[rel] : void 0;
4596
+ if (prev && prev.mtimeMs === stat.mtimeMs && prev.size === stat.size) {
4597
+ files[rel] = prev;
4598
+ continue;
4599
+ }
4600
+ changed = true;
4601
+ try {
4602
+ const text2 = fs8.readFileSync(abs, "utf8");
4603
+ files[rel] = { mtimeMs: stat.mtimeMs, size: stat.size, sections: parseRepoDoc({ repo, path: rel, text: text2 }, { orgId: config.orgId, ownerTeam, layer: source ? sourceLayer(source) : "org" }) };
4604
+ } catch {
4605
+ }
4606
+ }
4607
+ const index = {
4608
+ format: INDEX_FORMAT,
4609
+ repo,
4610
+ ownerTeam,
4611
+ listedAt: fresh ? cached.listedAt : new Date(now).toISOString(),
4612
+ paths,
4613
+ files
4614
+ };
4615
+ if (changed) {
4616
+ try {
4617
+ v2.writeRepoIndex(root, index);
4618
+ } catch {
4619
+ }
4620
+ }
4621
+ return { root, index, sections: Object.values(files).flatMap((f) => f.sections) };
4622
+ }
4623
+ function relativeToRoot(root, file2, cwd = root) {
4624
+ if (!file2) return null;
4625
+ const abs = path7.isAbsolute(file2) ? file2 : path7.resolve(cwd, file2);
4626
+ let real = abs;
4627
+ let realRoot = root;
4628
+ try {
4629
+ realRoot = fs8.realpathSync(root);
4630
+ } catch {
4631
+ }
4632
+ try {
4633
+ real = fs8.realpathSync(abs);
4634
+ } catch {
4635
+ try {
4636
+ real = path7.join(fs8.realpathSync(path7.dirname(abs)), path7.basename(abs));
4637
+ } catch {
4638
+ }
4639
+ }
4640
+ for (const [r, f] of [
4641
+ [realRoot, real],
4642
+ [root, abs]
4643
+ ]) {
4644
+ const rel = path7.relative(r, f);
4645
+ if (rel && !rel.startsWith("..") && !path7.isAbsolute(rel)) return rel.split(path7.sep).join("/");
4646
+ }
4647
+ return null;
4648
+ }
4649
+ var DOC_NAMES, SKIP_DIRS, LIST_TTL_MS, rootCache, isDoc, deployedSkill, INDEX_FORMAT;
4650
+ var init_repo = __esm({
4651
+ "src/v2/repo.ts"() {
4652
+ "use strict";
4653
+ init_v22();
4654
+ init_source();
4655
+ DOC_NAMES = /* @__PURE__ */ new Set(["spec.md", "testing.md", "skill.md"]);
4656
+ SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", "dist", ".bunshin"]);
4657
+ LIST_TTL_MS = 6e4;
4658
+ rootCache = /* @__PURE__ */ new Map();
4659
+ isDoc = (rel) => {
4660
+ const parts = rel.split("/");
4661
+ if (parts.some((p) => SKIP_DIRS.has(p))) return false;
4662
+ return DOC_NAMES.has(parts[parts.length - 1].toLowerCase());
4663
+ };
4664
+ deployedSkill = (root, rel) => /(^|\/)SKILL\.md$/i.test(rel) && fs8.existsSync(path7.join(root, path7.posix.dirname(rel), ".bunshin.json"));
4665
+ INDEX_FORMAT = 2;
4666
+ }
4667
+ });
4668
+
4669
+ // src/v2/source.ts
4670
+ var source_exports = {};
4671
+ __export(source_exports, {
4672
+ cwdInPool: () => cwdInPool,
4673
+ inPool: () => inPool,
4674
+ listFolders: () => listFolders,
4675
+ projectRootFor: () => projectRootFor,
4676
+ select: () => select,
4677
+ sourceFor: () => sourceFor,
4678
+ storeHome: () => storeHome,
4679
+ topFolder: () => topFolder
4680
+ });
4681
+ import fs9 from "node:fs";
4682
+ import path8 from "node:path";
4683
+ import { execFileSync as execFileSync2 } from "node:child_process";
4684
+ function storeHome(storeRoot) {
4685
+ return path8.dirname(path8.resolve(storeRoot));
4686
+ }
4687
+ function topFolder(cwd, storeRoot) {
4688
+ const rel = path8.relative(storeHome(storeRoot), path8.resolve(cwd));
4689
+ if (!rel || rel.startsWith("..") || path8.isAbsolute(rel)) return "";
4690
+ return rel.split(path8.sep)[0] ?? "";
4691
+ }
4692
+ function inPool(selection, folder) {
4693
+ if (!folder || !selection) return true;
4694
+ if (selection.exclude?.includes(folder)) return false;
4695
+ return selection.only ? selection.only.includes(folder) : true;
4696
+ }
4697
+ function cwdInPool(config, cwd, storeRoot) {
4698
+ return inPool(config.sources, topFolder(cwd, storeRoot));
4699
+ }
4700
+ function git2(cwd, args) {
4701
+ try {
4702
+ return execFileSync2("git", ["-C", cwd, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 1500 }).trim() || null;
4703
+ } catch {
4704
+ return null;
4705
+ }
4706
+ }
4707
+ function sourceFor(cwd, storeRoot, ctx) {
4708
+ if (ctx?.kind === "robot") return sourceId("robot", ctx.id);
4709
+ const key = `${path8.resolve(cwd)}
4710
+ ${storeRoot}`;
4711
+ if (sourceCache.has(key)) return sourceCache.get(key);
4712
+ const found = findSource(cwd, storeRoot);
4713
+ sourceCache.set(key, found);
4714
+ return found;
4715
+ }
4716
+ function findSource(cwd, storeRoot) {
4717
+ const home = storeHome(storeRoot);
4718
+ const top = git2(cwd, ["rev-parse", "--show-toplevel"]);
4719
+ if (top) {
4720
+ const remote = git2(top, ["remote", "get-url", "origin"]);
4721
+ const named = remote ? parseRemote(remote) : null;
4722
+ if (named) return sourceId("repo", named);
4723
+ const rel = path8.relative(home, top);
4724
+ return sourceId("folder", rel && !rel.startsWith("..") && !path8.isAbsolute(rel) ? rel.split(path8.sep).join("/") : path8.basename(top));
4725
+ }
4726
+ const folder = topFolder(cwd, storeRoot);
4727
+ return folder ? sourceId("folder", folder) : void 0;
4728
+ }
4729
+ function projectRootFor(cwd, storeRoot) {
4730
+ const home = storeHome(storeRoot);
4731
+ const top = git2(cwd, ["rev-parse", "--show-toplevel"]);
4732
+ if (top) {
4733
+ const rel = path8.relative(home, top);
4734
+ if (!rel.startsWith("..") && !path8.isAbsolute(rel)) return top;
4735
+ }
4736
+ const folder = topFolder(cwd, storeRoot);
4737
+ return folder ? path8.join(home, folder) : home;
4738
+ }
4739
+ function listFolders(storeRoot, selection, opts = {}) {
4740
+ const home = storeHome(storeRoot);
4741
+ let names = [];
4742
+ try {
4743
+ names = fs9.readdirSync(home, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name).sort((a, b) => a.localeCompare(b));
4744
+ } catch {
4745
+ }
4746
+ return names.map((folder) => ({
4747
+ folder,
4748
+ included: inPool(selection, folder),
4749
+ ...opts.sources ? { source: sourceFor(path8.join(home, folder), storeRoot) } : {}
4750
+ }));
4751
+ }
4752
+ function select(current, action, folders) {
4753
+ const uniq = (xs) => [...new Set(xs)].sort((a, b) => a.localeCompare(b));
4754
+ const only = current?.only;
4755
+ const exclude = current?.exclude ?? [];
4756
+ let next;
4757
+ switch (action) {
4758
+ case "all":
4759
+ return void 0;
4760
+ case "only":
4761
+ next = { only: uniq(folders) };
4762
+ break;
4763
+ case "include":
4764
+ next = { ...only ? { only: uniq([...only, ...folders]) } : {}, exclude: exclude.filter((f) => !folders.includes(f)) };
4765
+ break;
4766
+ case "exclude":
4767
+ next = { ...only ? { only: only.filter((f) => !folders.includes(f)) } : {}, exclude: uniq([...exclude, ...folders]) };
4768
+ break;
4769
+ }
4770
+ if (!next.exclude?.length) delete next.exclude;
4771
+ return next.only || next.exclude ? next : void 0;
4772
+ }
4773
+ var sourceCache;
4774
+ var init_source = __esm({
4775
+ "src/v2/source.ts"() {
4776
+ "use strict";
4777
+ init_v22();
4778
+ init_repo();
4779
+ sourceCache = /* @__PURE__ */ new Map();
4780
+ }
4781
+ });
4782
+
4372
4783
  // src/v2/deploy.ts
4373
4784
  import { execFileSync as execFileSync3 } from "node:child_process";
4374
4785
  import { createHash as createHash3 } from "node:crypto";
4375
- import fs9 from "node:fs";
4786
+ import fs10 from "node:fs";
4376
4787
  import os2 from "node:os";
4377
- import path8 from "node:path";
4788
+ import path9 from "node:path";
4378
4789
  function deployWorkspace(env = process.env) {
4379
- if (env.BUNSHIN_DEPLOY_WORKSPACE) return path8.resolve(env.BUNSHIN_DEPLOY_WORKSPACE);
4790
+ if (env.BUNSHIN_DEPLOY_WORKSPACE) return path9.resolve(env.BUNSHIN_DEPLOY_WORKSPACE);
4380
4791
  try {
4381
- const ws = JSON.parse(fs9.readFileSync(settingsFile(env.BUNSHIN_DEPLOY_HOME || os2.homedir()), "utf8")).workspace;
4792
+ const ws = JSON.parse(fs10.readFileSync(settingsFile(env.BUNSHIN_DEPLOY_HOME || os2.homedir()), "utf8")).workspace;
4382
4793
  return typeof ws === "string" && ws ? ws : null;
4383
4794
  } catch {
4384
4795
  return null;
@@ -4387,46 +4798,46 @@ function deployWorkspace(env = process.env) {
4387
4798
  function deployPaths(env = process.env, orgId) {
4388
4799
  const home = env.BUNSHIN_DEPLOY_HOME || os2.homedir();
4389
4800
  const ws = deployWorkspace(env);
4390
- const state = path8.join(home, ".bunshin", "deploy");
4391
- const shared = { claude: path8.join(ws ?? home, ".claude", "skills"), codex: path8.join(ws ?? home, ".codex", "skills") };
4392
- const org = orgId ? path8.join(state, orgKey(orgId)) : null;
4801
+ const state = path9.join(home, ".bunshin", "deploy");
4802
+ const shared = { claude: path9.join(ws ?? home, ".claude", "skills"), codex: path9.join(ws ?? home, ".codex", "skills") };
4803
+ const org = orgId ? path9.join(state, orgKey(orgId)) : null;
4393
4804
  return {
4394
4805
  home,
4395
- claudeSkills: org ? path8.join(org, "claude-skills") : shared.claude,
4396
- codexSkills: org ? path8.join(org, "codex-skills") : shared.codex,
4397
- ...org ? { legacy: [.../* @__PURE__ */ new Set([shared.claude, shared.codex, path8.join(home, ".claude", "skills"), path8.join(home, ".codex", "skills"), path8.join(home, ".bunshin", "library")])] } : {},
4398
- claudeMd: ws ? path8.join(ws, "CLAUDE.md") : path8.join(home, ".claude", "CLAUDE.md"),
4399
- agentsMd: ws ? path8.join(ws, "AGENTS.md") : path8.join(home, ".codex", "AGENTS.md"),
4400
- library: org ? path8.join(org, "library") : path8.join(home, ".bunshin", "library"),
4806
+ claudeSkills: org ? path9.join(org, "claude-skills") : shared.claude,
4807
+ codexSkills: org ? path9.join(org, "codex-skills") : shared.codex,
4808
+ ...org ? { legacy: [.../* @__PURE__ */ new Set([shared.claude, shared.codex, path9.join(home, ".claude", "skills"), path9.join(home, ".codex", "skills"), path9.join(home, ".bunshin", "library")])] } : {},
4809
+ claudeMd: ws ? path9.join(ws, "CLAUDE.md") : path9.join(home, ".claude", "CLAUDE.md"),
4810
+ agentsMd: ws ? path9.join(ws, "AGENTS.md") : path9.join(home, ".codex", "AGENTS.md"),
4811
+ library: org ? path9.join(org, "library") : path9.join(home, ".bunshin", "library"),
4401
4812
  // Pack executables are linked into one folder on PATH (shared by name; their files are per organization).
4402
- bin: path8.join(home, ".bunshin", "bin"),
4813
+ bin: path9.join(home, ".bunshin", "bin"),
4403
4814
  state
4404
4815
  };
4405
4816
  }
4406
4817
  function statePath(p, orgId) {
4407
- return path8.join(p.state, `${orgKey(orgId)}.json`);
4818
+ return path9.join(p.state, `${orgKey(orgId)}.json`);
4408
4819
  }
4409
4820
  function readState(p, orgId) {
4410
4821
  const s = readJson(statePath(p, orgId), null);
4411
4822
  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 } : {} };
4412
4823
  }
4413
- function readText(file) {
4824
+ function readText(file2) {
4414
4825
  try {
4415
- return fs9.readFileSync(file, "utf8");
4826
+ return fs10.readFileSync(file2, "utf8");
4416
4827
  } catch {
4417
4828
  return null;
4418
4829
  }
4419
4830
  }
4420
- function writeFile(file, content, mode) {
4421
- writeTextAtomic(file, content);
4831
+ function writeFile(file2, content, mode) {
4832
+ writeTextAtomic(file2, content);
4422
4833
  try {
4423
- fs9.chmodSync(file, mode === "x" ? 493 : 420);
4834
+ fs10.chmodSync(file2, mode === "x" ? 493 : 420);
4424
4835
  } catch {
4425
4836
  }
4426
4837
  }
4427
- function removeFile(file) {
4838
+ function removeFile(file2) {
4428
4839
  try {
4429
- fs9.unlinkSync(file);
4840
+ fs10.unlinkSync(file2);
4430
4841
  } catch {
4431
4842
  }
4432
4843
  }
@@ -4434,33 +4845,33 @@ function pruneDirs(dir2, stop) {
4434
4845
  let d = dir2;
4435
4846
  while (d.startsWith(stop) && d !== stop) {
4436
4847
  try {
4437
- if (fs9.readdirSync(d).length) return;
4438
- fs9.rmdirSync(d);
4848
+ if (fs10.readdirSync(d).length) return;
4849
+ fs10.rmdirSync(d);
4439
4850
  } catch {
4440
4851
  return;
4441
4852
  }
4442
- d = path8.dirname(d);
4853
+ d = path9.dirname(d);
4443
4854
  }
4444
4855
  }
4445
4856
  function listFiles(dir2, base = dir2) {
4446
4857
  let entries;
4447
4858
  try {
4448
- entries = fs9.readdirSync(dir2, { withFileTypes: true });
4859
+ entries = fs10.readdirSync(dir2, { withFileTypes: true });
4449
4860
  } catch {
4450
4861
  return [];
4451
4862
  }
4452
4863
  const out = [];
4453
4864
  for (const e of entries) {
4454
- const abs = path8.join(dir2, e.name);
4865
+ const abs = path9.join(dir2, e.name);
4455
4866
  if (e.isDirectory()) out.push(...listFiles(abs, base));
4456
- else if (e.isFile()) out.push(path8.relative(base, abs).split(path8.sep).join("/"));
4867
+ else if (e.isFile()) out.push(path9.relative(base, abs).split(path9.sep).join("/"));
4457
4868
  }
4458
4869
  return out.sort();
4459
4870
  }
4460
4871
  function childDir(root, name) {
4461
4872
  if (!name || !SAFE_NAME.test(name)) return null;
4462
- const dir2 = path8.join(root, name);
4463
- return path8.dirname(path8.resolve(dir2)) === path8.resolve(root) && insideRoot(root, dir2) ? dir2 : null;
4873
+ const dir2 = path9.join(root, name);
4874
+ return path9.dirname(path9.resolve(dir2)) === path9.resolve(root) && insideRoot(root, dir2) ? dir2 : null;
4464
4875
  }
4465
4876
  function layerRank(layer, tree) {
4466
4877
  const kind = layerKind(layer);
@@ -4541,8 +4952,8 @@ function planDeploy(bundle, p, harnesses) {
4541
4952
  }
4542
4953
  return plan;
4543
4954
  }
4544
- function readBlock(file) {
4545
- const text2 = readText(file);
4955
+ function readBlock(file2) {
4956
+ const text2 = readText(file2);
4546
4957
  if (text2 === null) return null;
4547
4958
  const start = text2.indexOf(BLOCK_BEGIN);
4548
4959
  const end = text2.indexOf(BLOCK_END);
@@ -4564,25 +4975,25 @@ ${neutralizeMarkers(d.text).replace(/\n*$/, "\n")}`),
4564
4975
  ];
4565
4976
  return parts.join("\n");
4566
4977
  }
4567
- function removeBlock(file) {
4568
- const text2 = readText(file);
4978
+ function removeBlock(file2) {
4979
+ const text2 = readText(file2);
4569
4980
  if (text2 === null) return false;
4570
4981
  const start = text2.indexOf(BLOCK_BEGIN);
4571
4982
  const end = text2.indexOf(BLOCK_END);
4572
4983
  if (start < 0 || end < start) return false;
4573
4984
  const rest = (text2.slice(0, start).replace(/\s*$/, "") + "\n" + text2.slice(end + BLOCK_END.length).replace(/^\s*/, "")).trim();
4574
- if (rest) writeTextAtomic(file, rest + "\n");
4575
- else fs9.unlinkSync(file);
4985
+ if (rest) writeTextAtomic(file2, rest + "\n");
4986
+ else fs10.unlinkSync(file2);
4576
4987
  return true;
4577
4988
  }
4578
- function writeBlock(file, block2) {
4579
- const text2 = readText(file) ?? "";
4989
+ function writeBlock(file2, block2) {
4990
+ const text2 = readText(file2) ?? "";
4580
4991
  const start = text2.indexOf(BLOCK_BEGIN);
4581
4992
  const end = text2.indexOf(BLOCK_END);
4582
4993
  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}
4583
4994
  `;
4584
4995
  if (next === text2) return false;
4585
- writeTextAtomic(file, next);
4996
+ writeTextAtomic(file2, next);
4586
4997
  return true;
4587
4998
  }
4588
4999
  function skillIndex(skills, p) {
@@ -4593,7 +5004,7 @@ function skillIndex(skills, p) {
4593
5004
  "",
4594
5005
  "When a task matches a skill below, read its SKILL.md and follow it before doing the work by hand.",
4595
5006
  "",
4596
- ...skills.map((s) => `- **${s.skill.name}** (\`${path8.join(p.codexSkills, s.skill.name, "SKILL.md")}\`): ${neutralizeMarkers(s.skill.description).replace(/\s+/g, " ").trim()}`)
5007
+ ...skills.map((s) => `- **${s.skill.name}** (\`${path9.join(p.codexSkills, s.skill.name, "SKILL.md")}\`): ${neutralizeMarkers(s.skill.description).replace(/\s+/g, " ").trim()}`)
4597
5008
  ];
4598
5009
  return lines.join("\n");
4599
5010
  }
@@ -4642,7 +5053,7 @@ function captureDoc(c, doc, out) {
4642
5053
  for (const dir2 of doc.dirs ?? []) {
4643
5054
  for (const rel of listFiles(dir2)) {
4644
5055
  if (rel === "SKILL.md" || rel === MANIFEST || seen.has(`file:${rel}`)) continue;
4645
- const abs = path8.join(dir2, rel);
5056
+ const abs = path9.join(dir2, rel);
4646
5057
  const content = readText(abs);
4647
5058
  if (content === null || Buffer.byteLength(content) > MAX_FILE) continue;
4648
5059
  byRel.set(`file:${rel}`, { target: { abs, rel, role: "file", sha: "", ...isExecutable(abs) ? { mode: "x" } : {} }, content });
@@ -4681,18 +5092,18 @@ function captureNewSkills(c, state, roots, owned, incoming, out, layer, only) {
4681
5092
  for (const root of roots) {
4682
5093
  let names = [];
4683
5094
  try {
4684
- names = fs9.readdirSync(root, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name);
5095
+ names = fs10.readdirSync(root, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name);
4685
5096
  } catch {
4686
5097
  continue;
4687
5098
  }
4688
5099
  for (const name of names) {
4689
- const dir2 = path8.join(root, name);
5100
+ const dir2 = path9.join(root, name);
4690
5101
  if (owned.has(dir2) || incoming.has(name) || only && name !== only) continue;
4691
- const skillMd = readText(path8.join(dir2, "SKILL.md"));
5102
+ const skillMd = readText(path9.join(dir2, "SKILL.md"));
4692
5103
  if (skillMd === null) continue;
4693
5104
  let born = 0;
4694
5105
  try {
4695
- const st = fs9.statSync(path8.join(dir2, "SKILL.md"));
5106
+ const st = fs10.statSync(path9.join(dir2, "SKILL.md"));
4696
5107
  born = Math.min(st.birthtimeMs || st.mtimeMs, st.mtimeMs);
4697
5108
  } catch {
4698
5109
  continue;
@@ -4701,8 +5112,8 @@ function captureNewSkills(c, state, roots, owned, incoming, out, layer, only) {
4701
5112
  const files = {};
4702
5113
  for (const rel of listFiles(dir2).filter((r) => !r.split("/").some((seg) => seg.startsWith(".")))) {
4703
5114
  if (rel === "SKILL.md" || rel === MANIFEST) continue;
4704
- const content = readText(path8.join(dir2, rel));
4705
- if (content !== null && Buffer.byteLength(content) <= MAX_FILE) files[rel] = { content, ...isExecutable(path8.join(dir2, rel)) ? { mode: "x" } : {} };
5115
+ const content = readText(path9.join(dir2, rel));
5116
+ if (content !== null && Buffer.byteLength(content) <= MAX_FILE) files[rel] = { content, ...isExecutable(path9.join(dir2, rel)) ? { mode: "x" } : {} };
4706
5117
  }
4707
5118
  const hash = sha(JSON.stringify([skillMd, files]));
4708
5119
  if (state.created[name]?.hash === hash) continue;
@@ -4750,15 +5161,15 @@ function captureEdits(v2, config, ctx, opts = {}) {
4750
5161
  }
4751
5162
  function lockDeploy(p) {
4752
5163
  ensureDir(p.state);
4753
- const file = path8.join(p.state, ".lock");
5164
+ const file2 = path9.join(p.state, ".lock");
4754
5165
  for (let i = 0; i < 2; i++) {
4755
5166
  try {
4756
- fs9.writeFileSync(file, String(process.pid), { flag: "wx" });
4757
- return () => removeFile(file);
5167
+ fs10.writeFileSync(file2, String(process.pid), { flag: "wx" });
5168
+ return () => removeFile(file2);
4758
5169
  } catch {
4759
5170
  try {
4760
- const age = Date.now() - fs9.statSync(file).mtimeMs;
4761
- const pid = Number(readText(file));
5171
+ const age = Date.now() - fs10.statSync(file2).mtimeMs;
5172
+ const pid = Number(readText(file2));
4762
5173
  let alive = age < 12e4;
4763
5174
  if (alive && pid > 0) {
4764
5175
  try {
@@ -4768,7 +5179,7 @@ function lockDeploy(p) {
4768
5179
  }
4769
5180
  }
4770
5181
  if (alive) return null;
4771
- removeFile(file);
5182
+ removeFile(file2);
4772
5183
  } catch {
4773
5184
  }
4774
5185
  }
@@ -4824,7 +5235,7 @@ function deployLocked(v2, config, ctx, bundle, opts, p, harnesses, now) {
4824
5235
  const foreign = /* @__PURE__ */ new Set();
4825
5236
  if (d.kind === "skill" && !prev) {
4826
5237
  for (const dir2 of d.dirs ?? []) {
4827
- const cur = readText(path8.join(dir2, "SKILL.md"));
5238
+ const cur = readText(path9.join(dir2, "SKILL.md"));
4828
5239
  if (cur === null || cur === d.section.body || state.created[d.name]) continue;
4829
5240
  foreign.add(dir2);
4830
5241
  report.warnings.push(`${dir2} is not managed by Bunshin; the library's ${d.name} skill was not installed there`);
@@ -4836,7 +5247,7 @@ function deployLocked(v2, config, ctx, bundle, opts, p, harnesses, now) {
4836
5247
  targets.push({ ...t, sha: sha(neutralizeMarkers(d.section.body).replace(/\n*$/, "\n")) });
4837
5248
  continue;
4838
5249
  }
4839
- if ([...foreign].some((dir2) => t.abs.startsWith(dir2 + path8.sep))) continue;
5250
+ if ([...foreign].some((dir2) => t.abs.startsWith(dir2 + path9.sep))) continue;
4840
5251
  if (!(d.dirs ?? (d.root ? [d.root] : [])).some((r) => insideRoot(r, t.abs))) {
4841
5252
  report.warnings.push(`${t.abs} not written: it leads outside its folder`);
4842
5253
  continue;
@@ -4845,10 +5256,10 @@ function deployLocked(v2, config, ctx, bundle, opts, p, harnesses, now) {
4845
5256
  const existing = readText(t.abs);
4846
5257
  try {
4847
5258
  if (existing !== content) {
4848
- ensureDir(path8.dirname(t.abs));
5259
+ ensureDir(path9.dirname(t.abs));
4849
5260
  writeFile(t.abs, content, t.mode);
4850
5261
  report.written++;
4851
- } else if (t.mode === "x" && !isExecutable(t.abs)) fs9.chmodSync(t.abs, 493);
5262
+ } else if (t.mode === "x" && !isExecutable(t.abs)) fs10.chmodSync(t.abs, 493);
4852
5263
  } catch (err) {
4853
5264
  report.warnings.push(`${t.abs} not written: ${err instanceof Error ? err.message : String(err)}`);
4854
5265
  continue;
@@ -4861,19 +5272,19 @@ function deployLocked(v2, config, ctx, bundle, opts, p, harnesses, now) {
4861
5272
  const cur = readText(old.abs);
4862
5273
  if (cur !== null && sha(cur) === old.sha) {
4863
5274
  removeFile(old.abs);
4864
- pruneDirs(path8.dirname(old.abs), d.kind === "skill" ? path8.dirname(path8.dirname(old.abs)) : p.library);
5275
+ pruneDirs(path9.dirname(old.abs), d.kind === "skill" ? path9.dirname(path9.dirname(old.abs)) : p.library);
4865
5276
  report.removed++;
4866
5277
  }
4867
5278
  }
4868
5279
  if (d.kind === "skill") {
4869
5280
  for (const dir2 of prev?.dirs ?? []) {
4870
5281
  if ((d.dirs ?? []).includes(dir2) || !removable(dir2)) continue;
4871
- removeFile(path8.join(dir2, MANIFEST));
4872
- pruneDirs(dir2, path8.dirname(dir2));
5282
+ removeFile(path9.join(dir2, MANIFEST));
5283
+ pruneDirs(dir2, path9.dirname(dir2));
4873
5284
  }
4874
5285
  for (const dir2 of d.dirs ?? []) {
4875
5286
  const manifest = safeJoin(dir2, MANIFEST);
4876
- if (foreign.has(dir2) || !manifest || !fs9.existsSync(path8.join(dir2, "SKILL.md"))) continue;
5287
+ if (foreign.has(dir2) || !manifest || !fs10.existsSync(path9.join(dir2, "SKILL.md"))) continue;
4877
5288
  writeJsonAtomic(manifest, { sectionId: id, name: d.name, version: d.section.version, libraryVersion: bundle.libraryVersion ?? null, managedBy: "bunshin sync" });
4878
5289
  }
4879
5290
  report.skills++;
@@ -4898,12 +5309,12 @@ function deployLocked(v2, config, ctx, bundle, opts, p, harnesses, now) {
4898
5309
  }
4899
5310
  for (const dir2 of doc.dirs ?? []) {
4900
5311
  if (!removable(dir2)) continue;
4901
- removeFile(path8.join(dir2, MANIFEST));
4902
- pruneDirs(dir2, path8.dirname(dir2));
4903
- if (fs9.existsSync(dir2)) {
5312
+ removeFile(path9.join(dir2, MANIFEST));
5313
+ pruneDirs(dir2, path9.dirname(dir2));
5314
+ if (fs10.existsSync(dir2)) {
4904
5315
  const left = listFiles(dir2);
4905
5316
  if (left.length) report.warnings.push(`${dir2} kept: it has files Bunshin did not write`);
4906
- else pruneDirs(dir2, path8.dirname(dir2));
5317
+ else pruneDirs(dir2, path9.dirname(dir2));
4907
5318
  }
4908
5319
  }
4909
5320
  }
@@ -4919,17 +5330,17 @@ function deployLocked(v2, config, ctx, bundle, opts, p, harnesses, now) {
4919
5330
  if (d.kind === "skill") continue;
4920
5331
  for (const t of d.targets) {
4921
5332
  if (t.role === "block" || t.mode !== "x" || !/(^|\/)bin\/[^/]+$/.test(t.rel) || !owned(t.abs)) continue;
4922
- const link = path8.join(p.bin, path8.basename(t.abs));
5333
+ const link = path9.join(p.bin, path9.basename(t.abs));
4923
5334
  ensureDir(p.bin);
4924
5335
  try {
4925
- const cur = fs9.readlinkSync(link);
5336
+ const cur = fs10.readlinkSync(link);
4926
5337
  if (cur !== t.abs) {
4927
- fs9.unlinkSync(link);
4928
- fs9.symlinkSync(t.abs, link);
5338
+ fs10.unlinkSync(link);
5339
+ fs10.symlinkSync(t.abs, link);
4929
5340
  }
4930
5341
  } catch {
4931
5342
  try {
4932
- if (!fs9.existsSync(link)) fs9.symlinkSync(t.abs, link);
5343
+ if (!fs10.existsSync(link)) fs10.symlinkSync(t.abs, link);
4933
5344
  } catch {
4934
5345
  }
4935
5346
  }
@@ -4940,19 +5351,19 @@ function deployLocked(v2, config, ctx, bundle, opts, p, harnesses, now) {
4940
5351
  if (harnesses.has("claude-code")) {
4941
5352
  for (const pack of packs) {
4942
5353
  const dir2 = childDir(p.library, pack);
4943
- if (!dir2 || !insideRoot(dir2, path8.join(dir2, ".claude", "x"))) continue;
4944
- const link = path8.join(dir2, ".claude", "skills");
5354
+ if (!dir2 || !insideRoot(dir2, path9.join(dir2, ".claude", "x"))) continue;
5355
+ const link = path9.join(dir2, ".claude", "skills");
4945
5356
  try {
4946
- fs9.lstatSync(link);
4947
- if (fs9.readlinkSync(link) !== p.claudeSkills) {
4948
- fs9.unlinkSync(link);
4949
- fs9.symlinkSync(p.claudeSkills, link);
5357
+ fs10.lstatSync(link);
5358
+ if (fs10.readlinkSync(link) !== p.claudeSkills) {
5359
+ fs10.unlinkSync(link);
5360
+ fs10.symlinkSync(p.claudeSkills, link);
4950
5361
  }
4951
5362
  } catch {
4952
- ensureDir(path8.dirname(link));
5363
+ ensureDir(path9.dirname(link));
4953
5364
  ensureDir(p.claudeSkills);
4954
5365
  try {
4955
- fs9.symlinkSync(p.claudeSkills, link);
5366
+ fs10.symlinkSync(p.claudeSkills, link);
4956
5367
  } catch {
4957
5368
  }
4958
5369
  }
@@ -4961,8 +5372,8 @@ function deployLocked(v2, config, ctx, bundle, opts, p, harnesses, now) {
4961
5372
  for (const old of state.links) {
4962
5373
  if (links.has(old)) continue;
4963
5374
  try {
4964
- const target = fs9.readlinkSync(old);
4965
- if (!fs9.existsSync(target)) fs9.unlinkSync(old);
5375
+ const target = fs10.readlinkSync(old);
5376
+ if (!fs10.existsSync(target)) fs10.unlinkSync(old);
4966
5377
  } catch {
4967
5378
  }
4968
5379
  }
@@ -4970,7 +5381,7 @@ function deployLocked(v2, config, ctx, bundle, opts, p, harnesses, now) {
4970
5381
  if (p.legacy) {
4971
5382
  const deployed = Object.values(next).filter((d) => d.kind === "skill" && (d.dirs ?? []).length);
4972
5383
  const layerOf = new Map(plan.skills.map((x) => [x.skill.name, x.layer]));
4973
- const roots = [.../* @__PURE__ */ new Set([...linked, ...opts.linkRoot ? [path8.resolve(opts.linkRoot)] : []])];
5384
+ const roots = [.../* @__PURE__ */ new Set([...linked, ...opts.linkRoot ? [path9.resolve(opts.linkRoot)] : []])];
4974
5385
  linked = [];
4975
5386
  for (const root of roots) {
4976
5387
  let source;
@@ -5001,13 +5412,13 @@ function materialize(sections, dir2) {
5001
5412
  const put = (rel, content, mode) => {
5002
5413
  const abs = safeJoin(dir2, rel);
5003
5414
  if (!abs) return;
5004
- ensureDir(path8.dirname(abs));
5415
+ ensureDir(path9.dirname(abs));
5005
5416
  writeFile(abs, content, mode);
5006
5417
  files++;
5007
5418
  };
5008
5419
  for (const s of sections.filter((x) => x.status === "active" || x.status === "stale")) {
5009
5420
  if (s.skill) {
5010
- const base = s.packPath && /(^|\/)SKILL\.md$/.test(s.packPath) ? path8.posix.dirname(s.packPath) : `.claude/skills/${s.skill.name}`;
5421
+ const base = s.packPath && /(^|\/)SKILL\.md$/.test(s.packPath) ? path9.posix.dirname(s.packPath) : `.claude/skills/${s.skill.name}`;
5011
5422
  put(`${base}/SKILL.md`, s.body);
5012
5423
  for (const [rel, f] of Object.entries(s.skill.files ?? {})) put(`${base}/${rel}`, f.content, f.mode);
5013
5424
  continue;
@@ -5019,51 +5430,51 @@ function materialize(sections, dir2) {
5019
5430
  }
5020
5431
  function linkSkills(p, root, harnesses, names) {
5021
5432
  const out = { linked: 0, removed: 0, kept: false, warnings: [] };
5022
- const abs = path8.resolve(root);
5023
- if (abs === path8.resolve(p.home) || abs === path8.resolve(os2.homedir()) || !fs9.existsSync(abs)) return out;
5024
- const managed = (target) => target.startsWith(path8.resolve(p.state) + path8.sep);
5433
+ const abs = path9.resolve(root);
5434
+ if (abs === path9.resolve(p.home) || abs === path9.resolve(os2.homedir()) || !fs10.existsSync(abs)) return out;
5435
+ const managed = (target) => target.startsWith(path9.resolve(p.state) + path9.sep);
5025
5436
  const excluded = [];
5026
5437
  for (const h of harnesses) {
5027
5438
  const spec = LINK_DIRS[h];
5028
5439
  if (!spec) continue;
5029
- const dir2 = path8.join(abs, spec.rel);
5030
- const canonical = path8.resolve(p[spec.key]);
5031
- const want = new Set(names.filter((n) => SAFE_NAME.test(n) && fs9.existsSync(path8.join(canonical, n, "SKILL.md"))));
5440
+ const dir2 = path9.join(abs, spec.rel);
5441
+ const canonical = path9.resolve(p[spec.key]);
5442
+ const want = new Set(names.filter((n) => SAFE_NAME.test(n) && fs10.existsSync(path9.join(canonical, n, "SKILL.md"))));
5032
5443
  let entries = [];
5033
5444
  try {
5034
- entries = fs9.readdirSync(dir2, { withFileTypes: true });
5445
+ entries = fs10.readdirSync(dir2, { withFileTypes: true });
5035
5446
  } catch {
5036
5447
  }
5037
5448
  for (const e of entries) {
5038
5449
  if (!e.isSymbolicLink()) continue;
5039
- const link = path8.join(dir2, e.name);
5450
+ const link = path9.join(dir2, e.name);
5040
5451
  let target = "";
5041
5452
  try {
5042
- target = path8.resolve(dir2, fs9.readlinkSync(link));
5453
+ target = path9.resolve(dir2, fs10.readlinkSync(link));
5043
5454
  } catch {
5044
5455
  continue;
5045
5456
  }
5046
5457
  if (!managed(target)) continue;
5047
- if (want.has(e.name) && target === path8.join(canonical, e.name)) {
5458
+ if (want.has(e.name) && target === path9.join(canonical, e.name)) {
5048
5459
  want.delete(e.name);
5049
- excluded.push(path8.join(spec.rel, e.name));
5460
+ excluded.push(path9.join(spec.rel, e.name));
5050
5461
  continue;
5051
5462
  }
5052
5463
  removeFile(link);
5053
5464
  out.removed++;
5054
5465
  }
5055
5466
  for (const name of want) {
5056
- const link = path8.join(dir2, name);
5467
+ const link = path9.join(dir2, name);
5057
5468
  try {
5058
- fs9.lstatSync(link);
5469
+ fs10.lstatSync(link);
5059
5470
  out.warnings.push(`${link} is the project's own; the library's ${name} skill was not linked there`);
5060
5471
  continue;
5061
5472
  } catch {
5062
5473
  }
5063
5474
  try {
5064
5475
  ensureDir(dir2);
5065
- fs9.symlinkSync(path8.join(canonical, name), link, "dir");
5066
- excluded.push(path8.join(spec.rel, name));
5476
+ fs10.symlinkSync(path9.join(canonical, name), link, "dir");
5477
+ excluded.push(path9.join(spec.rel, name));
5067
5478
  out.linked++;
5068
5479
  } catch (err) {
5069
5480
  out.warnings.push(`${link} not linked: ${err instanceof Error ? err.message : String(err)}`);
@@ -5076,26 +5487,26 @@ function linkSkills(p, root, harnesses, names) {
5076
5487
  return out;
5077
5488
  }
5078
5489
  function gitExclude(root, rels) {
5079
- if (!fs9.existsSync(path8.join(root, ".git"))) return;
5080
- let file;
5490
+ if (!fs10.existsSync(path9.join(root, ".git"))) return;
5491
+ let file2;
5081
5492
  try {
5082
- file = path8.resolve(root, execFileSync3("git", ["-C", root, "rev-parse", "--git-path", "info/exclude"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 2e3 }).trim());
5493
+ file2 = path9.resolve(root, execFileSync3("git", ["-C", root, "rev-parse", "--git-path", "info/exclude"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 2e3 }).trim());
5083
5494
  } catch {
5084
5495
  return;
5085
5496
  }
5086
- const cur = readText(file) ?? "";
5497
+ const cur = readText(file2) ?? "";
5087
5498
  const start = cur.indexOf(EXCLUDE_BEGIN);
5088
5499
  const end = start >= 0 ? cur.indexOf(EXCLUDE_END, start) : -1;
5089
5500
  const rest = start >= 0 && end >= 0 ? cur.slice(0, start) + cur.slice(end + EXCLUDE_END.length).replace(/^\n/, "") : cur;
5090
5501
  const block2 = rels.length ? `${EXCLUDE_BEGIN}
5091
- ${[...new Set(rels)].sort().map((r) => `/${r.split(path8.sep).join("/")}`).join("\n")}
5502
+ ${[...new Set(rels)].sort().map((r) => `/${r.split(path9.sep).join("/")}`).join("\n")}
5092
5503
  ${EXCLUDE_END}
5093
5504
  ` : "";
5094
5505
  const next = block2 ? `${rest}${rest && !rest.endsWith("\n") ? "\n" : ""}${block2}` : rest;
5095
5506
  if (next === cur) return;
5096
5507
  try {
5097
- ensureDir(path8.dirname(file));
5098
- fs9.writeFileSync(file, next);
5508
+ ensureDir(path9.dirname(file2));
5509
+ fs10.writeFileSync(file2, next);
5099
5510
  } catch {
5100
5511
  }
5101
5512
  }
@@ -5107,16 +5518,16 @@ var init_deploy = __esm({
5107
5518
  init_source();
5108
5519
  init_util();
5109
5520
  init_store2();
5110
- settingsFile = (home) => path8.join(home, ".bunshin", "deploy", "settings.json");
5521
+ settingsFile = (home) => path9.join(home, ".bunshin", "deploy", "settings.json");
5111
5522
  orgKey = (orgId) => orgId.replace(/[^A-Za-z0-9._-]/g, "_") || "org";
5112
5523
  sha = (text2) => createHash3("sha256").update(text2).digest("hex");
5113
5524
  BLOCK_BEGIN = "<!-- bunshin:begin -->";
5114
5525
  BLOCK_END = "<!-- bunshin:end -->";
5115
5526
  MANIFEST = ".bunshin.json";
5116
5527
  MAX_FILE = 2 * 1024 * 1024;
5117
- isExecutable = (file) => {
5528
+ isExecutable = (file2) => {
5118
5529
  try {
5119
- return (fs9.statSync(file).mode & 73) !== 0;
5530
+ return (fs10.statSync(file2).mode & 73) !== 0;
5120
5531
  } catch {
5121
5532
  return false;
5122
5533
  }
@@ -5127,8 +5538,8 @@ var init_deploy = __esm({
5127
5538
  docMarker = (id, version2) => `<!-- bunshin:doc id=${id} v=${version2} -->`;
5128
5539
  BORN_SLACK_MS = 2e3;
5129
5540
  LINK_DIRS = {
5130
- "claude-code": { rel: path8.join(".claude", "skills"), key: "claudeSkills" },
5131
- codex: { rel: path8.join(".codex", "skills"), key: "codexSkills" }
5541
+ "claude-code": { rel: path9.join(".claude", "skills"), key: "claudeSkills" },
5542
+ codex: { rel: path9.join(".codex", "skills"), key: "codexSkills" }
5132
5543
  };
5133
5544
  EXCLUDE_BEGIN = "# >>> bunshin: library skills linked here (managed by bunshin sync)";
5134
5545
  EXCLUDE_END = "# <<< bunshin";
@@ -5240,11 +5651,11 @@ var init_live = __esm({
5240
5651
  });
5241
5652
 
5242
5653
  // src/transcript.ts
5243
- import fs10 from "node:fs";
5244
- function parseTranscript(file) {
5654
+ import fs11 from "node:fs";
5655
+ function parseTranscript(file2) {
5245
5656
  let raw = "";
5246
5657
  try {
5247
- raw = fs10.readFileSync(file, "utf8");
5658
+ raw = fs11.readFileSync(file2, "utf8");
5248
5659
  } catch {
5249
5660
  return { turns: [], userMessages: 0, toolCalls: 0, toolFailures: 0 };
5250
5661
  }
@@ -5442,8 +5853,8 @@ function traceChunks(turns, maxBytes = 1e6) {
5442
5853
  if (cur) out.push(cur);
5443
5854
  return out;
5444
5855
  }
5445
- function recentContext(file, { turns = 2, maxChars = 6e3 } = {}) {
5446
- const facts = parseTranscript(file);
5856
+ function recentContext(file2, { turns = 2, maxChars = 6e3 } = {}) {
5857
+ const facts = parseTranscript(file2);
5447
5858
  const visible = facts.turns.filter((t) => t.role !== "tool");
5448
5859
  const userIdx = visible.map((t, i) => t.role === "user" ? i : -1).filter((i) => i >= 0);
5449
5860
  const start = userIdx.length > turns ? userIdx[userIdx.length - turns] : 0;
@@ -5564,7 +5975,7 @@ var init_view = __esm({
5564
5975
  });
5565
5976
 
5566
5977
  // src/v2/apply.ts
5567
- import fs11 from "node:fs";
5978
+ import fs12 from "node:fs";
5568
5979
  function appendedText(op) {
5569
5980
  return op.condition ? `- **${op.condition}:** ${op.text.trim()}` : op.text.trim();
5570
5981
  }
@@ -5617,14 +6028,14 @@ function applyLocally(v2, view, s) {
5617
6028
  const section = s.target.sectionId ? view.byId.get(s.target.sectionId) : void 0;
5618
6029
  if (!section) return { applied: false, target: s.target.sectionId ?? "?", reason: "target section not in the local view" };
5619
6030
  if (section.storage.type === "repo") {
5620
- const file = containedPath(view.root, section.storage.path);
6031
+ const file2 = isDoc(section.storage.path) ? containedPath(view.root, section.storage.path) : null;
5621
6032
  const ours = !view.repo || section.storage.repo === view.repo;
5622
- if (ours && file && fs11.existsSync(file)) {
5623
- const before = fs11.readFileSync(file, "utf8");
6033
+ if (ours && file2 && fs12.existsSync(file2)) {
6034
+ const before = fs12.readFileSync(file2, "utf8");
5624
6035
  const res2 = applyOpToMarkdown(before, section.storage.anchor, op);
5625
6036
  if (res2.ok) {
5626
6037
  const changed = res2.text !== before;
5627
- if (changed) fs11.writeFileSync(file, res2.text);
6038
+ if (changed) fs12.writeFileSync(file2, res2.text);
5628
6039
  const overlay2 = { ...base, kind: "working-tree", sectionId: section.id, file: section.storage.path, anchor: section.storage.anchor, changed };
5629
6040
  upsertOverlay(v2, overlay2);
5630
6041
  return { applied: true, target: describeTarget(s, view), overlay: overlay2 };
@@ -5641,11 +6052,11 @@ function applyLocally(v2, view, s) {
5641
6052
  function revertWorkingTree(root, o) {
5642
6053
  if (o.changed === false) return { reverted: false, reason: "edit was a no-op" };
5643
6054
  if (!o.file) return { reverted: false, reason: "no file" };
5644
- const file = containedPath(root, o.file);
5645
- if (!file) return { reverted: false, reason: "path outside the repository" };
6055
+ const file2 = containedPath(root, o.file);
6056
+ if (!file2) return { reverted: false, reason: "path outside the repository" };
5646
6057
  let text2;
5647
6058
  try {
5648
- text2 = fs11.readFileSync(file, "utf8");
6059
+ text2 = fs12.readFileSync(file2, "utf8");
5649
6060
  } catch {
5650
6061
  return { reverted: false, reason: "file missing" };
5651
6062
  }
@@ -5665,7 +6076,7 @@ ${appendedText(o.op)}`;
5665
6076
  if (once(text2, o.op.text) >= 0 && !text2.includes(o.op.find)) next = text2.replace(o.op.text, o.op.find);
5666
6077
  }
5667
6078
  if (next === null) return { reverted: false, reason: "file changed since the trial edit" };
5668
- fs11.writeFileSync(file, next);
6079
+ fs12.writeFileSync(file2, next);
5669
6080
  return { reverted: true };
5670
6081
  }
5671
6082
  function revertParam(v2, o) {
@@ -5727,6 +6138,7 @@ var init_apply = __esm({
5727
6138
  "use strict";
5728
6139
  init_v22();
5729
6140
  init_util();
6141
+ init_repo();
5730
6142
  init_view();
5731
6143
  STATUS_FOR = {
5732
6144
  "drop-overlay": "accepted",
@@ -5738,7 +6150,7 @@ var init_apply = __esm({
5738
6150
  });
5739
6151
 
5740
6152
  // src/v2/signals.ts
5741
- import fs12 from "node:fs";
6153
+ import fs13 from "node:fs";
5742
6154
  function isCorrection(text2) {
5743
6155
  const t = text2.trim().slice(0, 600);
5744
6156
  return !!t && CORRECTION_RE.test(t);
@@ -5755,16 +6167,16 @@ function codeOf(input) {
5755
6167
  if (v && typeof v === "object" && typeof v.code === "string") return v.code;
5756
6168
  return null;
5757
6169
  }
5758
- function scanTranscript(file) {
6170
+ function scanTranscript(file2) {
5759
6171
  const empty = { facts: { turns: [], userMessages: 0, toolCalls: 0, toolFailures: 0 }, snippets: [] };
5760
- if (!file) return empty;
6172
+ if (!file2) return empty;
5761
6173
  let raw;
5762
6174
  try {
5763
- raw = fs12.readFileSync(file, "utf8");
6175
+ raw = fs13.readFileSync(file2, "utf8");
5764
6176
  } catch {
5765
6177
  return empty;
5766
6178
  }
5767
- const out = { facts: parseTranscript(file), snippets: [] };
6179
+ const out = { facts: parseTranscript(file2), snippets: [] };
5768
6180
  for (const text2 of raw.split("\n")) {
5769
6181
  if (!text2.trim()) continue;
5770
6182
  let line;
@@ -5844,8 +6256,28 @@ var init_signals = __esm({
5844
6256
  });
5845
6257
 
5846
6258
  // src/v2/ui.ts
5847
- import fs13 from "node:fs";
5848
- import path9 from "node:path";
6259
+ var ui_exports = {};
6260
+ __export(ui_exports, {
6261
+ MOD_FRESH_MS: () => MOD_FRESH_MS,
6262
+ UI_FEED_VERSION: () => UI_FEED_VERSION,
6263
+ addEvent: () => addEvent,
6264
+ addServed: () => addServed,
6265
+ cliArgv: () => cliArgv,
6266
+ feedLines: () => feedLines,
6267
+ feedPath: () => feedPath,
6268
+ label: () => label,
6269
+ latestFeed: () => latestFeed,
6270
+ modActive: () => modActive,
6271
+ modPath: () => modPath,
6272
+ readFeed: () => readFeed,
6273
+ renderFeed: () => renderFeed,
6274
+ takeLines: () => takeLines,
6275
+ uiMode: () => uiMode,
6276
+ updateFeed: () => updateFeed,
6277
+ whyServed: () => whyServed
6278
+ });
6279
+ import fs14 from "node:fs";
6280
+ import path10 from "node:path";
5849
6281
  function feedPath(v2, sessionId) {
5850
6282
  return v2.p("ui", `${safe(sessionId)}.json`);
5851
6283
  }
@@ -5861,7 +6293,7 @@ function emptyFeed(v2, sessionId, now) {
5861
6293
  }
5862
6294
  function cliArgv() {
5863
6295
  const entry = process.argv[1];
5864
- return entry ? [process.execPath, path9.resolve(entry)] : ["bunshin"];
6296
+ return entry ? [process.execPath, path10.resolve(entry)] : ["bunshin"];
5865
6297
  }
5866
6298
  function updateFeed(v2, sessionId, patch, now = (/* @__PURE__ */ new Date()).toISOString()) {
5867
6299
  if (!sessionId || sessionId === "no-session") return null;
@@ -5876,7 +6308,7 @@ function updateFeed(v2, sessionId, patch, now = (/* @__PURE__ */ new Date()).toI
5876
6308
  f.cli = cliArgv();
5877
6309
  f.served = f.served.slice(0, MAX_SERVED);
5878
6310
  f.events = f.events.slice(-MAX_EVENTS);
5879
- fs13.mkdirSync(path9.dirname(feedPath(v2, sessionId)), { recursive: true });
6311
+ fs14.mkdirSync(path10.dirname(feedPath(v2, sessionId)), { recursive: true });
5880
6312
  writeJsonAtomic(feedPath(v2, sessionId), f);
5881
6313
  return f;
5882
6314
  } catch {
@@ -5977,16 +6409,16 @@ function latestFeed(v2) {
5977
6409
  const dir2 = v2.p("ui");
5978
6410
  let best = null;
5979
6411
  try {
5980
- for (const f2 of fs13.readdirSync(dir2)) {
6412
+ for (const f2 of fs14.readdirSync(dir2)) {
5981
6413
  if (!f2.endsWith(".json") || f2.endsWith(".mod.json")) continue;
5982
- const m = fs13.statSync(path9.join(dir2, f2)).mtimeMs;
6414
+ const m = fs14.statSync(path10.join(dir2, f2)).mtimeMs;
5983
6415
  if (!best || m > best.m) best = { f: f2, m };
5984
6416
  }
5985
6417
  } catch {
5986
6418
  return null;
5987
6419
  }
5988
6420
  if (!best) return null;
5989
- const f = readJson(path9.join(dir2, best.f), null);
6421
+ const f = readJson(path10.join(dir2, best.f), null);
5990
6422
  return f && f.v === UI_FEED_VERSION ? f : null;
5991
6423
  }
5992
6424
  var UI_FEED_VERSION, MAX_SERVED, MAX_EVENTS, MOD_FRESH_MS, DEFAULT_MODES;
@@ -6011,8 +6443,8 @@ __export(sync_exports, {
6011
6443
  syncV2: () => syncV2,
6012
6444
  uploadIndex: () => uploadIndex
6013
6445
  });
6014
- import fs14 from "node:fs";
6015
- import path10 from "node:path";
6446
+ import fs15 from "node:fs";
6447
+ import path11 from "node:path";
6016
6448
  function episodePayload(e) {
6017
6449
  const { orgId: _o, uploaded: _u, servedReported: _s, reportedServed: _rs, reportedLoaded: _rl, transcriptPath: _tp, ...rest } = e;
6018
6450
  void _o, _u, _s, _rs, _rl, _tp;
@@ -6045,15 +6477,15 @@ function markForRetrace(v2, { days = 30, now = Date.now() } = {}) {
6045
6477
  for (const e of v2.listEpisodes()) {
6046
6478
  if (e.upload === "header-only" || e.cliVersion || !e.transcript) continue;
6047
6479
  if (now - Date.parse(e.endedAt || e.startedAt) > days * 864e5) continue;
6048
- const file = e.transcriptPath ?? v2.readSession(e.sessionId)?.transcriptPath;
6049
- if (!file || !fs14.existsSync(file)) {
6480
+ const file2 = e.transcriptPath ?? v2.readSession(e.sessionId)?.transcriptPath;
6481
+ if (!file2 || !fs15.existsSync(file2)) {
6050
6482
  missing++;
6051
6483
  continue;
6052
6484
  }
6053
- const turns = e.turns ?? parseTranscript(file).turns.length;
6485
+ const turns = e.turns ?? parseTranscript(file2).turns.length;
6054
6486
  const { transcript: _t, ...rest } = e;
6055
6487
  void _t;
6056
- v2.writeEpisode({ ...rest, transcriptPath: file, transcriptFrom: e.transcriptFrom ?? 0, turns, cliVersion: version(), uploaded: false });
6488
+ v2.writeEpisode({ ...rest, transcriptPath: file2, transcriptFrom: e.transcriptFrom ?? 0, turns, cliVersion: version(), uploaded: false });
6057
6489
  queued++;
6058
6490
  }
6059
6491
  return { queued, missing };
@@ -6061,7 +6493,7 @@ function markForRetrace(v2, { days = 30, now = Date.now() } = {}) {
6061
6493
  async function syncV2(store, opts = {}) {
6062
6494
  const v2 = new V2Store(store);
6063
6495
  const config = store.config();
6064
- const cwd = opts.cwd ?? path10.dirname(store.root);
6496
+ const cwd = opts.cwd ?? path11.dirname(store.root);
6065
6497
  const report = { offline: !canCall(config), uploadedEpisodes: 0, deferredTraces: 0, uploadedSuggestions: 0, trialUpdates: 0, bundle: v2.readBundle() ? "cached" : "none", settled: [], errors: [] };
6066
6498
  const deadline = Date.now() + (opts.budgetMs ?? 24e4);
6067
6499
  if (report.offline) {
@@ -6208,7 +6640,7 @@ async function uploadIndex(store, cwd, deadline = Date.now() + 3e4) {
6208
6640
  const { root, index } = indexWorkingTree(v2, config, cwd, { force: true });
6209
6641
  const docs = (index.paths ?? Object.keys(index.files)).flatMap((rel) => {
6210
6642
  try {
6211
- return [{ path: rel, text: fs14.readFileSync(path10.join(root, rel), "utf8") }];
6643
+ return [{ path: rel, text: fs15.readFileSync(path11.join(root, rel), "utf8") }];
6212
6644
  } catch {
6213
6645
  return [];
6214
6646
  }
@@ -6239,7 +6671,7 @@ var init_sync = __esm({
6239
6671
  // src/v2/reflect.ts
6240
6672
  import { spawn as spawn3 } from "node:child_process";
6241
6673
  import { createHash as createHash4 } from "node:crypto";
6242
- import fs15 from "node:fs";
6674
+ import fs16 from "node:fs";
6243
6675
  function episodeIdFor(contextId, sessionId) {
6244
6676
  return `e_${createHash4("sha256").update(`${contextId}
6245
6677
  ${sessionId}`).digest("hex").slice(0, 16)}`;
@@ -6274,7 +6706,7 @@ function runClaudeFork(sessionId, prompt, { cwd, model, timeoutMs = FORK_TIMEOUT
6274
6706
  };
6275
6707
  let child;
6276
6708
  try {
6277
- child = spawn3(bin, args, { cwd: cwd && fs15.existsSync(cwd) ? cwd : void 0, env: modelEnv("claude-cli"), stdio: ["ignore", "pipe", "pipe"] });
6709
+ child = spawn3(bin, args, { cwd: cwd && fs16.existsSync(cwd) ? cwd : void 0, env: modelEnv("claude-cli"), stdio: ["ignore", "pipe", "pipe"] });
6278
6710
  } catch (e) {
6279
6711
  resolve({ ok: false, error: e instanceof Error ? e.message : String(e) });
6280
6712
  return;
@@ -6316,10 +6748,10 @@ function reflectionIndex(view, ids, task, focus, humanTurns = []) {
6316
6748
  } catch {
6317
6749
  }
6318
6750
  }
6319
- return [...chosen.values()].slice(0, 30).map(({ id, kind, layer, title, when, outline }) => ({ id, kind, layer, title, when, ...outline?.length ? { outline } : {} }));
6751
+ return withSpineAtoms([...chosen.values()].slice(0, 30), view.sections).map(({ id, kind, layer, title, when, outline }) => ({ id, kind, layer, title, when, ...outline?.length ? { outline } : {} }));
6320
6752
  }
6321
6753
  function humanTurnsOf(transcriptPath) {
6322
- if (!transcriptPath || !fs15.existsSync(transcriptPath)) return [];
6754
+ if (!transcriptPath || !fs16.existsSync(transcriptPath)) return [];
6323
6755
  try {
6324
6756
  return parseTranscript(transcriptPath).turns.filter((t) => t.role === "user" && t.text.trim()).map((t) => t.text.slice(0, 1e3));
6325
6757
  } catch {
@@ -6327,7 +6759,7 @@ function humanTurnsOf(transcriptPath) {
6327
6759
  }
6328
6760
  }
6329
6761
  function readFacts(transcriptPath) {
6330
- if (!transcriptPath || !fs15.existsSync(transcriptPath)) return null;
6762
+ if (!transcriptPath || !fs16.existsSync(transcriptPath)) return null;
6331
6763
  try {
6332
6764
  return parseTranscript(transcriptPath);
6333
6765
  } catch {
@@ -6390,7 +6822,7 @@ async function runReflectionV2(store, opts) {
6390
6822
  result.method = "fork";
6391
6823
  } else result.error = fork.error;
6392
6824
  }
6393
- if (result.method === "none" && session.transcriptPath && fs15.existsSync(session.transcriptPath)) {
6825
+ if (result.method === "none" && session.transcriptPath && fs16.existsSync(session.transcriptPath)) {
6394
6826
  const transcriptDigest = digest(facts ?? parseTranscript(session.transcriptPath), { from, maxChars: 4e4 });
6395
6827
  const res = await askJson(config, {
6396
6828
  system: "You are Bunshin's reflection pass. Follow the instructions in the user message and reply with one JSON object only.",
@@ -6519,11 +6951,11 @@ __export(route_exports, {
6519
6951
  });
6520
6952
  import { spawn as spawn4 } from "node:child_process";
6521
6953
  import { createHash as createHash5 } from "node:crypto";
6522
- import fs16 from "node:fs";
6523
- import path11 from "node:path";
6524
- function readJson2(file) {
6954
+ import fs17 from "node:fs";
6955
+ import path12 from "node:path";
6956
+ function readJson2(file2) {
6525
6957
  try {
6526
- return JSON.parse(fs16.readFileSync(file, "utf8"));
6958
+ return JSON.parse(fs17.readFileSync(file2, "utf8"));
6527
6959
  } catch {
6528
6960
  return null;
6529
6961
  }
@@ -6531,12 +6963,12 @@ function readJson2(file) {
6531
6963
  function lastReply(transcriptPath, maxBytes = 256e3) {
6532
6964
  if (!transcriptPath) return void 0;
6533
6965
  try {
6534
- const fd = fs16.openSync(transcriptPath, "r");
6966
+ const fd = fs17.openSync(transcriptPath, "r");
6535
6967
  try {
6536
- const size = fs16.fstatSync(fd).size;
6968
+ const size = fs17.fstatSync(fd).size;
6537
6969
  const len = Math.min(size, maxBytes);
6538
6970
  const buf = Buffer.alloc(len);
6539
- fs16.readSync(fd, buf, 0, len, size - len);
6971
+ fs17.readSync(fd, buf, 0, len, size - len);
6540
6972
  const lines = buf.toString("utf8").split("\n");
6541
6973
  for (let i = lines.length - 1; i >= 0; i--) {
6542
6974
  let m;
@@ -6551,7 +6983,7 @@ function lastReply(transcriptPath, maxBytes = 256e3) {
6551
6983
  if (text2.trim()) return redact2(text2.trim()).slice(0, 1500);
6552
6984
  }
6553
6985
  } finally {
6554
- fs16.closeSync(fd);
6986
+ fs17.closeSync(fd);
6555
6987
  }
6556
6988
  } catch {
6557
6989
  }
@@ -6563,9 +6995,13 @@ function promptContext(session) {
6563
6995
  const reply = lastReply(session.transcriptPath);
6564
6996
  return { ...session.task ? { first: session.task.slice(0, 1e3) } : {}, recent, ...reply ? { reply } : {} };
6565
6997
  }
6998
+ function withReply(session) {
6999
+ const reply = lastReply(session.transcriptPath);
7000
+ return reply ? { reply } : {};
7001
+ }
6566
7002
  async function routerIndex(store, v2, source) {
6567
- const file = path11.join(dir(v2), `index-${createHash5("sha256").update(source).digest("hex").slice(0, 12)}.json`);
6568
- const cached = readJson2(file);
7003
+ const file2 = path12.join(dir(v2), `index-${createHash5("sha256").update(source).digest("hex").slice(0, 12)}.json`);
7004
+ const cached = readJson2(file2);
6569
7005
  if (cached && Date.now() - Date.parse(cached.fetchedAt) < INDEX_TTL_MS) return cached;
6570
7006
  try {
6571
7007
  const res = await v2api(
@@ -6577,7 +7013,7 @@ async function routerIndex(store, v2, source) {
6577
7013
  );
6578
7014
  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() };
6579
7015
  if (!next.system) throw new Error("the server sent no index");
6580
- writeJsonAtomic(file, next);
7016
+ writeJsonAtomic(file2, next);
6581
7017
  return next;
6582
7018
  } catch (err) {
6583
7019
  if (cached) return cached;
@@ -6640,15 +7076,16 @@ async function routeJob(store, sessionId, seq) {
6640
7076
  if (!job || job.seq !== seq || job.cancelled) return null;
6641
7077
  const started = Date.parse(job.at) || Date.now();
6642
7078
  const model = config.recall.routerModel || process.env.BUNSHIN_ROUTER_MODEL || ROUTER_MODEL;
6643
- const { picks, indexHash } = await askRouter(store, v2, sessionId, model);
7079
+ const { picks, indexHash } = await askRouter(store, v2, sessionId, model, job.kind);
7080
+ if (job.kind === "checkpoint") delete picks.serve;
6644
7081
  const answer = { seq, at: (/* @__PURE__ */ new Date()).toISOString(), ms: Date.now() - started, ...picks };
6645
7082
  writeJsonAtomic(answerFile(v2, sessionId, seq), answer);
6646
7083
  const dense = (readJob(v2, sessionId) ?? job).dense;
6647
- 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 });
7084
+ 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 });
6648
7085
  await recordStats(v2, sessionId, answer, model, indexHash);
6649
7086
  return answer;
6650
7087
  }
6651
- async function askRouter(store, v2, sessionId, model) {
7088
+ async function askRouter(store, v2, sessionId, model, kind) {
6652
7089
  const config = store.config();
6653
7090
  let indexHash;
6654
7091
  try {
@@ -6656,14 +7093,16 @@ async function askRouter(store, v2, sessionId, model) {
6656
7093
  if (!session?.lastPrompt) return { picks: { error: "no prompt in the session file" } };
6657
7094
  if (!canCall(config)) return { picks: { error: "offline: the router's index comes from the server" } };
6658
7095
  const index = await routerIndex(store, v2, session.source ?? "");
7096
+ if (!/^[\w-]{1,64}$/.test(index.hash)) return { picks: { error: "the router index came back with a malformed hash" } };
6659
7097
  indexHash = index.hash;
6660
- const systemFile = path11.join(dir(v2), `system-${index.hash}.txt`);
6661
- if (!fs16.existsSync(systemFile)) fs16.writeFileSync(systemFile, index.system);
6662
- const cwd = path11.join(dir(v2), "cwd");
6663
- fs16.mkdirSync(cwd, { recursive: true });
7098
+ const systemFile = path12.join(dir(v2), `system-${index.hash}.txt`);
7099
+ if (!fs17.existsSync(systemFile)) fs17.writeFileSync(systemFile, index.system);
7100
+ const cwd = path12.join(dir(v2), "cwd");
7101
+ fs17.mkdirSync(cwd, { recursive: true });
6664
7102
  const inContext2 = session.inContext ?? [...session.loaded, ...session.pushed];
6665
7103
  const titles = new Map((v2.readBundle()?.sections ?? []).map((s) => [s.id, s.skill?.name ?? s.title]));
6666
- const message = routerMessage(session.lastPrompt, promptContext(session), inContext2.map((id) => titles.get(id)).filter((t) => !!t));
7104
+ const inTitles = inContext2.map((id) => titles.get(id)).filter((t) => !!t);
7105
+ 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);
6667
7106
  const res = await askClaude(systemFile, message, model, cwd);
6668
7107
  const u = res.usage ?? {};
6669
7108
  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 } : {} };
@@ -6698,7 +7137,7 @@ async function recordStats(v2, sessionId, a, model, indexHash) {
6698
7137
  add(stats.sessions[sessionId] ??= emptyTally());
6699
7138
  stats.model = model;
6700
7139
  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 } : {} };
6701
- writeJsonAtomic(path11.join(dir(v2), "stats.json"), stats);
7140
+ writeJsonAtomic(path12.join(dir(v2), "stats.json"), stats);
6702
7141
  } catch {
6703
7142
  } finally {
6704
7143
  release?.();
@@ -6706,10 +7145,10 @@ async function recordStats(v2, sessionId, a, model, indexHash) {
6706
7145
  }
6707
7146
  function sweepRouter(v2, now = Date.now()) {
6708
7147
  try {
6709
- for (const f of fs16.readdirSync(dir(v2))) {
7148
+ for (const f of fs17.readdirSync(dir(v2))) {
6710
7149
  if (!/\.(job|answer)\.json$/.test(f)) continue;
6711
- const p = path11.join(dir(v2), f);
6712
- if (now - fs16.statSync(p).mtimeMs > 864e5) fs16.rmSync(p, { force: true });
7150
+ const p = path12.join(dir(v2), f);
7151
+ if (now - fs17.statSync(p).mtimeMs > 864e5) fs17.rmSync(p, { force: true });
6713
7152
  }
6714
7153
  } catch {
6715
7154
  }
@@ -6727,16 +7166,16 @@ var init_route = __esm({
6727
7166
  ROUTER_MODEL = "claude-haiku-5-5";
6728
7167
  INDEX_TTL_MS = 10 * 6e4;
6729
7168
  CLAUDE_TIMEOUT_MS = 6e4;
6730
- dir = (v2) => path11.join(v2.dir, "router");
7169
+ dir = (v2) => path12.join(v2.dir, "router");
6731
7170
  safe2 = (id) => id.replace(/[^\w.-]/g, "_");
6732
- jobFile = (v2, session) => path11.join(dir(v2), `${safe2(session)}.job.json`);
6733
- answerFile = (v2, session, seq) => path11.join(dir(v2), `${safe2(session)}.${seq}.answer.json`);
7171
+ jobFile = (v2, session) => path12.join(dir(v2), `${safe2(session)}.job.json`);
7172
+ answerFile = (v2, session, seq) => path12.join(dir(v2), `${safe2(session)}.${seq}.answer.json`);
6734
7173
  readJob = (v2, session) => readJson2(jobFile(v2, session));
6735
7174
  writeJob = (v2, session, job) => writeJsonAtomic(jobFile(v2, session), job);
6736
7175
  readAnswer = (v2, session, seq) => readJson2(answerFile(v2, session, seq));
6737
7176
  emptyTally = () => ({ calls: 0, errors: 0, costUsd: 0, input: 0, cacheRead: 0, cacheWrite: 0, output: 0, msTotal: 0 });
6738
7177
  localDay = (d = /* @__PURE__ */ new Date()) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
6739
- readStats = (v2) => readJson2(path11.join(dir(v2), "stats.json"));
7178
+ readStats = (v2) => readJson2(path12.join(dir(v2), "stats.json"));
6740
7179
  }
6741
7180
  });
6742
7181
 
@@ -6752,51 +7191,51 @@ __export(uicmd_exports, {
6752
7191
  modSource: () => modSource
6753
7192
  });
6754
7193
  import { spawnSync } from "node:child_process";
6755
- import fs17 from "node:fs";
7194
+ import fs18 from "node:fs";
6756
7195
  import os3 from "node:os";
6757
- import path12 from "node:path";
7196
+ import path13 from "node:path";
6758
7197
  import { fileURLToPath } from "node:url";
6759
7198
  function modHome(home = process.env.BUNSHIN_DEPLOY_HOME || os3.homedir()) {
6760
- return path12.join(home, ".bunshin", "claude-code-ui");
7199
+ return path13.join(home, ".bunshin", "claude-code-ui");
6761
7200
  }
6762
7201
  function modSource() {
6763
- const here = path12.dirname(fileURLToPath(import.meta.url));
6764
- for (const dir2 of [path12.join(here, "claude-code-ui"), path12.join(here, "..", "claude-code-ui"), path12.resolve(here, "../../../../adapters/claude-code-ui")]) {
6765
- if (fs17.existsSync(path12.join(dir2, ".claude-plugin", "plugin.json"))) return dir2;
7202
+ const here = path13.dirname(fileURLToPath(import.meta.url));
7203
+ for (const dir2 of [path13.join(here, "claude-code-ui"), path13.join(here, "..", "claude-code-ui"), path13.resolve(here, "../../../../adapters/claude-code-ui")]) {
7204
+ if (fs18.existsSync(path13.join(dir2, ".claude-plugin", "plugin.json"))) return dir2;
6766
7205
  }
6767
7206
  return null;
6768
7207
  }
6769
7208
  function installedModVersion(home) {
6770
7209
  try {
6771
- return JSON.parse(fs17.readFileSync(path12.join(modHome(home), MOD_PLUGIN, ".claude-plugin", "plugin.json"), "utf8")).version ?? null;
7210
+ return fs18.readFileSync(path13.join(modHome(home), INSTALLED_MARKER), "utf8").trim() || null;
6772
7211
  } catch {
6773
7212
  return null;
6774
7213
  }
6775
7214
  }
6776
7215
  function copyDir(from, to) {
6777
- fs17.mkdirSync(to, { recursive: true });
6778
- for (const e of fs17.readdirSync(from, { withFileTypes: true })) {
7216
+ fs18.mkdirSync(to, { recursive: true });
7217
+ for (const e of fs18.readdirSync(from, { withFileTypes: true })) {
6779
7218
  if (e.name === "types" && from.endsWith(".claude-plugin")) continue;
6780
7219
  if (e.name === "node_modules") continue;
6781
- const a = path12.join(from, e.name);
6782
- const b = path12.join(to, e.name);
7220
+ const a = path13.join(from, e.name);
7221
+ const b = path13.join(to, e.name);
6783
7222
  if (e.isDirectory()) copyDir(a, b);
6784
- else fs17.copyFileSync(a, b);
7223
+ else fs18.copyFileSync(a, b);
6785
7224
  }
6786
7225
  }
6787
7226
  function installMod(version2, opts = {}) {
6788
7227
  const src = modSource();
6789
7228
  if (!src) throw new Error("the bunshin-ui mod is not in this build of the CLI");
6790
7229
  const home = modHome(opts.home);
6791
- const dir2 = path12.join(home, MOD_PLUGIN);
6792
- fs17.rmSync(dir2, { recursive: true, force: true });
7230
+ const dir2 = path13.join(home, MOD_PLUGIN);
7231
+ fs18.rmSync(dir2, { recursive: true, force: true });
6793
7232
  copyDir(src, dir2);
6794
- const manifest = path12.join(dir2, ".claude-plugin", "plugin.json");
6795
- const m = JSON.parse(fs17.readFileSync(manifest, "utf8"));
6796
- fs17.writeFileSync(manifest, JSON.stringify({ ...m, version: version2 }, null, 2) + "\n");
6797
- fs17.mkdirSync(path12.join(home, ".claude-plugin"), { recursive: true });
6798
- fs17.writeFileSync(
6799
- path12.join(home, ".claude-plugin", "marketplace.json"),
7233
+ const manifest = path13.join(dir2, ".claude-plugin", "plugin.json");
7234
+ const m = JSON.parse(fs18.readFileSync(manifest, "utf8"));
7235
+ fs18.writeFileSync(manifest, JSON.stringify({ ...m, version: version2 }, null, 2) + "\n");
7236
+ fs18.mkdirSync(path13.join(home, ".claude-plugin"), { recursive: true });
7237
+ fs18.writeFileSync(
7238
+ path13.join(home, ".claude-plugin", "marketplace.json"),
6800
7239
  JSON.stringify({ name: MOD_MARKETPLACE, owner: { name: "Bunshin" }, plugins: [{ name: MOD_PLUGIN, source: `./${MOD_PLUGIN}`, description: m.description }] }, null, 2) + "\n"
6801
7240
  );
6802
7241
  const run2 = opts.run ?? spawnSync;
@@ -6809,7 +7248,10 @@ function installMod(version2, opts = {}) {
6809
7248
  return r.status === 0;
6810
7249
  };
6811
7250
  if (!step(["plugin", "marketplace", "add", home])) step(["plugin", "marketplace", "update", MOD_MARKETPLACE]);
6812
- if (!step(["plugin", "install", `${MOD_PLUGIN}@${MOD_MARKETPLACE}`, "--scope", "user"])) step(["plugin", "update", `${MOD_PLUGIN}@${MOD_MARKETPLACE}`]);
7251
+ const ok = step(["plugin", "install", `${MOD_PLUGIN}@${MOD_MARKETPLACE}`, "--scope", "user"]) || step(["plugin", "update", `${MOD_PLUGIN}@${MOD_MARKETPLACE}`]);
7252
+ const marker = path13.join(home, INSTALLED_MARKER);
7253
+ if (ok) fs18.writeFileSync(marker, version2 + "\n");
7254
+ else fs18.rmSync(marker, { force: true });
6813
7255
  return { dir: dir2, version: version2, steps };
6814
7256
  }
6815
7257
  async function cmdUi(store, args, out, err, version2) {
@@ -6831,7 +7273,7 @@ async function cmdUi(store, args, out, err, version2) {
6831
7273
  `);
6832
7274
  for (const s of res.steps) out(` ${s.ok ? "\u2713" : "\xB7"} ${s.command}${s.ok ? "" : `: ${s.output.split("\n")[0] ?? ""}`}
6833
7275
  `);
6834
- 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");
7276
+ 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");
6835
7277
  }
6836
7278
  return installed || !failed.length ? 0 : 1;
6837
7279
  }
@@ -6889,7 +7331,7 @@ Claude Code mod: ${v ? `bunshin-ui ${v} (${modHome()})` : "not installed (bunshi
6889
7331
  show();
6890
7332
  return 0;
6891
7333
  }
6892
- var str2, bool, MOD_PLUGIN, MOD_MARKETPLACE, HARNESSES, MODES;
7334
+ var str2, bool, MOD_PLUGIN, MOD_MARKETPLACE, HARNESSES, MODES, INSTALLED_MARKER;
6893
7335
  var init_uicmd = __esm({
6894
7336
  "src/v2/uicmd.ts"() {
6895
7337
  "use strict";
@@ -6901,6 +7343,7 @@ var init_uicmd = __esm({
6901
7343
  MOD_MARKETPLACE = "bunshin-local";
6902
7344
  HARNESSES = ["claude-code", "codex", "pi", "other"];
6903
7345
  MODES = ["auto", "mod", "widget", "lines", "off"];
7346
+ INSTALLED_MARKER = ".installed-version";
6904
7347
  }
6905
7348
  });
6906
7349
 
@@ -6912,19 +7355,19 @@ __export(update_exports, {
6912
7355
  updateCheckDue: () => updateCheckDue,
6913
7356
  updateNotice: () => updateNotice
6914
7357
  });
6915
- import fs18 from "node:fs";
6916
- import path13 from "node:path";
7358
+ import fs19 from "node:fs";
7359
+ import path14 from "node:path";
6917
7360
  function readState2() {
6918
7361
  try {
6919
- return JSON.parse(fs18.readFileSync(stateFile(), "utf8"));
7362
+ return JSON.parse(fs19.readFileSync(stateFile(), "utf8"));
6920
7363
  } catch {
6921
7364
  return {};
6922
7365
  }
6923
7366
  }
6924
7367
  function writeState(s) {
6925
7368
  try {
6926
- fs18.mkdirSync(path13.dirname(stateFile()), { recursive: true });
6927
- fs18.writeFileSync(stateFile(), JSON.stringify(s, null, 2) + "\n");
7369
+ fs19.mkdirSync(path14.dirname(stateFile()), { recursive: true });
7370
+ fs19.writeFileSync(stateFile(), JSON.stringify(s, null, 2) + "\n");
6928
7371
  } catch {
6929
7372
  }
6930
7373
  }
@@ -6974,14 +7417,14 @@ var init_update = __esm({
6974
7417
  PKG = "@bunshin-cc/bunshin";
6975
7418
  LATEST_URL = `https://registry.npmjs.org/${PKG.replace("/", "%2f")}/latest`;
6976
7419
  DAY = 864e5;
6977
- stateFile = () => path13.join(homeDir(), ".bunshin", "update.json");
7420
+ stateFile = () => path14.join(homeDir(), ".bunshin", "update.json");
6978
7421
  disabled = () => process.env.BUNSHIN_NO_UPDATE_CHECK === "1" || process.env.BUNSHIN_NO_UPDATE_CHECK === "true";
6979
7422
  }
6980
7423
  });
6981
7424
 
6982
7425
  // src/v2/hooks.ts
6983
- import fs19 from "node:fs";
6984
- import path14 from "node:path";
7426
+ import fs20 from "node:fs";
7427
+ import path15 from "node:path";
6985
7428
  function inContext(s) {
6986
7429
  return s.inContext ?? [...s.loaded, ...s.pushed];
6987
7430
  }
@@ -7048,10 +7491,13 @@ async function keepModCurrent(ctx, config) {
7048
7491
  const { version: version2 } = await Promise.resolve().then(() => (init_cli(), cli_exports));
7049
7492
  const current = version2();
7050
7493
  if (!modSource2() || installedModVersion2() === current) return;
7051
- const marker = path14.join(modHome2(), `.attempted-${current}`);
7052
- if (fs19.existsSync(marker)) return;
7053
- fs19.mkdirSync(modHome2(), { recursive: true });
7054
- fs19.writeFileSync(marker, (/* @__PURE__ */ new Date()).toISOString());
7494
+ const marker = path15.join(modHome2(), `.attempted-${current}`);
7495
+ try {
7496
+ if (Date.now() - fs20.statSync(marker).mtimeMs < 24 * 36e5) return;
7497
+ } catch {
7498
+ }
7499
+ fs20.mkdirSync(modHome2(), { recursive: true });
7500
+ fs20.writeFileSync(marker, (/* @__PURE__ */ new Date()).toISOString());
7055
7501
  ctx.detach(["--root", ctx.store.root, "ui", "install", "--quiet"], { cwd: ctx.cwd });
7056
7502
  } catch {
7057
7503
  }
@@ -7178,7 +7624,7 @@ function liveUpdate(v2, ctx, session) {
7178
7624
  }
7179
7625
  function skillHint(sec, others) {
7180
7626
  const also = others.length ? ` Also possibly relevant: ${others.map((t) => `"${t}"`).join(", ")}.` : "";
7181
- 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}`;
7627
+ 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}`;
7182
7628
  }
7183
7629
  async function remoteAuto(ctx, prompt, exclude, source, context) {
7184
7630
  const config = ctx.store.config();
@@ -7203,11 +7649,18 @@ function invokedSkill(prompt, sections) {
7203
7649
  const name = m[1].split(":").pop().toLowerCase();
7204
7650
  return sections.find((s) => s.skill && s.skill.name.toLowerCase() === name);
7205
7651
  }
7206
- function startRoute(v2, ctx, sessionId, now) {
7652
+ function cardIndex(sections, spine, harness) {
7653
+ if (!spine.skill) return "";
7654
+ return renderCardIndex(spine, cardsOf(spine, sections), { mcp: harness === "claude-code" });
7655
+ }
7656
+ function startRoute(v2, ctx, sessionId, now, kind) {
7207
7657
  const prev = readJob(v2, sessionId);
7208
7658
  if (prev && !prev.delivered && !prev.cancelled) v2.log("v2-router-undelivered", { session: sessionId, seq: prev.seq, answered: !!readAnswer(v2, sessionId, prev.seq) });
7209
- const job = { seq: (prev?.seq ?? 0) + 1, at: now };
7659
+ const job = { seq: (prev?.seq ?? 0) + 1, at: now, ...kind ? { kind } : {} };
7210
7660
  writeJob(v2, sessionId, job);
7661
+ v2.updateSession(sessionId, ctx.cwd, (s) => {
7662
+ s.routeCalls = s.toolCalls ?? 0;
7663
+ });
7211
7664
  ctx.detach(["--root", ctx.store.root, "route", "--session", sessionId, "--seq", String(job.seq), "--quiet"], { cwd: ctx.cwd });
7212
7665
  return job;
7213
7666
  }
@@ -7232,7 +7685,7 @@ async function onPrompt(ctx) {
7232
7685
  const config = ctx.store.config();
7233
7686
  const view = localView(v2, config, ctx.cwd, session.source !== void 0 ? { source: session.source } : {});
7234
7687
  const injected = inContext(session);
7235
- const job = config.recall.router === "claude-cli" && canCall(config) ? startRoute(v2, ctx, session.sessionId, now) : void 0;
7688
+ const job = recallRouter(config) === "claude-cli" && canCall(config) ? startRoute(v2, ctx, session.sessionId, now) : void 0;
7236
7689
  const named = invokedSkill(prompt, view.sections);
7237
7690
  if (named && job) writeJob(v2, session.sessionId, { ...job, cancelled: true });
7238
7691
  if (named) {
@@ -7249,7 +7702,8 @@ async function onPrompt(ctx) {
7249
7702
  addServed(f, { id: named.id, title: named.title, kind: named.kind, skill: named.skill.name, how: "load", why });
7250
7703
  addEvent(f, "served", `loaded ${label({ skill: named.skill.name, title: named.title, kind: named.kind })} \u2014 ${why}`);
7251
7704
  });
7252
- return withLive(deployed || !fresh2 ? {} : additional("UserPromptSubmit", renderSection(named, why, { deployed: false })));
7705
+ const cards = fresh2 ? cardIndex(view.sections, named, config.harness) : "";
7706
+ return withLive(additional("UserPromptSubmit", [deployed || !fresh2 ? "" : renderSection(named, why, { deployed: false }), cards].filter(Boolean).join("\n\n")));
7253
7707
  }
7254
7708
  const res = auto(view.sections, view.reader, prompt, { exclude: injected });
7255
7709
  const recent = session.recentPrompts ?? [];
@@ -7310,7 +7764,7 @@ async function onPrompt(ctx) {
7310
7764
  addServed(f, { id: sec.id, title: sec.title, kind: sec.kind, ...sec.skill ? { skill: sec.skill.name } : {}, how: "auto", why });
7311
7765
  addEvent(f, "served", `served ${label({ ...sec.skill ? { skill: sec.skill.name } : {}, title: sec.title, kind: sec.kind })} \u2014 ${why}`);
7312
7766
  });
7313
- return withLessons(renderSection(sec, "your prompt matches it", { ...res.anchor ? { anchor: res.anchor } : {}, deployed: !!sec.skill && deployEnabled(config, view.ctx) }));
7767
+ 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"));
7314
7768
  }
7315
7769
  const fresh = res.hint.filter((h) => !session.hinted?.includes(h.id) && !rules.some((r) => r.id === h.id)).slice(0, 3);
7316
7770
  if (!fresh.length) return withLessons("");
@@ -7339,15 +7793,20 @@ function toolPaths(input) {
7339
7793
  }
7340
7794
  return [...new Set(out)];
7341
7795
  }
7342
- async function routedText(v2, ctx, session) {
7796
+ async function routedText(v2, ctx, session, callText) {
7343
7797
  const config = ctx.store.config();
7344
- if (config.recall.router !== "claude-cli") return "";
7798
+ if (recallRouter(config) !== "claude-cli") return "";
7345
7799
  const job = readJob(v2, session.sessionId);
7346
7800
  if (!job || job.delivered || job.cancelled) return "";
7347
7801
  const answer = readAnswer(v2, session.sessionId, job.seq);
7348
7802
  if (!answer) return "";
7803
+ const checkpoint = job.kind === "checkpoint";
7349
7804
  const fallback = !!answer.error;
7350
7805
  writeJob(v2, session.sessionId, { ...job, delivered: { at: (/* @__PURE__ */ new Date()).toISOString(), ...ctx.input.tool_name ? { tool: ctx.input.tool_name } : {}, ...fallback ? { fallback } : {} } });
7806
+ if (checkpoint && fallback) {
7807
+ 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 });
7808
+ return "";
7809
+ }
7351
7810
  const seen = new Set(inContext(session));
7352
7811
  const view = localView(v2, config, ctx.cwd, session.source !== void 0 ? { source: session.source } : {});
7353
7812
  const find = async (id) => {
@@ -7359,48 +7818,98 @@ async function routedText(v2, ctx, session) {
7359
7818
  return void 0;
7360
7819
  }
7361
7820
  };
7362
- const serveId = fallback ? job.dense?.serve : answer.serve;
7821
+ const serveId = checkpoint ? void 0 : fallback ? job.dense?.serve : answer.serve;
7363
7822
  const fresh = (ids2) => [...new Set(ids2.filter((id) => !!id && !seen.has(id)))];
7364
7823
  const [doc] = await Promise.all(fresh([serveId]).map(find));
7365
7824
  const rules = (await Promise.all(fresh(fallback ? [] : answer.rules ?? []).filter((id) => id !== doc?.id).map(find))).filter((s) => !!s);
7366
- const hints = fresh(fallback ? job.dense?.hint ?? [] : answer.hint ?? []).filter((id) => id !== doc?.id && !session.hinted?.includes(id));
7825
+ const hints = checkpoint ? [] : fresh(fallback ? job.dense?.hint ?? [] : answer.hint ?? []).filter((id) => id !== doc?.id && !session.hinted?.includes(id));
7367
7826
  const hintTitles = hints.map((id) => view.sections.find((s) => s.id === id)?.title).filter((t) => !!t);
7368
- 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 } : {} });
7827
+ 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 } : {} });
7369
7828
  const ids = [...doc ? [doc.id] : [], ...rules.map((r) => r.id)];
7370
7829
  if (!ids.length && !hintTitles.length) return "";
7830
+ const judged = routerFires(rules, session.toolCalls ?? 0, callText);
7371
7831
  v2.updateSession(session.sessionId, ctx.cwd, (s) => {
7372
7832
  addUnique(s.served, ...ids, ...hints);
7373
7833
  addUnique(s.loaded, ...ids);
7374
7834
  markInContext(s, ...ids);
7375
7835
  s.hinted = s.hinted ?? [];
7376
7836
  addUnique(s.hinted, ...hints);
7837
+ if (judged.fires.length) s.fires = [...s.fires ?? [], ...judged.fires].slice(-40);
7377
7838
  });
7839
+ recordTriggers(v2, judged.updates);
7378
7840
  const why = fallback ? "your request matches it" : "the router picked it for the user's latest request";
7841
+ const ruleWhy = checkpoint ? "the router picked it for the step your work is at" : "a lesson learned before applies to this work";
7379
7842
  updateFeed(v2, session.sessionId, (f) => {
7380
- 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" });
7843
+ 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" });
7381
7844
  if (doc) addServed(f, { id: doc.id, title: doc.title, kind: doc.kind, ...doc.skill ? { skill: doc.skill.name } : {}, how: "auto", why });
7382
7845
  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"}`);
7383
- if (rules.length) addEvent(f, "served", `lessons: ${rules.map((r) => r.title).join(", ")}`);
7846
+ if (rules.length) addEvent(f, "served", `${checkpoint ? "at this step" : "lessons"}: ${rules.map((r) => r.title).join(", ")}`);
7384
7847
  });
7385
7848
  return [
7386
7849
  doc ? renderSection(doc, why, { deployed: !!doc.skill && deployEnabled(config, view.ctx) }) : "",
7387
- ...rules.map((r) => renderSection(r, "a lesson learned before applies to this work", { deployed: false })),
7850
+ doc ? cardIndex(view.sections, doc, config.harness) : "",
7851
+ ...rules.map((r) => renderSection(r, ruleWhy, { deployed: false })),
7388
7852
  hintTitles.length ? hintLine(hintTitles, config.harness) : ""
7389
7853
  ].filter(Boolean).join("\n\n");
7390
7854
  }
7855
+ function triggerText(v2, ctx, session, tool, callText) {
7856
+ const config = ctx.store.config();
7857
+ if (config.recall.atomTriggers === false || !tool || !callText) return "";
7858
+ const view = localView(v2, config, ctx.cwd, { index: false, ...session.source !== void 0 ? { source: session.source } : {} });
7859
+ const now = v2.readSession(session.sessionId) ?? session;
7860
+ 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);
7861
+ if (!t.atoms.length) return "";
7862
+ const ids = t.atoms.map((a) => a.id);
7863
+ v2.updateSession(session.sessionId, ctx.cwd, (s) => {
7864
+ addUnique(s.pushed, ...ids);
7865
+ addUnique(s.loaded, ...ids);
7866
+ addUnique(s.served, ...ids);
7867
+ markInContext(s, ...ids);
7868
+ if (t.fires.length) s.fires = [...s.fires ?? [], ...t.fires].slice(-40);
7869
+ });
7870
+ recordTriggers(v2, t.updates);
7871
+ v2.log("v2-atom-trigger", { session: session.sessionId, tool, atoms: t.atoms.map((a, i) => `${a.id} ${t.why[i]}`) });
7872
+ updateFeed(v2, session.sessionId, (f) => {
7873
+ t.atoms.forEach((a, i) => addServed(f, { id: a.id, title: a.title, kind: a.kind, how: "push", why: t.why[i] }));
7874
+ addEvent(f, "push", `at this step: ${t.atoms.map((a) => a.title).join(", ")}`);
7875
+ });
7876
+ return t.text;
7877
+ }
7878
+ function maybeCheckpoint(v2, ctx, session) {
7879
+ const config = ctx.store.config();
7880
+ if (recallRouter(config) !== "claude-cli" || !canCall(config)) return;
7881
+ const every = config.recall.checkpointEvery ?? 20;
7882
+ if (!(every > 0) || (session.toolCalls ?? 0) - (session.routeCalls ?? 0) < every) return;
7883
+ const job = readJob(v2, session.sessionId);
7884
+ if (job && !job.delivered && !job.cancelled && Date.now() - Date.parse(job.at) < 12e4) return;
7885
+ startRoute(v2, ctx, session.sessionId, (/* @__PURE__ */ new Date()).toISOString(), "checkpoint");
7886
+ }
7391
7887
  async function onPreToolUse(ctx) {
7392
7888
  const v2 = new V2Store(ctx.store);
7889
+ const tool = ctx.input.tool_name ?? "";
7890
+ const callText = toolCallText(ctx.input.tool_input);
7891
+ let judged = [];
7393
7892
  const session = touch(v2, ctx, (s) => {
7394
7893
  s.lastActivityAt = (/* @__PURE__ */ new Date()).toISOString();
7894
+ s.toolCalls = (s.toolCalls ?? 0) + 1;
7895
+ if (tool) s.actions = [...s.actions ?? [], actionLine(tool, callText)].slice(-MAX_ACTIONS);
7896
+ judged = judgeFires(s, callText, true);
7395
7897
  });
7898
+ recordTriggers(v2, judged);
7396
7899
  const live = liveUpdate(v2, ctx, session);
7397
7900
  let routed = "";
7398
7901
  try {
7399
- routed = await routedText(v2, ctx, session);
7902
+ routed = await routedText(v2, ctx, session, callText);
7903
+ } catch {
7904
+ }
7905
+ let triggered = "";
7906
+ try {
7907
+ triggered = triggerText(v2, ctx, session, tool, callText);
7908
+ maybeCheckpoint(v2, ctx, session);
7400
7909
  } catch {
7401
7910
  }
7402
7911
  const withLive = (out) => {
7403
- const text3 = [live, routed, out.hookSpecificOutput?.additionalContext ?? ""].filter(Boolean).join("\n\n");
7912
+ const text3 = [live, routed, triggered, out.hookSpecificOutput?.additionalContext ?? ""].filter(Boolean).join("\n\n");
7404
7913
  return text3 === (out.hookSpecificOutput?.additionalContext ?? "") ? out : additional("PreToolUse", text3);
7405
7914
  };
7406
7915
  const raw = toolPaths(ctx.input.tool_input);
@@ -7438,6 +7947,15 @@ function onStop(ctx) {
7438
7947
  s.lastActivityAt = now.toISOString();
7439
7948
  });
7440
7949
  const config = ctx.store.config();
7950
+ if (session.fires?.length) {
7951
+ try {
7952
+ const reply = lastReply(ctx.input.transcript_path ?? session.transcriptPath);
7953
+ let judged = [];
7954
+ if (reply) v2.updateSession(session.sessionId, ctx.cwd, (s) => void (judged = judgeFires(s, reply, false)));
7955
+ recordTriggers(v2, judged);
7956
+ } catch {
7957
+ }
7958
+ }
7441
7959
  if (ctx.input.stop_hook_active) return {};
7442
7960
  const scan = scanTranscript(ctx.input.transcript_path ?? session.transcriptPath);
7443
7961
  if (canCall(config) && checkpointDue(session, scan, now)) {
@@ -7651,9 +8169,11 @@ var init_hooks = __esm({
7651
8169
  "src/v2/hooks.ts"() {
7652
8170
  "use strict";
7653
8171
  init_v22();
8172
+ init_store();
7654
8173
  init_redact2();
7655
8174
  init_version();
7656
8175
  init_api();
8176
+ init_atoms2();
7657
8177
  init_deploy();
7658
8178
  init_live();
7659
8179
  init_reflect3();
@@ -7678,8 +8198,8 @@ var init_hooks = __esm({
7678
8198
  });
7679
8199
 
7680
8200
  // src/hooks.ts
7681
- import fs20 from "node:fs";
7682
- import path15 from "node:path";
8201
+ import fs21 from "node:fs";
8202
+ import path16 from "node:path";
7683
8203
  function normalizeEvent(raw) {
7684
8204
  return EVENT_NAMES[String(raw ?? "").trim().toLowerCase().replace(/_/g, "-")] ?? null;
7685
8205
  }
@@ -7747,17 +8267,17 @@ async function handleHook(rawEvent, input, opts = {}) {
7747
8267
  }
7748
8268
  function deferToProject(cwd, env = process.env) {
7749
8269
  if (env.BUNSHIN_HOOK_SCOPE !== "user") return false;
7750
- let dir2 = path15.resolve(cwd);
8270
+ let dir2 = path16.resolve(cwd);
7751
8271
  for (let i = 0; i < 40; i++) {
7752
8272
  for (const f of [".claude/settings.local.json", ".claude/settings.json", ".codex/hooks.json"]) {
7753
8273
  try {
7754
- const text2 = fs20.readFileSync(path15.join(dir2, f), "utf8");
8274
+ const text2 = fs21.readFileSync(path16.join(dir2, f), "utf8");
7755
8275
  if (/\bbunshin\b[^"]*\bhook\b/.test(text2) && !/BUNSHIN_HOOK_SCOPE=user/.test(text2)) return true;
7756
8276
  } catch {
7757
8277
  }
7758
8278
  }
7759
- if (fs20.existsSync(path15.join(dir2, ".git"))) return false;
7760
- const up = path15.dirname(dir2);
8279
+ if (fs21.existsSync(path16.join(dir2, ".git"))) return false;
8280
+ const up = path16.dirname(dir2);
7761
8281
  if (up === dir2) return false;
7762
8282
  dir2 = up;
7763
8283
  }
@@ -7805,11 +8325,11 @@ var init_hooks2 = __esm({
7805
8325
  });
7806
8326
 
7807
8327
  // src/project-hooks.ts
7808
- import fs21 from "node:fs";
7809
- import path16 from "node:path";
8328
+ import fs22 from "node:fs";
8329
+ import path17 from "node:path";
7810
8330
  import { execFileSync as execFileSync4 } from "node:child_process";
7811
8331
  function codexProjectHooks(cwd) {
7812
- const legacyFile = path16.join(cwd, ".codex", "hooks.json");
8332
+ const legacyFile = path17.join(cwd, ".codex", "hooks.json");
7813
8333
  const git5 = (...args) => execFileSync4("git", ["-C", cwd, "rev-parse", ...args], {
7814
8334
  encoding: "utf8",
7815
8335
  stdio: ["ignore", "pipe", "ignore"],
@@ -7823,15 +8343,15 @@ function codexProjectHooks(cwd) {
7823
8343
  } catch {
7824
8344
  return { file: legacyFile, shared: false, legacyFile };
7825
8345
  }
7826
- const linked = fs21.realpathSync(common) !== fs21.realpathSync(directory);
8346
+ const linked = fs22.realpathSync(common) !== fs22.realpathSync(directory);
7827
8347
  if (linked) {
7828
- if (path16.basename(common) !== ".git" || !fs21.statSync(common).isDirectory()) {
8348
+ if (path17.basename(common) !== ".git" || !fs22.statSync(common).isDirectory()) {
7829
8349
  throw new Error("Codex hooks in a worktree of a bare repository are not supported yet. Use a full checkout for Bunshin setup.");
7830
8350
  }
7831
- root = path16.dirname(common);
8351
+ root = path17.dirname(common);
7832
8352
  }
7833
- const file = fs21.realpathSync(root) === fs21.realpathSync(cwd) ? legacyFile : path16.join(root, ".codex", "hooks.json");
7834
- return { file, shared: linked, legacyFile };
8353
+ const file2 = fs22.realpathSync(root) === fs22.realpathSync(cwd) ? legacyFile : path17.join(root, ".codex", "hooks.json");
8354
+ return { file: file2, shared: linked, legacyFile };
7835
8355
  }
7836
8356
  var init_project_hooks = __esm({
7837
8357
  "src/project-hooks.ts"() {
@@ -7864,8 +8384,8 @@ __export(init_exports, {
7864
8384
  runInit: () => runInit
7865
8385
  });
7866
8386
  import { execFileSync as execFileSync5 } from "node:child_process";
7867
- import fs22 from "node:fs";
7868
- import path17 from "node:path";
8387
+ import fs23 from "node:fs";
8388
+ import path18 from "node:path";
7869
8389
  import { fileURLToPath as fileURLToPath2, pathToFileURL } from "node:url";
7870
8390
  function isBunshinEntry(entry) {
7871
8391
  return entry?._bunshin === true || typeof entry?.command === "string" && /\bbunshin\b.*\bhook\b/.test(entry.command);
@@ -7911,17 +8431,17 @@ function countBunshinHooks(settings) {
7911
8431
  );
7912
8432
  }
7913
8433
  function claudeSettingsPath() {
7914
- return path17.join(homeDir(), ".claude", "settings.json");
8434
+ return path18.join(homeDir(), ".claude", "settings.json");
7915
8435
  }
7916
8436
  function installPiExtension(cwd, remove = false, scope = "repo") {
7917
- const file = scope === "global" ? path17.join(homeDir(), ".pi/agent/extensions/bunshin.js") : path17.join(cwd, ".pi/extensions/bunshin.js");
8437
+ const file2 = scope === "global" ? path18.join(homeDir(), ".pi/agent/extensions/bunshin.js") : path18.join(cwd, ".pi/extensions/bunshin.js");
7918
8438
  const marker = "// Managed by Bunshin setup.";
7919
8439
  try {
7920
- const previous = fileExists(file) ? fs22.readFileSync(file, "utf8") : "";
8440
+ const previous = fileExists(file2) ? fs23.readFileSync(file2, "utf8") : "";
7921
8441
  if (previous && !previous.startsWith(marker)) throw new Error("An existing Bunshin extension file is not managed by setup; preserve or move it before continuing.");
7922
8442
  if (remove) {
7923
- if (previous) fs22.unlinkSync(file);
7924
- return { file, installed: 0, changed: !!previous };
8443
+ if (previous) fs23.unlinkSync(file2);
8444
+ return { file: file2, installed: 0, changed: !!previous };
7925
8445
  }
7926
8446
  const extension = fileURLToPath2(new URL("./pi-extension.js", import.meta.url));
7927
8447
  if (!fileExists(extension)) throw new Error("The packaged Pi extension is missing. Reinstall @bunshin-cc/bunshin.");
@@ -7929,64 +8449,64 @@ function installPiExtension(cwd, remove = false, scope = "repo") {
7929
8449
  export { default } from ${JSON.stringify(pathToFileURL(extension).href)};
7930
8450
  `;
7931
8451
  if (text2 !== previous) {
7932
- ensureDir(path17.dirname(file));
7933
- fs22.writeFileSync(file, text2);
8452
+ ensureDir(path18.dirname(file2));
8453
+ fs23.writeFileSync(file2, text2);
7934
8454
  }
7935
- return { file, installed: 1, changed: text2 !== previous };
8455
+ return { file: file2, installed: 1, changed: text2 !== previous };
7936
8456
  } catch (error) {
7937
- return { file, installed: 0, changed: false, error: error instanceof Error ? error.message : String(error) };
8457
+ return { file: file2, installed: 0, changed: false, error: error instanceof Error ? error.message : String(error) };
7938
8458
  }
7939
8459
  }
7940
- function installClaudeHooks({ file = claudeSettingsPath(), bin = "bunshin", remove = false, harness = "claude-code", user = false, allTools = false } = {}) {
8460
+ function installClaudeHooks({ file: file2 = claudeSettingsPath(), bin = "bunshin", remove = false, harness = "claude-code", user = false, allTools = false } = {}) {
7941
8461
  try {
7942
- const before = fileExists(file) ? JSON.parse(fs22.readFileSync(file, "utf8")) : {};
8462
+ const before = fileExists(file2) ? JSON.parse(fs23.readFileSync(file2, "utf8")) : {};
7943
8463
  const after = remove ? removeBunshinHooks(before) : mergeClaudeSettings(before, { bin, harness, user, allTools });
7944
8464
  const changed = JSON.stringify(before) !== JSON.stringify(after);
7945
8465
  if (changed) {
7946
- ensureDir(path17.dirname(file));
7947
- if (fileExists(file)) {
8466
+ ensureDir(path18.dirname(file2));
8467
+ if (fileExists(file2)) {
7948
8468
  try {
7949
- fs22.copyFileSync(file, `${file}.bunshin-backup`);
8469
+ fs23.copyFileSync(file2, `${file2}.bunshin-backup`);
7950
8470
  } catch {
7951
8471
  }
7952
8472
  }
7953
- writeJsonAtomic(file, after);
8473
+ writeJsonAtomic(file2, after);
7954
8474
  }
7955
- return { file, installed: countBunshinHooks(after), changed };
8475
+ return { file: file2, installed: countBunshinHooks(after), changed };
7956
8476
  } catch (err) {
7957
- return { file, installed: 0, changed: false, error: err instanceof Error ? err.message : String(err) };
8477
+ return { file: file2, installed: 0, changed: false, error: err instanceof Error ? err.message : String(err) };
7958
8478
  }
7959
8479
  }
7960
8480
  function mcpLauncher(bin) {
7961
8481
  if (!bin || /^[\w./@+-]+$/.test(bin)) return { command: bin || "bunshin", args: ["mcp"] };
7962
8482
  let script = process.argv[1] ?? "";
7963
8483
  try {
7964
- script = fs22.realpathSync(script);
8484
+ script = fs23.realpathSync(script);
7965
8485
  } catch {
7966
8486
  }
7967
8487
  return { command: process.execPath, args: [script, "mcp"] };
7968
8488
  }
7969
- function installLearnCommand({ file, remove = false, content = LEARN_COMMAND }) {
8489
+ function installLearnCommand({ file: file2, remove = false, content = LEARN_COMMAND }) {
7970
8490
  try {
7971
- const current = fileExists(file) ? fs22.readFileSync(file, "utf8") : null;
8491
+ const current = fileExists(file2) ? fs23.readFileSync(file2, "utf8") : null;
7972
8492
  const ours = current === null || current === content;
7973
8493
  if (remove) {
7974
- if (current !== null && ours) fs22.unlinkSync(file);
7975
- return { file, installed: 0, changed: current !== null && ours };
8494
+ if (current !== null && ours) fs23.unlinkSync(file2);
8495
+ return { file: file2, installed: 0, changed: current !== null && ours };
7976
8496
  }
7977
- if (!ours) return { file, installed: 0, changed: false, error: `a different ${path17.basename(file)} is already there; left as it is` };
8497
+ if (!ours) return { file: file2, installed: 0, changed: false, error: `a different ${path18.basename(file2)} is already there; left as it is` };
7978
8498
  if (current === null) {
7979
- fs22.mkdirSync(path17.dirname(file), { recursive: true });
7980
- fs22.writeFileSync(file, content);
8499
+ fs23.mkdirSync(path18.dirname(file2), { recursive: true });
8500
+ fs23.writeFileSync(file2, content);
7981
8501
  }
7982
- return { file, installed: 1, changed: current === null };
8502
+ return { file: file2, installed: 1, changed: current === null };
7983
8503
  } catch (err) {
7984
- return { file, installed: 0, changed: false, error: err instanceof Error ? err.message : String(err) };
8504
+ return { file: file2, installed: 0, changed: false, error: err instanceof Error ? err.message : String(err) };
7985
8505
  }
7986
8506
  }
7987
- function installMcpConfig({ file, launcher, remove = false }) {
8507
+ function installMcpConfig({ file: file2, launcher, remove = false }) {
7988
8508
  try {
7989
- const before = fileExists(file) ? JSON.parse(fs22.readFileSync(file, "utf8")) : {};
8509
+ const before = fileExists(file2) ? JSON.parse(fs23.readFileSync(file2, "utf8")) : {};
7990
8510
  const servers = { ...before.mcpServers ?? {} };
7991
8511
  if (remove) delete servers.bunshin;
7992
8512
  else servers.bunshin = { type: "stdio", command: launcher.command, args: launcher.args, env: { BUNSHIN_HARNESS: "claude-code" } };
@@ -7994,16 +8514,16 @@ function installMcpConfig({ file, launcher, remove = false }) {
7994
8514
  if (!Object.keys(servers).length) delete after.mcpServers;
7995
8515
  const changed = JSON.stringify(before) !== JSON.stringify(after);
7996
8516
  if (changed) {
7997
- if (!Object.keys(after).length && fileExists(file)) fs22.unlinkSync(file);
7998
- else if (Object.keys(after).length) writeJsonAtomic(file, after);
8517
+ if (!Object.keys(after).length && fileExists(file2)) fs23.unlinkSync(file2);
8518
+ else if (Object.keys(after).length) writeJsonAtomic(file2, after);
7999
8519
  }
8000
- return { file, installed: servers.bunshin ? 1 : 0, changed };
8520
+ return { file: file2, installed: servers.bunshin ? 1 : 0, changed };
8001
8521
  } catch (err) {
8002
- return { file, installed: 0, changed: false, error: err instanceof Error ? err.message : String(err) };
8522
+ return { file: file2, installed: 0, changed: false, error: err instanceof Error ? err.message : String(err) };
8003
8523
  }
8004
8524
  }
8005
8525
  function installUserMcp({ launcher, remove = false, claude = "claude" }) {
8006
- const file = path17.join(homeDir(), ".claude.json");
8526
+ const file2 = path18.join(homeDir(), ".claude.json");
8007
8527
  const run2 = (args) => execFileSync5(claude, args, { stdio: ["ignore", "pipe", "pipe"], timeout: 2e4, env: { ...process.env, BUNSHIN_CHILD: "1" } }).toString();
8008
8528
  try {
8009
8529
  let had = false;
@@ -8018,33 +8538,33 @@ function installUserMcp({ launcher, remove = false, claude = "claude" }) {
8018
8538
  } catch {
8019
8539
  }
8020
8540
  }
8021
- if (remove) return { file, installed: 0, changed: had };
8541
+ if (remove) return { file: file2, installed: 0, changed: had };
8022
8542
  run2(["mcp", "add-json", "bunshin", JSON.stringify({ type: "stdio", command: launcher.command, args: launcher.args, env: { BUNSHIN_HARNESS: "claude-code" } }), "-s", "user"]);
8023
- return { file, installed: 1, changed: true };
8543
+ return { file: file2, installed: 1, changed: true };
8024
8544
  } catch (err) {
8025
- return { file, installed: 0, changed: false, error: err instanceof Error ? err.message.split("\n")[0] : String(err) };
8545
+ return { file: file2, installed: 0, changed: false, error: err instanceof Error ? err.message.split("\n")[0] : String(err) };
8026
8546
  }
8027
8547
  }
8028
8548
  function runInit(opts = {}) {
8029
8549
  const cwd = opts.cwd ?? process.cwd();
8030
8550
  const warnings = [];
8031
8551
  const scope = opts.scope ?? "repo";
8032
- const root = scope === "global" ? path17.join(homeDir(), ".bunshin") : path17.join(cwd, ".bunshin");
8033
- if (fs22.existsSync(root) && !new Store(root).trusted && fs22.readdirSync(root).length) {
8552
+ const root = scope === "global" ? path18.join(homeDir(), ".bunshin") : path18.join(cwd, ".bunshin");
8553
+ if (fs23.existsSync(root) && !new Store(root).trusted && fs23.readdirSync(root).length) {
8034
8554
  const aside = `${root}.untrusted-${Date.now()}`;
8035
- fs22.renameSync(root, aside);
8555
+ fs23.renameSync(root, aside);
8036
8556
  warnings.push(`moved ${root} aside to ${aside}: this user did not create it`);
8037
8557
  }
8038
- const existed = fileExists(path17.join(root, "config.json"));
8558
+ const existed = fileExists(path18.join(root, "config.json"));
8039
8559
  const store = new Store(root);
8040
8560
  store.ensureLayout();
8041
- fs22.chmodSync(root, 448);
8561
+ fs23.chmodSync(root, 448);
8042
8562
  const hookScope = opts.hooks ?? (scope === "global" ? "user" : (existed && store.trusted ? store.config().hooks : void 0) ?? "project");
8043
- if (scope === "repo" && (hookScope === "project" || fileExists(path17.join(cwd, ".git")))) {
8044
- const ignore = path17.join(cwd, ".gitignore");
8045
- const current = fileExists(ignore) ? fs22.readFileSync(ignore, "utf8") : "";
8563
+ if (scope === "repo" && (hookScope === "project" || fileExists(path18.join(cwd, ".git")))) {
8564
+ const ignore = path18.join(cwd, ".gitignore");
8565
+ const current = fileExists(ignore) ? fs23.readFileSync(ignore, "utf8") : "";
8046
8566
  if (!current.split(/\r?\n/).some((line) => /^\/?\.bunshin\/?$/.test(line.trim()))) {
8047
- fs22.appendFileSync(ignore, `${current && !current.endsWith("\n") ? "\n" : ""}.bunshin/
8567
+ fs23.appendFileSync(ignore, `${current && !current.endsWith("\n") ? "\n" : ""}.bunshin/
8048
8568
  `);
8049
8569
  }
8050
8570
  }
@@ -8074,17 +8594,17 @@ function runInit(opts = {}) {
8074
8594
  }
8075
8595
  if ((opts.removeHooks || !opts.noHooks) && (config.harness === "codex" || config.harness === "claude-code")) {
8076
8596
  const projectHooks = config.harness === "codex" && hookScope === "project" && !opts.settingsFile ? codexProjectHooks(cwd) : void 0;
8077
- 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());
8078
- hooks = installClaudeHooks({ file, bin: opts.bin, remove: opts.removeHooks, harness: config.harness, user: hookScope === "user" && !opts.settingsFile, allTools: config.recall.router === "claude-cli" });
8597
+ 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());
8598
+ hooks = installClaudeHooks({ file: file2, bin: opts.bin, remove: opts.removeHooks, harness: config.harness, user: hookScope === "user" && !opts.settingsFile, allTools: recallRouter(config) === "claude-cli" });
8079
8599
  if (!opts.removeHooks && !opts.settingsFile && hookScope === "user" && config.harness === "claude-code") {
8080
- const local = path17.join(cwd, ".claude", "settings.local.json");
8081
- if (fileExists(local) && path17.resolve(local) !== path17.resolve(file)) installClaudeHooks({ file: local, remove: true });
8600
+ const local = path18.join(cwd, ".claude", "settings.local.json");
8601
+ if (fileExists(local) && path18.resolve(local) !== path18.resolve(file2)) installClaudeHooks({ file: local, remove: true });
8082
8602
  }
8083
8603
  if (projectHooks?.shared) {
8084
8604
  hooks.sharedWithWorktrees = true;
8085
- if (!hooks.error && !opts.removeHooks) ensureDir(path17.dirname(projectHooks.legacyFile));
8605
+ if (!hooks.error && !opts.removeHooks) ensureDir(path18.dirname(projectHooks.legacyFile));
8086
8606
  }
8087
- if (!hooks.error && projectHooks && projectHooks.file !== projectHooks.legacyFile && fileExists(projectHooks.legacyFile) && fs22.realpathSync(projectHooks.file) !== fs22.realpathSync(projectHooks.legacyFile)) {
8607
+ if (!hooks.error && projectHooks && projectHooks.file !== projectHooks.legacyFile && fileExists(projectHooks.legacyFile) && fs23.realpathSync(projectHooks.file) !== fs23.realpathSync(projectHooks.legacyFile)) {
8088
8608
  const old = installClaudeHooks({ file: projectHooks.legacyFile, remove: true, harness: "codex" });
8089
8609
  if (old.error) hooks.error = `Could not remove old Bunshin hooks from ${old.file}: ${old.error}`;
8090
8610
  }
@@ -8094,17 +8614,17 @@ function runInit(opts = {}) {
8094
8614
  let learnCommand;
8095
8615
  if ((opts.removeHooks || !opts.noHooks) && config.harness === "claude-code") {
8096
8616
  const user = hookScope === "user";
8097
- 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 });
8617
+ 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 });
8098
8618
  if (mcp.error) warnings.push(`could not update ${mcp.file}: ${mcp.error}`);
8099
- learnCommand = installLearnCommand({ file: path17.join(user ? path17.join(homeDir(), ".claude") : path17.join(cwd, ".claude"), "commands", "learn.md"), remove: opts.removeHooks });
8619
+ learnCommand = installLearnCommand({ file: path18.join(user ? path18.join(homeDir(), ".claude") : path18.join(cwd, ".claude"), "commands", "learn.md"), remove: opts.removeHooks });
8100
8620
  if (learnCommand.error) warnings.push(`/learn not installed at ${learnCommand.file}: ${learnCommand.error}`);
8101
8621
  }
8102
8622
  let borrowCommand;
8103
8623
  if (opts.removeHooks || !opts.noHooks) {
8104
8624
  const user = hookScope === "user";
8105
- 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;
8106
- if (file) {
8107
- borrowCommand = installLearnCommand({ file, remove: opts.removeHooks, content: BORROW_COMMAND });
8625
+ 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;
8626
+ if (file2) {
8627
+ borrowCommand = installLearnCommand({ file: file2, remove: opts.removeHooks, content: BORROW_COMMAND });
8108
8628
  if (borrowCommand.error) warnings.push(`/borrow not installed at ${borrowCommand.file}: ${borrowCommand.error}`);
8109
8629
  }
8110
8630
  }
@@ -8260,8 +8780,8 @@ __export(commands_exports, {
8260
8780
  setupRobot: () => setupRobot,
8261
8781
  v2Status: () => v2Status
8262
8782
  });
8263
- import fs23 from "node:fs";
8264
- import path18 from "node:path";
8783
+ import fs24 from "node:fs";
8784
+ import path19 from "node:path";
8265
8785
  import { createHash as createHash6, randomBytes as randomBytes4 } from "node:crypto";
8266
8786
  function cmdReview(store, args, cwd, out, err) {
8267
8787
  const v2 = new V2Store(store);
@@ -8432,13 +8952,13 @@ function cmdSuggest(store, args, cwd, out, err) {
8432
8952
  err('bunshin suggest: usage: bunshin suggest --code <harness-relative path> [--file <local file>] [--rationale "<text>"]\n');
8433
8953
  return 1;
8434
8954
  }
8435
- const harnessDir = path18.resolve(cwd, str3(args.flags["harness-dir"]) ?? ".");
8436
- const file = str3(args.flags.file) ? path18.resolve(cwd, str3(args.flags.file)) : path18.join(harnessDir, rel);
8955
+ const harnessDir = path19.resolve(cwd, str3(args.flags["harness-dir"]) ?? ".");
8956
+ const file2 = str3(args.flags.file) ? path19.resolve(cwd, str3(args.flags.file)) : path19.join(harnessDir, rel);
8437
8957
  let content;
8438
8958
  try {
8439
- content = fs23.readFileSync(file, "utf8");
8959
+ content = fs24.readFileSync(file2, "utf8");
8440
8960
  } catch {
8441
- err(`bunshin suggest: cannot read ${file}
8961
+ err(`bunshin suggest: cannot read ${file2}
8442
8962
  `);
8443
8963
  return 1;
8444
8964
  }
@@ -8557,26 +9077,26 @@ async function cmdQuestions(store, args, out, err) {
8557
9077
  return 0;
8558
9078
  }
8559
9079
  function saveCredential(storeRoot, apiUrl, apiKey, id) {
8560
- const dir2 = path18.join(homeDir(), ".config/bunshin/credentials");
8561
- fs23.mkdirSync(dir2, { recursive: true, mode: 448 });
8562
- fs23.chmodSync(dir2, 448);
8563
- const file = path18.join(dir2, `${createHash6("sha256").update(`${storeRoot}
9080
+ const dir2 = path19.join(homeDir(), ".config/bunshin/credentials");
9081
+ fs24.mkdirSync(dir2, { recursive: true, mode: 448 });
9082
+ fs24.chmodSync(dir2, 448);
9083
+ const file2 = path19.join(dir2, `${createHash6("sha256").update(`${storeRoot}
8564
9084
  ${apiUrl}
8565
9085
  ${id}`).digest("hex")}.json`);
8566
- const tmp = `${file}.${randomBytes4(4).toString("hex")}.tmp`;
8567
- fs23.writeFileSync(tmp, JSON.stringify({ apiUrl, apiKey }) + "\n", { mode: 384, flag: "wx" });
8568
- fs23.renameSync(tmp, file);
8569
- return file;
9086
+ const tmp = `${file2}.${randomBytes4(4).toString("hex")}.tmp`;
9087
+ fs24.writeFileSync(tmp, JSON.stringify({ apiUrl, apiKey }) + "\n", { mode: 384, flag: "wx" });
9088
+ fs24.renameSync(tmp, file2);
9089
+ return file2;
8570
9090
  }
8571
9091
  async function setupRobot(opts) {
8572
9092
  if (!/^[A-Za-z0-9._-]{1,100}$/.test(opts.robotId)) throw new Error("--robot-id must be letters, digits, '.', '_' or '-'");
8573
9093
  const existing = Store.discover(opts.cwd);
8574
9094
  let store;
8575
9095
  const harness = opts.harness ?? "other";
8576
- if (existing && path18.resolve(path18.dirname(existing.root)) === path18.resolve(opts.cwd) && harness === "other") store = existing;
9096
+ if (existing && path19.resolve(path19.dirname(existing.root)) === path19.resolve(opts.cwd) && harness === "other") store = existing;
8577
9097
  else {
8578
9098
  runInit({ cwd: opts.cwd, harness, noHooks: harness === "other", ...opts.apiUrl ? { apiUrl: opts.apiUrl } : {} });
8579
- store = new Store(path18.join(opts.cwd, ".bunshin"));
9099
+ store = new Store(path19.join(opts.cwd, ".bunshin"));
8580
9100
  }
8581
9101
  let config = store.config();
8582
9102
  const apiUrl = (opts.apiUrl ?? config.apiUrl ?? "").replace(/\/$/, "");
@@ -8730,16 +9250,16 @@ __export(setup_exports, {
8730
9250
  setupProject: () => setupProject,
8731
9251
  shellQuote: () => shellQuote
8732
9252
  });
8733
- import fs24 from "node:fs";
8734
- import path19 from "node:path";
9253
+ import fs25 from "node:fs";
9254
+ import path20 from "node:path";
8735
9255
  import { createHash as createHash7, randomBytes as randomBytes5 } from "node:crypto";
8736
9256
  function executable(name) {
8737
- const directories = [...(process.env.PATH ?? "").split(path19.delimiter), path19.join(homeDir(), ".local/bin")];
9257
+ const directories = [...(process.env.PATH ?? "").split(path20.delimiter), path20.join(homeDir(), ".local/bin")];
8738
9258
  for (const directory of directories) {
8739
- const file = path19.resolve(directory, name);
9259
+ const file2 = path20.resolve(directory, name);
8740
9260
  try {
8741
- fs24.accessSync(file, fs24.constants.X_OK);
8742
- if (fs24.statSync(file).isFile()) return file;
9261
+ fs25.accessSync(file2, fs25.constants.X_OK);
9262
+ if (fs25.statSync(file2).isFile()) return file2;
8743
9263
  } catch {
8744
9264
  }
8745
9265
  }
@@ -8747,8 +9267,8 @@ function executable(name) {
8747
9267
  }
8748
9268
  function hookBinary(harness) {
8749
9269
  const agent = executable(harness === "claude-code" ? "claude" : harness);
8750
- const directories = [.../* @__PURE__ */ new Set([path19.dirname(process.execPath), path19.join(homeDir(), ".local/bin"), ...agent ? [path19.dirname(agent)] : []])];
8751
- return `PATH=${shellQuote(directories.join(path19.delimiter))}:"$PATH" ${shellQuote(process.execPath)} ${shellQuote(fs24.realpathSync(process.argv[1]))}`;
9270
+ const directories = [.../* @__PURE__ */ new Set([path20.dirname(process.execPath), path20.join(homeDir(), ".local/bin"), ...agent ? [path20.dirname(agent)] : []])];
9271
+ return `PATH=${shellQuote(directories.join(path20.delimiter))}:"$PATH" ${shellQuote(process.execPath)} ${shellQuote(fs25.realpathSync(process.argv[1]))}`;
8752
9272
  }
8753
9273
  function apiAddress(raw) {
8754
9274
  const url = new URL(raw);
@@ -8777,7 +9297,8 @@ async function connectionProfile(apiUrl, apiKey) {
8777
9297
  if (!profile || ![profile.orgId, profile.userId, profile.role].every((value) => typeof value === "string" && value.length > 0) || typeof profile.orgUnit !== "string" || !["public", "org", "department", "team", "leadership", "csuite", "private"].includes(profile.clearance) || !Array.isArray(profile.responsibilities) || !profile.responsibilities.every((value) => typeof value === "string")) {
8778
9298
  throw new Error("Bunshin returned an incomplete profile. No connection settings were changed.");
8779
9299
  }
8780
- return profile;
9300
+ const { orgId, userId, role, orgUnit, clearance, responsibilities } = profile;
9301
+ return { orgId, userId, role, orgUnit, clearance, responsibilities: [...responsibilities] };
8781
9302
  }
8782
9303
  async function readKey() {
8783
9304
  if (!process.stdin.isTTY) throw new Error("Run setup in a terminal to paste your key, or supply it through BUNSHIN_API_KEY or --key-stdin.");
@@ -8817,23 +9338,23 @@ async function setupProject(opts) {
8817
9338
  const apiKey = opts.apiKey.trim();
8818
9339
  if (!apiKey || /\s/.test(apiKey)) throw new Error("Paste the complete agent key from your Bunshin workspace.");
8819
9340
  const profile = await connectionProfile(apiUrl, apiKey);
8820
- const root = path19.join(opts.cwd, ".bunshin");
9341
+ const root = path20.join(opts.cwd, ".bunshin");
8821
9342
  const store = new Store(root);
8822
9343
  const previous = store.config();
8823
9344
  if ((previous.orgId !== profile.orgId || previous.userId !== profile.userId) && (store.listLessons().length || store.allTraces().length || store.listRecallLessons().length)) {
8824
9345
  throw new Error("This project has lessons or activity from another profile. Use a fresh project to connect this workspace.");
8825
9346
  }
8826
- const credentialDirectory = path19.join(homeDir(), ".config/bunshin/credentials");
8827
- fs24.mkdirSync(credentialDirectory, { recursive: true, mode: 448 });
8828
- fs24.chmodSync(credentialDirectory, 448);
9347
+ const credentialDirectory = path20.join(homeDir(), ".config/bunshin/credentials");
9348
+ fs25.mkdirSync(credentialDirectory, { recursive: true, mode: 448 });
9349
+ fs25.chmodSync(credentialDirectory, 448);
8829
9350
  const name = createHash7("sha256").update(`${root}
8830
9351
  ${apiUrl}
8831
9352
  ${profile.orgId}
8832
9353
  ${profile.userId}`).digest("hex");
8833
- const credentialFile = path19.join(credentialDirectory, `${name}.json`);
9354
+ const credentialFile = path20.join(credentialDirectory, `${name}.json`);
8834
9355
  const temporary = `${credentialFile}.${randomBytes5(4).toString("hex")}.tmp`;
8835
- fs24.writeFileSync(temporary, JSON.stringify({ apiUrl, apiKey }) + "\n", { mode: 384, flag: "wx" });
8836
- fs24.renameSync(temporary, credentialFile);
9356
+ fs25.writeFileSync(temporary, JSON.stringify({ apiUrl, apiKey }) + "\n", { mode: 384, flag: "wx" });
9357
+ fs25.renameSync(temporary, credentialFile);
8837
9358
  const result = runInit({
8838
9359
  cwd: opts.cwd,
8839
9360
  harness: opts.harness,
@@ -9186,8 +9707,8 @@ __export(sync_exports2, {
9186
9707
  runSync: () => runSync
9187
9708
  });
9188
9709
  import { createHash as createHash8 } from "node:crypto";
9189
- import path20 from "node:path";
9190
- import fs25 from "node:fs";
9710
+ import path21 from "node:path";
9711
+ import fs26 from "node:fs";
9191
9712
  async function api(config, method, route, body, timeoutMs = 1e4) {
9192
9713
  const ctrl = new AbortController();
9193
9714
  const timer = setTimeout(() => ctrl.abort(), timeoutMs);
@@ -9225,22 +9746,22 @@ async function mothershipLookup(config, ids, timeoutMs = 8e3) {
9225
9746
  }
9226
9747
  }
9227
9748
  async function runSync(store) {
9228
- const lock = path20.join(store.root, "sync.lock");
9749
+ const lock = path21.join(store.root, "sync.lock");
9229
9750
  const deadline = Date.now() + 12e4;
9230
9751
  for (; ; ) {
9231
9752
  try {
9232
- fs25.writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 });
9753
+ fs26.writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 });
9233
9754
  break;
9234
9755
  } catch (error) {
9235
9756
  if (error.code !== "EEXIST") throw error;
9236
9757
  try {
9237
- const owner = Number(fs25.readFileSync(lock, "utf8"));
9758
+ const owner = Number(fs26.readFileSync(lock, "utf8"));
9238
9759
  if (Number.isInteger(owner) && owner > 0) {
9239
9760
  try {
9240
9761
  process.kill(owner, 0);
9241
9762
  } catch (error2) {
9242
9763
  if (error2.code === "ESRCH") {
9243
- fs25.unlinkSync(lock);
9764
+ fs26.unlinkSync(lock);
9244
9765
  continue;
9245
9766
  }
9246
9767
  }
@@ -9259,7 +9780,7 @@ async function runSync(store) {
9259
9780
  return await syncStore(store);
9260
9781
  } finally {
9261
9782
  try {
9262
- fs25.unlinkSync(lock);
9783
+ fs26.unlinkSync(lock);
9263
9784
  } catch {
9264
9785
  }
9265
9786
  }
@@ -9287,7 +9808,7 @@ async function syncStore(store) {
9287
9808
  result.errors.push(String(e instanceof Error ? e.message : e));
9288
9809
  }
9289
9810
  }
9290
- const acknowledgementsFile = path20.join(store.root, "synced-traces.json");
9811
+ const acknowledgementsFile = path21.join(store.root, "synced-traces.json");
9291
9812
  const acknowledgements = readJson(acknowledgementsFile, {});
9292
9813
  const fingerprint2 = (trace) => createHash8("sha256").update(JSON.stringify(trace)).digest("hex");
9293
9814
  const traces = store.allTraces().filter((t) => acknowledgements[t.id] !== fingerprint2(t)).slice(0, 50);
@@ -9542,11 +10063,11 @@ __export(demo_exports, {
9542
10063
  runDemo: () => runDemo
9543
10064
  });
9544
10065
  import assert from "node:assert/strict";
9545
- import fs26 from "node:fs";
10066
+ import fs27 from "node:fs";
9546
10067
  import os4 from "node:os";
9547
- import path21 from "node:path";
10068
+ import path22 from "node:path";
9548
10069
  async function runDemo(write) {
9549
- const root = fs26.mkdtempSync(path21.join(os4.tmpdir(), "bunshin-demo-"));
10070
+ const root = fs27.mkdtempSync(path22.join(os4.tmpdir(), "bunshin-demo-"));
9550
10071
  try {
9551
10072
  const store = Store.init(root, { ...APR_ENGINEER, apiUrl: "" });
9552
10073
  const { lessons, constraint, workflow } = aprScenario();
@@ -9563,7 +10084,7 @@ Task: ${APR_TASK}
9563
10084
  write(result.text);
9564
10085
  write("\nPASS: Collections constraint and workflow recalled; C-suite, other-company, and superseded lessons excluded.\n");
9565
10086
  } finally {
9566
- fs26.rmSync(root, { recursive: true, force: true });
10087
+ fs27.rmSync(root, { recursive: true, force: true });
9567
10088
  }
9568
10089
  }
9569
10090
  var init_demo = __esm({
@@ -9576,21 +10097,21 @@ var init_demo = __esm({
9576
10097
  });
9577
10098
 
9578
10099
  // src/v2/gitremote.ts
9579
- import fs27 from "node:fs";
9580
- import path22 from "node:path";
10100
+ import fs28 from "node:fs";
10101
+ import path23 from "node:path";
9581
10102
  import { createHash as createHash9 } from "node:crypto";
9582
10103
  function saveGitCredential(apiUrl, apiKey) {
9583
- const file = gitCredentialFile();
9584
- fs27.mkdirSync(path22.dirname(file), { recursive: true, mode: 448 });
10104
+ const file2 = gitCredentialFile();
10105
+ fs28.mkdirSync(path23.dirname(file2), { recursive: true, mode: 448 });
9585
10106
  let all = {};
9586
10107
  try {
9587
- all = JSON.parse(fs27.readFileSync(file, "utf8"));
10108
+ all = JSON.parse(fs28.readFileSync(file2, "utf8"));
9588
10109
  } catch {
9589
10110
  }
9590
10111
  all[apiUrl.replace(/\/$/, "")] = apiKey;
9591
- const tmp = `${file}.${process.pid}.tmp`;
9592
- fs27.writeFileSync(tmp, JSON.stringify(all, null, 2) + "\n", { mode: 384 });
9593
- fs27.renameSync(tmp, file);
10112
+ const tmp = `${file2}.${process.pid}.tmp`;
10113
+ fs28.writeFileSync(tmp, JSON.stringify(all, null, 2) + "\n", { mode: 384 });
10114
+ fs28.renameSync(tmp, file2);
9594
10115
  }
9595
10116
  function resolveGitKey(apiUrl) {
9596
10117
  const base = apiUrl.replace(/\/$/, "");
@@ -9598,20 +10119,20 @@ function resolveGitKey(apiUrl) {
9598
10119
  const origin = urlOrigin(base);
9599
10120
  if (process.env.BUNSHIN_API_KEY && origin && trustedOrigins().has(origin)) return process.env.BUNSHIN_API_KEY;
9600
10121
  try {
9601
- const all = JSON.parse(fs27.readFileSync(gitCredentialFile(), "utf8"));
10122
+ const all = JSON.parse(fs28.readFileSync(gitCredentialFile(), "utf8"));
9602
10123
  if (all[base]) return all[base];
9603
10124
  } catch {
9604
10125
  }
9605
- const dir2 = path22.join(homeDir(), ".config/bunshin/credentials");
10126
+ const dir2 = path23.join(homeDir(), ".config/bunshin/credentials");
9606
10127
  let files = [];
9607
10128
  try {
9608
- files = fs27.readdirSync(dir2).filter((f) => f.endsWith(".json"));
10129
+ files = fs28.readdirSync(dir2).filter((f) => f.endsWith(".json"));
9609
10130
  } catch {
9610
10131
  return void 0;
9611
10132
  }
9612
10133
  for (const f of files.sort()) {
9613
10134
  try {
9614
- const c = JSON.parse(fs27.readFileSync(path22.join(dir2, f), "utf8"));
10135
+ const c = JSON.parse(fs28.readFileSync(path23.join(dir2, f), "utf8"));
9615
10136
  if (c.apiKey && c.apiUrl?.replace(/\/$/, "") === base) return c.apiKey;
9616
10137
  } catch {
9617
10138
  }
@@ -9632,7 +10153,7 @@ var init_gitremote = __esm({
9632
10153
  ZERO_SHA = "0".repeat(40);
9633
10154
  REMOTE_PATH = "/v1/git/repos/";
9634
10155
  remoteUrl = (apiUrl, repo) => `bunshin::${apiUrl.replace(/\/$/, "")}${REMOTE_PATH}${repo}`;
9635
- gitCredentialFile = () => path22.join(homeDir(), ".config/bunshin/git-credentials.json");
10156
+ gitCredentialFile = () => path23.join(homeDir(), ".config/bunshin/git-credentials.json");
9636
10157
  GitApiError = class extends Error {
9637
10158
  constructor(status, message, body = null) {
9638
10159
  super(message);
@@ -9724,8 +10245,8 @@ __export(gitrepo_exports, {
9724
10245
  githubReferences: () => githubReferences,
9725
10246
  repoFromUrl: () => repoFromUrl
9726
10247
  });
9727
- import fs28 from "node:fs";
9728
- import path23 from "node:path";
10248
+ import fs29 from "node:fs";
10249
+ import path24 from "node:path";
9729
10250
  import { spawnSync as spawnSync2 } from "node:child_process";
9730
10251
  function git3(cwd, args, opts = {}) {
9731
10252
  const r = spawnSync2("git", ["-C", cwd, ...args], { encoding: "utf8", stdio: opts.inherit ? ["ignore", "inherit", "inherit"] : ["ignore", "pipe", "pipe"], maxBuffer: 256 * 1024 * 1024 });
@@ -9734,9 +10255,9 @@ function git3(cwd, args, opts = {}) {
9734
10255
  return res;
9735
10256
  }
9736
10257
  function onPath(name) {
9737
- for (const dir2 of (process.env.PATH ?? "").split(path23.delimiter)) {
10258
+ for (const dir2 of (process.env.PATH ?? "").split(path24.delimiter)) {
9738
10259
  try {
9739
- fs28.accessSync(path23.join(dir2, name), fs28.constants.X_OK);
10260
+ fs29.accessSync(path24.join(dir2, name), fs29.constants.X_OK);
9740
10261
  return true;
9741
10262
  } catch {
9742
10263
  }
@@ -9820,11 +10341,11 @@ function switchOrigin(root, url, out) {
9820
10341
  }
9821
10342
  async function cmdImport(args, cwd, out, err) {
9822
10343
  requireHelper();
9823
- const root = toplevel(path23.resolve(str4(args.flags.path) ?? args._[1] ?? cwd));
10344
+ const root = toplevel(path24.resolve(str4(args.flags.path) ?? args._[1] ?? cwd));
9824
10345
  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");
9825
10346
  const rs = remotes(root);
9826
10347
  const originUrl = rs.get("origin");
9827
- const name = str4(args.flags.name) ?? (originUrl && !originUrl.startsWith("bunshin::") ? repoFromUrl(originUrl) : null) ?? `${path23.basename(path23.dirname(root))}/${path23.basename(root)}`;
10348
+ const name = str4(args.flags.name) ?? (originUrl && !originUrl.startsWith("bunshin::") ? repoFromUrl(originUrl) : null) ?? `${path24.basename(path24.dirname(root))}/${path24.basename(root)}`;
9828
10349
  const client = await connect(args, cwd);
9829
10350
  const url = remoteUrl(client.apiUrl, name);
9830
10351
  const fromOrigin = !!originUrl && !originUrl.startsWith("bunshin::") && !bool3(args.flags.local);
@@ -9900,7 +10421,7 @@ ${refsToGithub.length} line${refsToGithub.length === 1 ? "" : "s"} in the reposi
9900
10421
  if (refsToGithub.length > 40) out(` \u2026 and ${refsToGithub.length - 40} more (git grep for ${name})
9901
10422
  `);
9902
10423
  }
9903
- if (fs28.existsSync(path23.join(root, ".github"))) out(`
10424
+ if (fs29.existsSync(path24.join(root, ".github"))) out(`
9904
10425
  Note: .github/ (Actions, CODEOWNERS, templates) only works on GitHub; Bunshin does not run it.
9905
10426
  `);
9906
10427
  out(`
@@ -9911,7 +10432,7 @@ New machines clone with: bunshin repo clone ${name}
9911
10432
  }
9912
10433
  async function cmdAttach(args, cwd, out, err) {
9913
10434
  requireHelper();
9914
- const root = toplevel(path23.resolve(str4(args.flags.path) ?? cwd));
10435
+ const root = toplevel(path24.resolve(str4(args.flags.path) ?? cwd));
9915
10436
  const rs = remotes(root);
9916
10437
  const originUrl = rs.get("origin");
9917
10438
  const name = str4(args.flags.name) ?? args._[1] ?? (originUrl ? repoFromUrl(originUrl) : null);
@@ -9959,12 +10480,12 @@ async function cmdClone(args, cwd, out) {
9959
10480
  const dir2 = args._[2] ?? name.split("/")[1];
9960
10481
  const r = spawnSync2("git", ["clone", remoteUrl(client.apiUrl, name), dir2], { cwd, stdio: "inherit" });
9961
10482
  if (r.status !== 0) return r.status ?? 1;
9962
- out(`Cloned ${name} into ${path23.resolve(cwd, dir2)}
10483
+ out(`Cloned ${name} into ${path24.resolve(cwd, dir2)}
9963
10484
  `);
9964
10485
  return 0;
9965
10486
  }
9966
10487
  async function cmdVerify(args, cwd, out, err) {
9967
- const root = toplevel(path23.resolve(str4(args.flags.path) ?? cwd));
10488
+ const root = toplevel(path24.resolve(str4(args.flags.path) ?? cwd));
9968
10489
  const rs = remotes(root);
9969
10490
  const originUrl = rs.get("origin") ?? "";
9970
10491
  if (!originUrl.startsWith("bunshin::")) throw new Error("origin is not a Bunshin repository (run bunshin repo attach)");
@@ -10127,22 +10648,22 @@ __export(runner_exports, {
10127
10648
  setupText: () => setupText
10128
10649
  });
10129
10650
  import { spawnSync as spawnSync3 } from "node:child_process";
10130
- import fs29 from "node:fs";
10651
+ import fs30 from "node:fs";
10131
10652
  import os5 from "node:os";
10132
- import path24 from "node:path";
10653
+ import path25 from "node:path";
10133
10654
  function runnerHome(home = process.env.BUNSHIN_RUNNER_HOME || os5.homedir()) {
10134
- return path24.join(home, ".bunshin", "runner");
10655
+ return path25.join(home, ".bunshin", "runner");
10135
10656
  }
10136
10657
  function readInstalled(home) {
10137
10658
  try {
10138
- return JSON.parse(fs29.readFileSync(path24.join(runnerHome(home), "config.json"), "utf8"));
10659
+ return JSON.parse(fs30.readFileSync(path25.join(runnerHome(home), "config.json"), "utf8"));
10139
10660
  } catch {
10140
10661
  return null;
10141
10662
  }
10142
10663
  }
10143
10664
  function connection(args, cwd) {
10144
10665
  const saved = readInstalled();
10145
- const store = saved && path24.resolve(cwd).startsWith(runnerHome()) ? null : Store.discover(cwd);
10666
+ const store = saved && path25.resolve(cwd).startsWith(runnerHome()) ? null : Store.discover(cwd);
10146
10667
  const config = store?.config();
10147
10668
  const key = str5(args.flags.key) || process.env.BUNSHIN_RUNNER_KEY || process.env.BUNSHIN_API_KEY || config?.apiKey || saved?.key || "";
10148
10669
  const apiUrl = (str5(args.flags["api-url"]) || process.env.BUNSHIN_API_URL || config?.apiUrl || saved?.apiUrl || DEFAULT_API).replace(/\/$/, "");
@@ -10202,9 +10723,9 @@ async function runOnce(c, args, out, err) {
10202
10723
  const [job] = await lease(c, args);
10203
10724
  if (!job) break;
10204
10725
  const started = Date.now();
10205
- const scratch = fs29.mkdtempSync(path24.join(os5.tmpdir(), "bunshin-job-"));
10726
+ const scratch = fs30.mkdtempSync(path25.join(os5.tmpdir(), "bunshin-job-"));
10206
10727
  const res = await askJson(config, { system: job.system, user: job.prompt, schema: job.schema, enforceSchema: false, timeoutMs: 15 * 6e4, maxTokens: 16e3, cwd: scratch }).finally(
10207
- () => fs29.rmSync(scratch, { recursive: true, force: true })
10728
+ () => fs30.rmSync(scratch, { recursive: true, force: true })
10208
10729
  );
10209
10730
  const model = config.backend === "codex-cli" ? config.codexModel ?? "codex default" : config.backend === "pi-cli" ? config.piModel ?? "pi default" : config.model;
10210
10731
  if (!res.ok) {
@@ -10294,24 +10815,24 @@ function renderCheck(id, c) {
10294
10815
  }
10295
10816
  function logAnswer(entry) {
10296
10817
  try {
10297
- fs29.mkdirSync(runnerHome(), { recursive: true });
10298
- fs29.appendFileSync(path24.join(runnerHome(), "log.jsonl"), `${JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), ...entry })}
10818
+ fs30.mkdirSync(runnerHome(), { recursive: true });
10819
+ fs30.appendFileSync(path25.join(runnerHome(), "log.jsonl"), `${JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), ...entry })}
10299
10820
  `);
10300
10821
  } catch {
10301
10822
  }
10302
10823
  }
10303
10824
  function which(name) {
10304
- for (const d of [...(process.env.PATH || "").split(path24.delimiter), path24.join(os5.homedir(), ".local", "bin")]) {
10305
- if (d && fs29.existsSync(path24.join(d, name))) return path24.join(d, name);
10825
+ for (const d of [...(process.env.PATH || "").split(path25.delimiter), path25.join(os5.homedir(), ".local", "bin")]) {
10826
+ if (d && fs30.existsSync(path25.join(d, name))) return path25.join(d, name);
10306
10827
  }
10307
10828
  return null;
10308
10829
  }
10309
10830
  function scheduledCommand(backend) {
10310
- const node = path24.dirname(process.execPath);
10311
- const npx = fs29.existsSync(path24.join(node, "npx")) ? path24.join(node, "npx") : which("npx") ?? "npx";
10831
+ const node = path25.dirname(process.execPath);
10832
+ const npx = fs30.existsSync(path25.join(node, "npx")) ? path25.join(node, "npx") : which("npx") ?? "npx";
10312
10833
  const bin = BIN_OF[backend] ? which(BIN_OF[backend]) : null;
10313
- 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"])];
10314
- return { argv: [npx, "-y", PKG2, "runner", "--once"], path: dirs.join(path24.delimiter) };
10834
+ 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"])];
10835
+ return { argv: [npx, "-y", PKG2, "runner", "--once"], path: dirs.join(path25.delimiter) };
10315
10836
  }
10316
10837
  function launchdPlist(backend, everyMinutes, home = runnerHome()) {
10317
10838
  const cmd = scheduledCommand(backend);
@@ -10326,8 +10847,8 @@ function launchdPlist(backend, everyMinutes, home = runnerHome()) {
10326
10847
  <dict><key>PATH</key><string>${xml(cmd.path)}</string></dict>
10327
10848
  <key>WorkingDirectory</key><string>${xml(home)}</string>
10328
10849
  <key>StartInterval</key><integer>${everyMinutes * 60}</integer>
10329
- <key>StandardOutPath</key><string>${xml(path24.join(home, "runner.log"))}</string>
10330
- <key>StandardErrorPath</key><string>${xml(path24.join(home, "runner.log"))}</string>
10850
+ <key>StandardOutPath</key><string>${xml(path25.join(home, "runner.log"))}</string>
10851
+ <key>StandardErrorPath</key><string>${xml(path25.join(home, "runner.log"))}</string>
10331
10852
  <key>ProcessType</key><string>Background</string>
10332
10853
  <key>LowPriorityIO</key><true/>
10333
10854
  </dict>
@@ -10338,19 +10859,19 @@ function cronLine(backend, everyMinutes, home = runnerHome()) {
10338
10859
  const cmd = scheduledCommand(backend);
10339
10860
  const when = everyMinutes >= 60 ? `17 */${Math.max(1, Math.round(everyMinutes / 60))} * * *` : `*/${everyMinutes} * * * *`;
10340
10861
  const q = (v) => `'${v.replace(/'/g, `'\\''`)}'`;
10341
- return `${when} cd ${q(home)} && PATH=${q(cmd.path)} ${cmd.argv.map(q).join(" ")} >> ${q(path24.join(home, "runner.log"))} 2>&1 ${CRON_MARK}`;
10862
+ return `${when} cd ${q(home)} && PATH=${q(cmd.path)} ${cmd.argv.map(q).join(" ")} >> ${q(path25.join(home, "runner.log"))} 2>&1 ${CRON_MARK}`;
10342
10863
  }
10343
10864
  function launchAgentsDir(opts) {
10344
- return opts.launchAgents ?? path24.join(process.env.BUNSHIN_RUNNER_HOME || os5.homedir(), "Library", "LaunchAgents");
10865
+ return opts.launchAgents ?? path25.join(process.env.BUNSHIN_RUNNER_HOME || os5.homedir(), "Library", "LaunchAgents");
10345
10866
  }
10346
10867
  function installSchedule(backend, everyMinutes, opts = {}) {
10347
10868
  const platform = opts.platform ?? process.platform;
10348
10869
  const run2 = opts.run ?? realRun;
10349
10870
  if (platform === "darwin") {
10350
10871
  const dir2 = launchAgentsDir(opts);
10351
- const plist = path24.join(dir2, `${LAUNCHD_LABEL}.plist`);
10352
- fs29.mkdirSync(dir2, { recursive: true });
10353
- fs29.writeFileSync(plist, launchdPlist(backend, everyMinutes));
10872
+ const plist = path25.join(dir2, `${LAUNCHD_LABEL}.plist`);
10873
+ fs30.mkdirSync(dir2, { recursive: true });
10874
+ fs30.writeFileSync(plist, launchdPlist(backend, everyMinutes));
10354
10875
  const domain = `gui/${process.getuid?.() ?? 501}`;
10355
10876
  run2("launchctl", ["bootout", `${domain}/${LAUNCHD_LABEL}`]);
10356
10877
  const r = run2("launchctl", ["bootstrap", domain, plist]);
@@ -10370,10 +10891,10 @@ function removeSchedule(opts = {}) {
10370
10891
  const platform = opts.platform ?? process.platform;
10371
10892
  const run2 = opts.run ?? realRun;
10372
10893
  if (platform === "darwin") {
10373
- const plist = path24.join(launchAgentsDir(opts), `${LAUNCHD_LABEL}.plist`);
10894
+ const plist = path25.join(launchAgentsDir(opts), `${LAUNCHD_LABEL}.plist`);
10374
10895
  run2("launchctl", ["bootout", `gui/${process.getuid?.() ?? 501}/${LAUNCHD_LABEL}`]);
10375
- if (!fs29.existsSync(plist)) return "no schedule";
10376
- fs29.rmSync(plist, { force: true });
10896
+ if (!fs30.existsSync(plist)) return "no schedule";
10897
+ fs30.rmSync(plist, { force: true });
10377
10898
  return `removed ${plist}`;
10378
10899
  }
10379
10900
  const current = run2("crontab", ["-l"]);
@@ -10400,10 +10921,10 @@ async function install(args, cwd, out, err, opts = {}) {
10400
10921
  }
10401
10922
  const every = Math.max(15, Number(str5(args.flags.every) ?? 60) || 60);
10402
10923
  const home = runnerHome();
10403
- fs29.mkdirSync(home, { recursive: true, mode: 448 });
10924
+ fs30.mkdirSync(home, { recursive: true, mode: 448 });
10404
10925
  const saved = { apiUrl: c.apiUrl, key: c.key, backend, ...config.model && str5(args.flags.model) ? { model: config.model } : {}, name: c.name, every };
10405
- fs29.writeFileSync(path24.join(home, "config.json"), JSON.stringify(saved, null, 2) + "\n", { mode: 384 });
10406
- fs29.chmodSync(path24.join(home, "config.json"), 384);
10926
+ fs30.writeFileSync(path25.join(home, "config.json"), JSON.stringify(saved, null, 2) + "\n", { mode: 384 });
10927
+ fs30.chmodSync(path25.join(home, "config.json"), 384);
10407
10928
  let schedule;
10408
10929
  try {
10409
10930
  schedule = installSchedule(backend, every, opts);
@@ -10416,7 +10937,7 @@ Run it yourself: npx -y ${PKG2} runner --once
10416
10937
  out(`\u2713 Runner "${c.name}" answers ${c.apiUrl}'s model jobs with ${BACKEND_NAME[backend] ?? backend} on this computer.
10417
10938
  `);
10418
10939
  out(schedule.kind === "none" ? ` No scheduler here: run \`npx -y ${PKG2} runner --once\` on a schedule yourself.
10419
- ` : ` Every ${every} minutes while this computer is on (${schedule.kind}). Log: ${path24.join(home, "runner.log")}
10940
+ ` : ` Every ${every} minutes while this computer is on (${schedule.kind}). Log: ${path25.join(home, "runner.log")}
10420
10941
  `);
10421
10942
  out(` Stop: npx -y ${PKG2} runner uninstall
10422
10943
  `);
@@ -10433,10 +10954,10 @@ Answering what waits now\u2026
10433
10954
  function uninstall(out, opts = {}) {
10434
10955
  out(`${removeSchedule(opts)}
10435
10956
  `);
10436
- const file = path24.join(runnerHome(), "config.json");
10437
- if (fs29.existsSync(file)) {
10438
- fs29.rmSync(file, { force: true });
10439
- out(`removed ${file} (revoke the key in the console: Agent keys)
10957
+ const file2 = path25.join(runnerHome(), "config.json");
10958
+ if (fs30.existsSync(file2)) {
10959
+ fs30.rmSync(file2, { force: true });
10960
+ out(`removed ${file2} (revoke the key in the console: Agent keys)
10440
10961
  `);
10441
10962
  }
10442
10963
  return 0;
@@ -10610,17 +11131,17 @@ async function cmdRunner(args, cwd, out, err, opts = {}) {
10610
11131
  }
10611
11132
  const cmd = invocation();
10612
11133
  const text2 = renderJob(job, cmd);
10613
- const file = str5(args.flags.out);
10614
- if (!file) {
11134
+ const file2 = str5(args.flags.out);
11135
+ if (!file2) {
10615
11136
  out(text2);
10616
11137
  return 0;
10617
11138
  }
10618
- fs29.writeFileSync(file, text2, { mode: 384 });
11139
+ fs30.writeFileSync(file2, text2, { mode: 384 });
10619
11140
  const left = Math.round((Date.parse(job.leaseUntil) - Date.now()) / 6e4);
10620
11141
  out(
10621
11142
  [
10622
11143
  `JOB ${job.id} (${job.kind}), attempt ${job.attempts}, answer before ${job.leaseUntil} (${left} min left)`,
10623
- `written to ${file}: ${text2.split("\n").length.toLocaleString("en")} lines`,
11144
+ `written to ${file2}: ${text2.split("\n").length.toLocaleString("en")} lines`,
10624
11145
  `size and effort: ${effortOf(job)}`,
10625
11146
  ...jobIndex(text2).map((l) => ` ${l}`),
10626
11147
  `when done: ${cmd} runner validate ${job.id} <answer.json> && ${cmd} runner submit ${job.id} <answer.json>`,
@@ -10631,18 +11152,18 @@ async function cmdRunner(args, cwd, out, err, opts = {}) {
10631
11152
  }
10632
11153
  if (sub === "validate" || sub === "check") {
10633
11154
  const id = args._[2];
10634
- const file = args._[3] ?? "-";
11155
+ const file2 = args._[3] ?? "-";
10635
11156
  if (!id) throw new Error("usage: bunshin runner validate <job id> <file|->");
10636
- const text2 = file === "-" ? fs29.readFileSync(0, "utf8") : fs29.readFileSync(file, "utf8");
11157
+ const text2 = file2 === "-" ? fs30.readFileSync(0, "utf8") : fs30.readFileSync(file2, "utf8");
10637
11158
  const r = await call(c, "POST", `/jobs/${id}/check`, { answer: text2, runner: c.name }, 12e4);
10638
11159
  out(renderCheck(id, r.body));
10639
11160
  return r.body.ok ? 0 : 1;
10640
11161
  }
10641
11162
  if (sub === "submit") {
10642
11163
  const id = args._[2];
10643
- const file = args._[3] ?? "-";
11164
+ const file2 = args._[3] ?? "-";
10644
11165
  if (!id) throw new Error("usage: bunshin runner submit <job id> <file|-> [--force]");
10645
- const text2 = file === "-" ? fs29.readFileSync(0, "utf8") : fs29.readFileSync(file, "utf8");
11166
+ const text2 = file2 === "-" ? fs30.readFileSync(0, "utf8") : fs30.readFileSync(file2, "utf8");
10646
11167
  const check = await call(c, "POST", `/jobs/${id}/check`, { answer: text2, runner: c.name }, 12e4).catch(() => null);
10647
11168
  if (check?.body && (check.status < 400 || check.body.problems)) {
10648
11169
  out(renderCheck(id, check.body));
@@ -10666,7 +11187,7 @@ async function cmdRunner(args, cwd, out, err, opts = {}) {
10666
11187
  const since = Date.parse(str5(args.flags.since) ?? "") || Date.now() - 12 * 36e5;
10667
11188
  const entries = (() => {
10668
11189
  try {
10669
- 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);
11190
+ 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);
10670
11191
  } catch {
10671
11192
  return [];
10672
11193
  }
@@ -10736,8 +11257,8 @@ var init_runner = __esm({
10736
11257
 
10737
11258
  // src/v2/importer.ts
10738
11259
  import { execFileSync as execFileSync6 } from "node:child_process";
10739
- import fs30 from "node:fs";
10740
- import path25 from "node:path";
11260
+ import fs31 from "node:fs";
11261
+ import path26 from "node:path";
10741
11262
  function rewriteRepoPaths(text2, repoName2, pack) {
10742
11263
  const re = new RegExp(`(?<=^|[\\s\`'"(=:])(?:~|\\$\\{?[A-Za-z_][A-Za-z0-9_]*\\}?)?(?:/[\\w.@+-]+)*/${escapeRe(repoName2)}(?=[/\\s\`'")\\]]|[.,;:](?:\\s|$)|$)`, "gm");
10743
11264
  return text2.replace(re, `~/.bunshin/library/${pack}`);
@@ -10776,7 +11297,7 @@ function buildDocs(files, opts) {
10776
11297
  const main2 = `${dir2}/SKILL.md`;
10777
11298
  const text2 = rw(files.get(main2).content);
10778
11299
  const fm = frontmatterDescription(text2);
10779
- const name = path25.posix.basename(dir2);
11300
+ const name = path26.posix.basename(dir2);
10780
11301
  const bundle = {};
10781
11302
  for (const p of all.filter((x) => x.startsWith(`${dir2}/`))) {
10782
11303
  claimed.add(p);
@@ -10874,22 +11395,22 @@ function isGitRepo(root) {
10874
11395
  function workingTreeFiles(root) {
10875
11396
  const out = /* @__PURE__ */ new Map();
10876
11397
  const list2 = isGitRepo(root) ? git4(root, ["ls-files", "-z"]).split("\0").filter(Boolean) : (function walk(dir2, base = "") {
10877
- return fs30.readdirSync(dir2, { withFileTypes: true }).flatMap((e) => {
11398
+ return fs31.readdirSync(dir2, { withFileTypes: true }).flatMap((e) => {
10878
11399
  if (e.name === ".git" || e.name === "node_modules") return [];
10879
11400
  const rel = base ? `${base}/${e.name}` : e.name;
10880
- return e.isDirectory() ? walk(path25.join(dir2, e.name), rel) : e.isFile() ? [rel] : [];
11401
+ return e.isDirectory() ? walk(path26.join(dir2, e.name), rel) : e.isFile() ? [rel] : [];
10881
11402
  });
10882
11403
  })(root);
10883
11404
  for (const rel of list2) {
10884
- const abs = path25.join(root, rel);
11405
+ const abs = path26.join(root, rel);
10885
11406
  let buf;
10886
11407
  try {
10887
- buf = fs30.readFileSync(abs);
11408
+ buf = fs31.readFileSync(abs);
10888
11409
  } catch {
10889
11410
  continue;
10890
11411
  }
10891
11412
  if (!isText(buf)) continue;
10892
- const exec = (fs30.statSync(abs).mode & 73) !== 0;
11413
+ const exec = (fs31.statSync(abs).mode & 73) !== 0;
10893
11414
  out.set(rel, { content: buf.toString("utf8"), ...exec ? { mode: "x" } : {} });
10894
11415
  }
10895
11416
  return out;
@@ -10923,7 +11444,7 @@ function diffDocs(prev, next) {
10923
11444
  return { docs: next.filter((d) => before.get(d.path) !== fingerprint(d)), removed: [...before.keys()].filter((p) => !after.has(p)) };
10924
11445
  }
10925
11446
  function readSkillSystem(root, opts) {
10926
- const repoName2 = path25.basename(path25.resolve(root));
11447
+ const repoName2 = path26.basename(path26.resolve(root));
10927
11448
  const build = (files2) => buildDocs(files2, { pack: opts.pack, repoName: repoName2, ...opts.rewrite === false ? { rewrite: false } : {} });
10928
11449
  const tree = build(workingTreeFiles(root));
10929
11450
  if (!opts.history || !isGitRepo(root)) return { versions: [{ summary: `import ${opts.pack}`, docs: tree, removed: [], complete: true }], docs: tree };
@@ -11000,7 +11521,7 @@ var init_importer = __esm({
11000
11521
  escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
11001
11522
  looksGenerated = (text2) => /generated by|do not edit( by hand)?/i.test(text2.slice(0, 600));
11002
11523
  isStopHook = (text2) => /"decision"\s*:\s*"block"|decision.{0,4}block/.test(text2) && /REASON=/.test(text2);
11003
- isUpdateHook = (p, text2) => /auto-?update/i.test(path25.basename(p)) || /git (pull|fetch)/.test(text2) && /SessionStart|session start/i.test(text2);
11524
+ isUpdateHook = (p, text2) => /auto-?update/i.test(path26.basename(p)) || /git (pull|fetch)/.test(text2) && /SessionStart|session start/i.test(text2);
11004
11525
  fingerprint = (d) => JSON.stringify(d);
11005
11526
  REWRITE_SYSTEM = `You adapt a company's skill documents after its skill system moved into Bunshin.
11006
11527
 
@@ -11036,8 +11557,8 @@ __export(skills_exports, {
11036
11557
  cmdSkill: () => cmdSkill,
11037
11558
  parsePin: () => parsePin
11038
11559
  });
11039
- import fs31 from "node:fs";
11040
- import path26 from "node:path";
11560
+ import fs32 from "node:fs";
11561
+ import path27 from "node:path";
11041
11562
  function requireOnline(store, what) {
11042
11563
  if (!canCall(store.config())) throw new Error(`${what} needs the hosted library: run \`bunshin setup\` first`);
11043
11564
  }
@@ -11046,9 +11567,9 @@ async function cmdImport2(store, args, cwd, out, err) {
11046
11567
  err("usage: bunshin import skills <dir> [--pack <name>] [--layer org|team:<unit>] [--owner-team <unit>] [--no-history] [--dry-run] [--propose-rewrites]\n");
11047
11568
  return 1;
11048
11569
  }
11049
- const root = path26.resolve(cwd, args._[2]);
11050
- if (!fs31.existsSync(root)) throw new Error(`${root} does not exist`);
11051
- const pack = str6(args.flags.pack) ?? path26.basename(root);
11570
+ const root = path27.resolve(cwd, args._[2]);
11571
+ if (!fs32.existsSync(root)) throw new Error(`${root} does not exist`);
11572
+ const pack = str6(args.flags.pack) ?? path27.basename(root);
11052
11573
  const history = args.flags.history !== false && !bool4(args.flags["no-history"]);
11053
11574
  const read = readSkillSystem(root, { pack, history, ...str6(args.flags.since) ? { since: str6(args.flags.since) } : {} });
11054
11575
  const kinds = /* @__PURE__ */ new Map();
@@ -11083,7 +11604,7 @@ async function cmdImport2(store, args, cwd, out, err) {
11083
11604
  const propose = args.flags["propose-rewrites"];
11084
11605
  if (propose) {
11085
11606
  const only = typeof propose === "string" && propose !== "true" ? propose.split(",").map((x) => x.trim()).filter(Boolean) : [];
11086
- await proposeRewrites(store, read.docs.filter((d) => !only.length || only.some((o) => d.path.includes(o))), pack, path26.basename(root), out, err);
11607
+ await proposeRewrites(store, read.docs.filter((d) => !only.length || only.some((o) => d.path.includes(o))), pack, path27.basename(root), out, err);
11087
11608
  }
11088
11609
  out("Run `bunshin sync` on each machine (it runs at session start) to install the skills, instructions and files.\n");
11089
11610
  return 0;
@@ -11223,7 +11744,7 @@ ${report.skills} skills, ${report.references} references, ${report.errors.length
11223
11744
  }
11224
11745
  const graph = str6(args.flags.graph) ?? (bool4(args.flags.graph) ? "SKILLS-GRAPH.md" : void 0);
11225
11746
  if (graph) {
11226
- fs31.writeFileSync(path26.resolve(cwd, graph), renderSkillGraph(report));
11747
+ fs32.writeFileSync(path27.resolve(cwd, graph), renderSkillGraph(report));
11227
11748
  out(`graph written to ${graph}
11228
11749
  `);
11229
11750
  }
@@ -11245,12 +11766,138 @@ ${report.skills} skills, ${report.references} references, ${report.errors.length
11245
11766
  `);
11246
11767
  return r.errors.length ? 1 : 0;
11247
11768
  }
11769
+ case "split":
11770
+ return await splitSkill(store, args, byName(args._[2]), args._[2], out, err);
11248
11771
  default:
11249
- err(`bunshin skill: unknown subcommand "${sub}" (list, show, log, lint, push)
11772
+ err(`bunshin skill: unknown subcommand "${sub}" (list, show, log, lint, push, split)
11250
11773
  `);
11251
11774
  return 1;
11252
11775
  }
11253
11776
  }
11777
+ function splitPreview(f, sourceWords) {
11778
+ const u = f.plan.units;
11779
+ const count = (k) => u.filter((x) => x.kind === k).length;
11780
+ return [
11781
+ `# Split of \`${f.name}\` (v${f.version})`,
11782
+ "",
11783
+ `${sourceWords} words \u2192 spine ${words3(f.plan.spine.body)} words + ${u.length} atoms (${count("card")} cards, ${count("fact")} facts, ${count("rule")} rules).`,
11784
+ 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.`,
11785
+ "",
11786
+ "Edit the .json next to this file to change anything, then send it with `bunshin skill split " + f.name + " --submit`.",
11787
+ "",
11788
+ "## Spine",
11789
+ "",
11790
+ f.plan.spine.body,
11791
+ "",
11792
+ ...u.flatMap((x) => [
11793
+ `## ${x.kind}: ${x.title}`,
11794
+ "",
11795
+ `- when: ${x.when}`,
11796
+ ...x.step ? [`- step: ${x.step}`] : [],
11797
+ ...x.triggers?.length ? [`- triggers: ${x.triggers.map((t) => `${t.tool} /${t.match}/`).join(", ")}`] : [],
11798
+ ...x.from ? [`- from: ${x.from}`] : [],
11799
+ "",
11800
+ x.body,
11801
+ ""
11802
+ ]),
11803
+ ...f.coverage.missing.length ? ["## Lines in no unit", "", ...f.coverage.missing.map((l) => `- ${l}`)] : []
11804
+ ].join("\n");
11805
+ }
11806
+ async function splitSkill(store, args, skill, name, out, err) {
11807
+ if (!name) {
11808
+ err("usage: bunshin skill split <name> [--submit] [--force]\n");
11809
+ return 1;
11810
+ }
11811
+ if (!skill?.skill) throw new Error(`no skill ${name}`);
11812
+ const v2 = new V2Store(store);
11813
+ const config = store.config();
11814
+ const files = splitPaths(v2, skill.skill.name);
11815
+ const sourceWords = words3(skill.body.slice(parseFrontmatter2(skill.body).bodyStart));
11816
+ if (bool4(args.flags.submit)) {
11817
+ if (!fs32.existsSync(files.json)) throw new Error(`no split of ${skill.skill.name} yet: run \`bunshin skill split ${skill.skill.name}\` first`);
11818
+ const f2 = JSON.parse(fs32.readFileSync(files.json, "utf8"));
11819
+ 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`);
11820
+ const plan2 = parseSplit(f2.plan);
11821
+ if (!plan2) throw new Error(`${files.json} holds no spine`);
11822
+ const coverage2 = splitCoverage(skill.body, [plan2.spine, ...plan2.units]);
11823
+ if (coverage2.missing.length && !bool4(args.flags.force)) {
11824
+ for (const l of coverage2.missing.slice(0, 20)) err(` in no unit: ${l}
11825
+ `);
11826
+ 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)`);
11827
+ }
11828
+ const made = splitSuggestions(v2, config, skill, plan2);
11829
+ fs32.rmSync(files.json, { force: true });
11830
+ if (!canCall(config)) {
11831
+ out(`${made} suggestions queued (${plan2.units.length} atoms and the spine); they leave with the next sync and wait for owner review.
11832
+ `);
11833
+ return 0;
11834
+ }
11835
+ const r = await syncV2(store, { deploy: false });
11836
+ 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("; ")})` : ""}.
11837
+ `);
11838
+ return r.errors.length ? 1 : 0;
11839
+ }
11840
+ out(`Splitting ${skill.skill.name} (${sourceWords} words) into a spine and atoms; a long skill takes a few minutes\u2026
11841
+ `);
11842
+ const res = await askJson(config, {
11843
+ system: "You split agent skills into a workflow spine and atoms, losslessly. Output JSON only.",
11844
+ user: buildSplitPrompt({ name: skill.skill.name, description: skill.skill.description, body: skill.body }),
11845
+ schema: SPLIT_SCHEMA,
11846
+ maxTokens: 64e3,
11847
+ timeoutMs: 9e5
11848
+ });
11849
+ if (!res.ok) throw new Error(res.error);
11850
+ const plan = parseSplit(res.value);
11851
+ if (!plan) throw new Error("the model's answer holds no spine");
11852
+ const coverage = splitCoverage(skill.body, [plan.spine, ...plan.units]);
11853
+ const f = { skill: skill.id, name: skill.skill.name, version: skill.version, at: (/* @__PURE__ */ new Date()).toISOString(), plan, coverage };
11854
+ fs32.mkdirSync(path27.dirname(files.json), { recursive: true });
11855
+ fs32.writeFileSync(files.json, JSON.stringify(f, null, 2));
11856
+ fs32.writeFileSync(files.md, splitPreview(f, sourceWords));
11857
+ 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)`}
11858
+ `);
11859
+ out(`Read ${files.md}; edit ${files.json} if needed; then send it with \`bunshin skill split ${skill.skill.name} --submit\`.
11860
+ `);
11861
+ return 0;
11862
+ }
11863
+ function splitSuggestions(v2, config, skill, plan) {
11864
+ const ctx = contextFor(v2, config);
11865
+ const name = skill.skill.name;
11866
+ const outline = outlineOf(plan.spine.body);
11867
+ const anchorOf2 = (step) => {
11868
+ if (!step) return void 0;
11869
+ const t = step.replace(/^[§#]\s*/, "").trim().toLowerCase();
11870
+ return (outline.find((h) => h.anchor === t || h.title.toLowerCase() === t) ?? outline.find((h) => h.anchor === slugify(t)))?.anchor;
11871
+ };
11872
+ const now = (/* @__PURE__ */ new Date()).toISOString();
11873
+ 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 };
11874
+ let n = 0;
11875
+ for (const u of plan.units) {
11876
+ const step = anchorOf2(u.step);
11877
+ const s = {
11878
+ ...base,
11879
+ id: hexId("g"),
11880
+ target: { layer: skill.layer },
11881
+ 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 } : {} } },
11882
+ rationale: `split of ${name}: ${u.kind} from ${u.from ?? "the skill"}`,
11883
+ summary: `split ${name}: ${u.kind} "${u.title}"`
11884
+ };
11885
+ v2.writeSuggestion(s);
11886
+ n++;
11887
+ }
11888
+ const fm = skill.body.slice(0, parseFrontmatter2(skill.body).bodyStart);
11889
+ v2.writeSuggestion({
11890
+ ...base,
11891
+ id: hexId("g"),
11892
+ target: { sectionId: skill.id },
11893
+ op: { op: "rewrite", text: `${fm}${plan.spine.body.trim()}
11894
+ ` },
11895
+ baseVersion: skill.version,
11896
+ rationale: `split of ${name}: the skill becomes its spine; the detail moved into ${plan.units.length} atoms`,
11897
+ summary: `split ${name}: spine`
11898
+ });
11899
+ return n + 1;
11900
+ }
11254
11901
  function sinceCutoff(since) {
11255
11902
  const m = /^(\d+)\.?(day|days|week|weeks|month|months|year|years)$/.exec(since.replace(/\s+/g, ""));
11256
11903
  if (m) {
@@ -11311,12 +11958,12 @@ async function cmdLibrary(store, args, cwd, out, err) {
11311
11958
  const res = await v2api(config, "GET", "/library?limit=1");
11312
11959
  const line = `bunshin: lib@${res.version}
11313
11960
  `;
11314
- const file = str6(args.flags.write) ?? (bool4(args.flags.write) ? ".claude/skills-version" : void 0);
11315
- if (file) {
11316
- const abs = path26.resolve(cwd, file);
11317
- fs31.mkdirSync(path26.dirname(abs), { recursive: true });
11318
- fs31.writeFileSync(abs, line);
11319
- out(`${file}: ${line}`);
11961
+ const file2 = str6(args.flags.write) ?? (bool4(args.flags.write) ? ".claude/skills-version" : void 0);
11962
+ if (file2) {
11963
+ const abs = path27.resolve(cwd, file2);
11964
+ fs32.mkdirSync(path27.dirname(abs), { recursive: true });
11965
+ fs32.writeFileSync(abs, line);
11966
+ out(`${file2}: ${line}`);
11320
11967
  } else out(line);
11321
11968
  return 0;
11322
11969
  }
@@ -11325,12 +11972,12 @@ async function cmdLibrary(store, args, cwd, out, err) {
11325
11972
  const to = str6(args.flags.to);
11326
11973
  if (!to) throw new Error("--to <dir> is required");
11327
11974
  const pinFile = str6(args.flags.pin);
11328
- const pin = str6(args.flags.git) ? { git: str6(args.flags.git) } : pinFile ? parsePin(fs31.readFileSync(path26.resolve(cwd, pinFile), "utf8")) : parsePin(args._[2] ?? "");
11975
+ const pin = str6(args.flags.git) ? { git: str6(args.flags.git) } : pinFile ? parsePin(fs32.readFileSync(path27.resolve(cwd, pinFile), "utf8")) : parsePin(args._[2] ?? "");
11329
11976
  const q = pin.git ? `git=${pin.git}` : pin.version ? `version=${pin.version}` : "";
11330
11977
  if (!q) throw new Error("name a version: lib@N, --git <sha>, or --pin <file>");
11331
11978
  const snap = await v2api(config, "GET", `/library/snapshot?${q}`, void 0, { timeoutMs: 12e4 });
11332
- const dir2 = path26.resolve(cwd, to);
11333
- if (fs31.existsSync(dir2) && fs31.readdirSync(dir2).length && !bool4(args.flags.force)) throw new Error(`${dir2} is not empty (use --force)`);
11979
+ const dir2 = path27.resolve(cwd, to);
11980
+ if (fs32.existsSync(dir2) && fs32.readdirSync(dir2).length && !bool4(args.flags.force)) throw new Error(`${dir2} is not empty (use --force)`);
11334
11981
  const pack = str6(args.flags.pack);
11335
11982
  const docs = snap.sections.filter((s) => !pack || s.pack === pack);
11336
11983
  const res = materialize(docs, dir2);
@@ -11344,7 +11991,7 @@ async function cmdLibrary(store, args, cwd, out, err) {
11344
11991
  return 1;
11345
11992
  }
11346
11993
  }
11347
- var str6, bool4, skillsOf;
11994
+ var str6, bool4, skillsOf, words3, splitPaths;
11348
11995
  var init_skills = __esm({
11349
11996
  "src/v2/skills.ts"() {
11350
11997
  "use strict";
@@ -11359,6 +12006,11 @@ var init_skills = __esm({
11359
12006
  str6 = (v) => typeof v === "string" ? v : void 0;
11360
12007
  bool4 = (v) => v === true || v === "true";
11361
12008
  skillsOf = (sections) => sections.filter((s) => s.skill && (s.status === "active" || s.status === "stale"));
12009
+ words3 = (t) => t.split(/\s+/).filter(Boolean).length;
12010
+ splitPaths = (v2, name) => {
12011
+ const base = path27.join(v2.dir, "split", name.replace(/[^\w.-]/g, "_"));
12012
+ return { json: `${base}.json`, md: `${base}.md` };
12013
+ };
11362
12014
  }
11363
12015
  });
11364
12016
 
@@ -11369,27 +12021,27 @@ __export(reflect_exports, {
11369
12021
  buildLesson: () => buildLesson,
11370
12022
  runReflection: () => runReflection
11371
12023
  });
11372
- import fs32 from "node:fs";
11373
- import path27 from "node:path";
12024
+ import fs33 from "node:fs";
12025
+ import path28 from "node:path";
11374
12026
  import { createHash as createHash10 } from "node:crypto";
11375
12027
  async function runReflection(store, opts) {
11376
12028
  const empty = { lessonIds: [], used: [], missed: [], attribution: [] };
11377
- const lock = path27.join(store.root, `reflect-${createHash10("sha256").update(opts.sessionId).digest("hex")}.lock`);
12029
+ const lock = path28.join(store.root, `reflect-${createHash10("sha256").update(opts.sessionId).digest("hex")}.lock`);
11378
12030
  const deadline = Date.now() + 66e4;
11379
12031
  for (; ; ) {
11380
12032
  try {
11381
- fs32.writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 });
12033
+ fs33.writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 });
11382
12034
  break;
11383
12035
  } catch (error) {
11384
12036
  if (error.code !== "EEXIST") throw error;
11385
12037
  try {
11386
- const owner = Number(fs32.readFileSync(lock, "utf8"));
12038
+ const owner = Number(fs33.readFileSync(lock, "utf8"));
11387
12039
  if (Number.isInteger(owner) && owner > 0) {
11388
12040
  try {
11389
12041
  process.kill(owner, 0);
11390
12042
  } catch (error2) {
11391
12043
  if (error2.code === "ESRCH") {
11392
- fs32.unlinkSync(lock);
12044
+ fs33.unlinkSync(lock);
11393
12045
  continue;
11394
12046
  }
11395
12047
  }
@@ -11404,7 +12056,7 @@ async function runReflection(store, opts) {
11404
12056
  return await reflectSession(store, opts);
11405
12057
  } finally {
11406
12058
  try {
11407
- fs32.unlinkSync(lock);
12059
+ fs33.unlinkSync(lock);
11408
12060
  } catch {
11409
12061
  }
11410
12062
  }
@@ -11744,10 +12396,11 @@ __export(cli_exports, {
11744
12396
  HELP: () => HELP2,
11745
12397
  main: () => main,
11746
12398
  parseArgs: () => parseArgs,
12399
+ setupMod: () => setupMod,
11747
12400
  version: () => version
11748
12401
  });
11749
- import fs33 from "node:fs";
11750
- import path28 from "node:path";
12402
+ import fs34 from "node:fs";
12403
+ import path29 from "node:path";
11751
12404
  function parseArgs(argv) {
11752
12405
  const out = { _: [], flags: {} };
11753
12406
  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"]);
@@ -11847,7 +12500,7 @@ async function main(argv, opts = {}) {
11847
12500
  if (harness !== "codex" && harness !== "claude-code" && harness !== "pi") throw new Error("Choose your agent: bunshin setup --harness codex, claude-code, or pi.");
11848
12501
  const agent = harness === "claude-code" ? "claude" : harness;
11849
12502
  if (!executable2(agent)) throw new Error(`${agent} was not found. Install and sign in to your agent, then run setup again.`);
11850
- const prior = new Store(path28.join(cwd, ".bunshin"));
12503
+ const prior = new Store(path29.join(cwd, ".bunshin"));
11851
12504
  const existing = prior.trusted ? prior.config() : { apiUrl: "", apiKey: void 0 };
11852
12505
  const apiUrl = str7(args.flags["api-url"]);
11853
12506
  const key = bool5(args.flags["key-stdin"]) ? await new Promise((resolve, reject) => {
@@ -11876,7 +12529,7 @@ async function main(argv, opts = {}) {
11876
12529
  });
11877
12530
  if (result.config.hooks === "user" && !only && !exclude && !bool5(args.flags.all) && process.stdin.isTTY && !bool5(args.flags["key-stdin"])) {
11878
12531
  const { askSources: askSources2 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
11879
- await askSources2(new Store(path28.join(cwd, ".bunshin")), out);
12532
+ await askSources2(new Store(path29.join(cwd, ".bunshin")), out);
11880
12533
  }
11881
12534
  out(`Connected as ${result.profile.role}${result.profile.orgUnit ? ` in ${result.profile.orgUnit}` : " (company-wide)"}.
11882
12535
  `);
@@ -11894,6 +12547,7 @@ Key saved privately outside the project.
11894
12547
  `);
11895
12548
  else if (result.learnCommand?.error) out(`/learn not installed: ${result.learnCommand.error} (${result.learnCommand.file})
11896
12549
  `);
12550
+ if (harness === "claude-code" && result.hooks) out(await setupMod(result.config));
11897
12551
  if (result.hooks?.sharedWithWorktrees) out("Codex shares these hooks with the repository\u2019s linked worktrees. Each connected worktree keeps its own Bunshin store.\n");
11898
12552
  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");
11899
12553
  else if (harness === "pi" && result.hooks) out("Open Pi in this project and approve its project extension. Check it with /bunshin status.\n");
@@ -11913,7 +12567,7 @@ Key saved privately outside the project.
11913
12567
  if (cmd === "mcp") {
11914
12568
  const { runMcpServer: runMcpServer2 } = await Promise.resolve().then(() => (init_mcp(), mcp_exports));
11915
12569
  const root = str7(args.flags.root);
11916
- await runMcpServer2({ cwd, ...root ? { store: new Store(path28.resolve(root)) } : {}, version: version() });
12570
+ await runMcpServer2({ cwd, ...root ? { store: new Store(path29.resolve(root)) } : {}, version: version() });
11917
12571
  return 0;
11918
12572
  }
11919
12573
  if (cmd === "demo") {
@@ -12005,6 +12659,8 @@ Key saved privately outside the project.
12005
12659
  return await (await Promise.resolve().then(() => (init_skills(), skills_exports))).cmdSkill(store, args, cwd, out, err);
12006
12660
  case "library":
12007
12661
  return await (await Promise.resolve().then(() => (init_skills(), skills_exports))).cmdLibrary(store, args, cwd, out, err);
12662
+ case "atoms":
12663
+ return (await Promise.resolve().then(() => (init_atoms2(), atoms_exports))).cmdAtoms(store, args, out);
12008
12664
  case "ui":
12009
12665
  return await (await Promise.resolve().then(() => (init_uicmd(), uicmd_exports))).cmdUi(store, args, out, err, version());
12010
12666
  case "sources":
@@ -12025,7 +12681,7 @@ ${HELP2}`);
12025
12681
  function openStore(args, cwd) {
12026
12682
  const root = str7(args.flags.root);
12027
12683
  if (root) {
12028
- const store = new Store(path28.resolve(root));
12684
+ const store = new Store(path29.resolve(root));
12029
12685
  store.ensureLayout();
12030
12686
  return store;
12031
12687
  }
@@ -12041,7 +12697,7 @@ async function cmdInit(args, cwd, out, err) {
12041
12697
  orgId: str7(args.flags["org-id"]),
12042
12698
  userId: str7(args.flags["user-id"]),
12043
12699
  apiUrl: str7(args.flags["api-url"]),
12044
- apiKey: bool5(args.flags["key-stdin"]) ? fs33.readFileSync(0, "utf8").trim() || void 0 : str7(args.flags["api-key"]),
12700
+ apiKey: bool5(args.flags["key-stdin"]) ? fs34.readFileSync(0, "utf8").trim() || void 0 : str7(args.flags["api-key"]),
12045
12701
  scope: bool5(args.flags.global) ? "global" : str7(args.flags.scope),
12046
12702
  harness,
12047
12703
  noHooks: args.flags.hooks === false || bool5(args.flags["no-hooks"]),
@@ -12084,14 +12740,14 @@ function cmdStatus(store, args, out, v2) {
12084
12740
  const conflicts = store.listConflicts().filter((c) => c.status === "open");
12085
12741
  const metrics = store.readMetrics(void 0);
12086
12742
  const last50 = metrics?.windows?.find((w) => w.name === "last50");
12087
- 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")] : [];
12088
- const hooks = config.harness === "pi" ? hookFiles.filter((file) => {
12743
+ 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")] : [];
12744
+ const hooks = config.harness === "pi" ? hookFiles.filter((file2) => {
12089
12745
  try {
12090
- return fs33.readFileSync(file, "utf8").startsWith("// Managed by Bunshin setup.");
12746
+ return fs34.readFileSync(file2, "utf8").startsWith("// Managed by Bunshin setup.");
12091
12747
  } catch {
12092
12748
  return false;
12093
12749
  }
12094
- }).length : hookFiles.reduce((total, file) => total + hookCount(file), 0);
12750
+ }).length : hookFiles.reduce((total, file2) => total + hookCount(file2), 0);
12095
12751
  const served = lessons.reduce((n, l) => n + l.stats.served, 0);
12096
12752
  const used = lessons.reduce((n, l) => n + l.stats.used, 0);
12097
12753
  const status = {
@@ -12104,8 +12760,9 @@ function cmdStatus(store, args, out, v2) {
12104
12760
  conflictsOpen: conflicts.length,
12105
12761
  mothership: config.apiUrl ? { apiUrl: config.apiUrl, key: config.apiKey ? "set" : "missing", lastSyncAt: config.lastSyncAt ?? null } : null,
12106
12762
  llmBackend: resolveBackend(config) ?? "none (set ANTHROPIC_API_KEY or install the claude/codex CLI)",
12763
+ recallRouter: recallRouter(config),
12107
12764
  hooks: { [config.harness]: hooks },
12108
- hookFiles: hookFiles.filter((file) => fs33.existsSync(file)),
12765
+ hookFiles: hookFiles.filter((file2) => fs34.existsSync(file2)),
12109
12766
  recallQuality: last50 ? { precision: last50.precision, recall: last50.recall, f1: last50.f1, traces: last50.traces } : null,
12110
12767
  v2
12111
12768
  };
@@ -12139,6 +12796,8 @@ function cmdStatus(store, args, out, v2) {
12139
12796
  out(`mothership ${config.apiUrl ? `${config.apiUrl} (key ${config.apiKey ? "set" : "MISSING"}, last sync ${config.lastSyncAt ?? "never"})` : "local only"}
12140
12797
  `);
12141
12798
  out(`llm backend ${status.llmBackend}
12799
+ `);
12800
+ 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"}
12142
12801
  `);
12143
12802
  out(`hooks ${config.harness}: ${hooks > 0 ? `${hooks} configured` : "not detected"}${config.harness === "codex" ? " (requires Codex hook trust)" : ""}
12144
12803
  `);
@@ -12146,9 +12805,9 @@ function cmdStatus(store, args, out, v2) {
12146
12805
  `);
12147
12806
  return 0;
12148
12807
  }
12149
- function hookCount(file) {
12808
+ function hookCount(file2) {
12150
12809
  try {
12151
- const raw = JSON.parse(fs33.readFileSync(file, "utf8"));
12810
+ const raw = JSON.parse(fs34.readFileSync(file2, "utf8"));
12152
12811
  let n = 0;
12153
12812
  for (const groups of Object.values(raw.hooks ?? {})) {
12154
12813
  for (const g of groups ?? []) {
@@ -12268,7 +12927,7 @@ function cmdLessonAdd(store, args, out, err) {
12268
12927
  let content = str7(args.flags.content) ?? "";
12269
12928
  if (!content || content === "-" || args._.includes("-")) {
12270
12929
  try {
12271
- content = fs33.readFileSync(0, "utf8");
12930
+ content = fs34.readFileSync(0, "utf8");
12272
12931
  } catch {
12273
12932
  }
12274
12933
  }
@@ -12334,7 +12993,7 @@ async function cmdReflect(store, args, cwd, out, err) {
12334
12993
  }
12335
12994
  const { runReflection: runReflection2 } = await Promise.resolve().then(() => (init_reflect4(), reflect_exports));
12336
12995
  const result = await runReflection2(store, {
12337
- sessionId: str7(args.flags.session) ?? path28.basename(transcript).replace(/\.jsonl?$/, ""),
12996
+ sessionId: str7(args.flags.session) ?? path29.basename(transcript).replace(/\.jsonl?$/, ""),
12338
12997
  transcriptPath: transcript,
12339
12998
  cwd,
12340
12999
  force: bool5(args.flags.force)
@@ -12440,6 +13099,30 @@ async function cmdConflict(store, args, out, err) {
12440
13099
  function store0HasKey(store) {
12441
13100
  return !!store.config().apiKey;
12442
13101
  }
13102
+ async function setupMod(config) {
13103
+ const { uiMode: uiMode2 } = await Promise.resolve().then(() => (init_ui(), ui_exports));
13104
+ if (uiMode2(config, "claude-code") === "off" || process.env.BUNSHIN_UI_AUTOINSTALL === "0") return "";
13105
+ const { installMod: installMod2, installedModVersion: installedModVersion2, modHome: modHome2, modSource: modSource2 } = await Promise.resolve().then(() => (init_uicmd(), uicmd_exports));
13106
+ const v = version();
13107
+ if (!modSource2()) return "";
13108
+ if (installedModVersion2() === v) return `Bunshin UI: bunshin-ui ${v} is installed (a band above the prompt, /bunshin).
13109
+ `;
13110
+ try {
13111
+ fs34.mkdirSync(modHome2(), { recursive: true });
13112
+ fs34.writeFileSync(path29.join(modHome2(), `.attempted-${v}`), nowIso());
13113
+ const res = installMod2(v);
13114
+ if (res.steps.some((st) => st.ok && /plugin (install|update)/.test(st.command))) {
13115
+ return `Bunshin UI: bunshin-ui ${v} installed (a band above the prompt, /bunshin). It needs Claude Code mods on your account.
13116
+ `;
13117
+ }
13118
+ const why = res.steps.filter((st) => !st.ok).map((st) => st.output.split("\n")[0]).filter(Boolean).pop();
13119
+ return `Bunshin UI not installed${why ? `: ${why}` : ""}. It needs Claude Code 2.1.287+ with mods on your account. Try: bunshin ui install
13120
+ `;
13121
+ } catch (e) {
13122
+ return `Bunshin UI not installed: ${e instanceof Error ? e.message : String(e)}. Try: bunshin ui install
13123
+ `;
13124
+ }
13125
+ }
12443
13126
  var str7, bool5, HELP2, untrustedNote;
12444
13127
  var init_cli = __esm({
12445
13128
  "src/cli.ts"() {
@@ -12497,6 +13180,11 @@ Usage: bunshin <command> [options]
12497
13180
  tools, history) into the library; the repository can then go
12498
13181
  skill list|show <name>|log [name] [--since 3.months]|lint [--graph [file]]|push [name] [--layer L]
12499
13182
  the deployed skills; push proposes local edits / a new skill now
13183
+ skill split <name> [--submit] [--force]
13184
+ a long skill \u2192 its spine plus atoms (cards, facts, rules), checked
13185
+ lossless and written here for review; --submit sends it
13186
+ atoms [--json] atom triggers on this machine: fires, how often what they brought
13187
+ was used, and which are muted for firing without helping
12500
13188
  library version|log|status|pin [--write [file]]|checkout <lib@N> --to <dir> [--git <sha>] [--pin <file>]
12501
13189
  library versions (lib@N), history, and exact reproductions
12502
13190
  library workspace (retired: each workspace keeps its own skills and links them into
@@ -12537,7 +13225,7 @@ Global: --root <dir> (use this .bunshin store) --version --help
12537
13225
  Env: BUNSHIN_API_KEY, BUNSHIN_HARNESS, BUNSHIN_DISABLE, BUNSHIN_CHILD, BUNSHIN_CLAUDE_BIN,
12538
13226
  CLAUDE_CODE_SESSION_ID (learn / mcp session), ANTHROPIC_API_KEY (non-fork reflection)
12539
13227
  `;
12540
- 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.`;
13228
+ 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.`;
12541
13229
  }
12542
13230
  });
12543
13231