@bunshin-cc/bunshin 0.10.5 → 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.
Files changed (2) hide show
  1. package/dist/bin.js +1557 -874
  2. package/package.json +11 -10
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,11 +1830,11 @@ function globToRegExp(glob) {
1827
1830
  globCache.set(glob, out);
1828
1831
  return out;
1829
1832
  }
1830
- function normalPath(path29) {
1831
- return path29.replace(/\\/g, "/").split("/").filter((s) => s !== "" && s !== ".").join("/");
1833
+ function normalPath(path30) {
1834
+ return path30.replace(/\\/g, "/").split("/").filter((s) => s !== "" && s !== ".").join("/");
1832
1835
  }
1833
- function matchesGlob(path29, glob) {
1834
- return globToRegExp(glob.replace(/^\.\//, "")).test(normalPath(path29));
1836
+ function matchesGlob(path30, glob) {
1837
+ return globToRegExp(glob.replace(/^\.\//, "")).test(normalPath(path30));
1835
1838
  }
1836
1839
  var DEFAULT_EMBEDDERS, globCache;
1837
1840
  var init_text_index = __esm({
@@ -1922,10 +1925,10 @@ function push(sections, reader, query) {
1922
1925
  for (const s of recallable(sections, reader).filter((x) => reachesReader(x, reader))) {
1923
1926
  const triggers = [...(s.triggers ?? []).filter((t) => t.anchor), { anchor: "", paths: s.paths, entities: s.entities, skills: s.skills }];
1924
1927
  for (const t of triggers) {
1925
- const path29 = paths.find((p) => t.paths.some((g) => matchesGlob(p, g)));
1926
- const entity = path29 ? void 0 : t.entities.find((e) => entities.has(e) || text2 && text2.includes(e));
1927
- const skill = path29 || entity ? void 0 : skills.find((k) => t.skills.includes(k));
1928
- const trigger = path29 ? `path:${path29}` : entity ? `entity:${entity}` : skill ? `skill:${skill}` : "";
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}` : "";
1929
1932
  if (trigger) {
1930
1933
  hits.set(s.id, { section: s, trigger, anchor: t.anchor });
1931
1934
  break;
@@ -2040,8 +2043,8 @@ function renderSection(s, trigger, opts = {}) {
2040
2043
  return [
2041
2044
  ...head,
2042
2045
  "",
2043
- `The \`${s.skill.name}\` skill applies: ${s.skill.description}`,
2044
- `It is installed. Invoke it (Skill tool, or \`/${s.skill.name}\`) before doing this by hand${part2 ? `; the relevant part is \xA7${part2.anchor} "${part2.title}"` : ""}.`
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}")` : ""}.`
2045
2048
  ].join("\n");
2046
2049
  }
2047
2050
  if (s.body.length <= max) return [...head, "", s.body.trim()].join("\n");
@@ -2080,6 +2083,230 @@ var init_engine = __esm({
2080
2083
  }
2081
2084
  });
2082
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
+
2083
2310
  // ../core/src/v2/recall/router.ts
2084
2311
  function routerMessage(prompt, ctx, inContext2) {
2085
2312
  const lines = ["Session context:"];
@@ -2095,6 +2322,20 @@ ${prompt.slice(0, 6e3)}
2095
2322
  >>>
2096
2323
  Return the JSON line.`;
2097
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
+ }
2098
2339
  function parseRouterAnswer(text2, items, skip = []) {
2099
2340
  const m = /\{[\s\S]*\}/.exec(text2);
2100
2341
  if (!m) return null;
@@ -2116,14 +2357,15 @@ var MAX_RULES, RULES;
2116
2357
  var init_router = __esm({
2117
2358
  "../core/src/v2/recall/router.ts"() {
2118
2359
  "use strict";
2360
+ init_atoms();
2119
2361
  MAX_RULES = 3;
2120
- RULES = `You are the prompt-time recall router for an engineering team's agent library. A coding agent is about to act on the user's latest prompt. You see the prompt plus session context: the session's first prompt, recent user prompts, the agent's last reply, and the items already in the agent's context. Decide what, if anything, to inject now.
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).
2121
2363
 
2122
- - "serve": at most ONE skill or document, injected in full (long). Serve only when this prompt starts or clearly redirects work that the item is the procedure for, and it is not already in context. Follow-ups, approvals, status questions, chatter, and continuing work already under way need none.
2123
- - "rules": at most ${MAX_RULES} LESSONS (short corrections or preferences learned from this team before), injected in full. Include a lesson only when what the agent will DO in response to this prompt \u2014 including the steps the work it starts normally leads to (a ticket ends in a PR and a report; a fix ends in evidence and a merge) \u2014 is the lesson's situation, even if the user does not mention the lesson. Not for shared topic words, not for preferences that would not change the agent's next actions, not if already in context. When unsure, include none.
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.
2124
2366
  - "hints": up to 2 other possibly relevant document ids, shown as titles only.
2125
2367
 
2126
- Only use ids from the library. Output exactly one line of JSON and nothing else: {"serve": "<id or null>", "rules": ["<lesson id>", ...], "hints": ["<id>", ...]}`;
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>", ...]}`;
2127
2369
  }
2128
2370
  });
2129
2371
 
@@ -2817,17 +3059,27 @@ A lesson is read by agents on other tasks, months from now. Write the rule, not
2817
3059
 
2818
3060
  ## Where it goes
2819
3061
 
2820
- Every entry is a whole document (a skill, a spec, a policy). Prefer editing an existing document
2821
- over creating one, and aim the edit: "anchor" names the heading (from its headings list) the text
2822
- belongs under, so it lands in the right part of the document.
2823
-
2824
- Steering and approach lessons (a, e) are the exception: each is its own short lesson. Use op
2825
- "create" with kind "rule": a title naming the behaviour, a "when" naming the situations it applies
2826
- in (as the user would phrase a request there, even one that never mentions it), and a body of at
2827
- most about 120 words: the rule, why, and when it was learned. Do not append such a lesson inside a
2828
- long skill or procedure: a rule buried in a long document goes unfollowed even when the document is
2829
- loaded, and the user ends up repeating it. If a short rule in the list below already says it, append
2830
- to that rule instead. Traps, procedures and facts (b, c, d) still go into the document they belong to.
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.
2831
3083
 
2832
3084
  Library documents relevant to this session:
2833
3085
  ${index}
@@ -2874,8 +3126,10 @@ At most ${max} suggestions. Schema:
2874
3126
  "suggestions": [{"target": {"sectionId"?: string, "layer"?: string},
2875
3127
  "op": {"op": "append", "text": string, "condition"?: string, "anchor"?: string}
2876
3128
  | {"op": "replace", "find": string, "text": string, "anchor"?: string}
2877
- | {"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",
2878
3130
  "title": string, "body": string, "when": string,
3131
+ "triggers"?: [{"tool": string, "match": string}],
3132
+ "partOf"?: string, "step"?: string,
2879
3133
  "paths"?: string[], "entities"?: string[], "skills"?: string[]}}
2880
3134
  | {"op": "param", "key": string, "value": string|number|boolean}
2881
3135
  | {"op": "situation", "text": string},
@@ -2977,9 +3231,24 @@ function parseOp(raw) {
2977
3231
  const body = clean(s.body);
2978
3232
  const when = clean(s.when);
2979
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(/^[§#]/, "") : "";
2980
3238
  return {
2981
3239
  op: "create",
2982
- section: { kind, title, body, when: when || title, paths: strList(s.paths), entities: strList(s.entities).map((e) => e.toLowerCase()), skills: strList(s.skills) }
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
+ }
2983
3252
  };
2984
3253
  }
2985
3254
  case "situation": {
@@ -3011,6 +3280,10 @@ function parseReflection(raw, opts = { layers: [] }) {
3011
3280
  let sectionId = typeof t.sectionId === "string" && t.sectionId.trim() ? t.sectionId.trim() : void 0;
3012
3281
  if (op.op !== "create" && op.op !== "param" && (!sectionId || opts.knownSectionIds && !opts.knownSectionIds.has(sectionId))) continue;
3013
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
+ }
3014
3287
  const layerRaw = typeof t.layer === "string" ? t.layer.trim() : "";
3015
3288
  const layer = opts.layers.includes(layerRaw) ? layerRaw : void 0;
3016
3289
  out.push({
@@ -3046,6 +3319,7 @@ var REFLECT_MARKER, ENVIRONMENT_RECHECK_DAYS, SIGNAL_WORDS, REFLECT_SCHEMA, KIND
3046
3319
  var init_reflect = __esm({
3047
3320
  "../core/src/v2/reflect.ts"() {
3048
3321
  "use strict";
3322
+ init_atoms();
3049
3323
  init_guidelines();
3050
3324
  init_redact();
3051
3325
  init_types();
@@ -3080,7 +3354,7 @@ var init_reflect = __esm({
3080
3354
  }
3081
3355
  }
3082
3356
  };
3083
- KINDS = ["skill", "procedure", "spec", "verification", "rule", "guardrail", "reference", "tool"];
3357
+ KINDS = ["skill", "procedure", "spec", "verification", "rule", "guardrail", "reference", "tool", "fact", "card"];
3084
3358
  anchorOf = (v) => {
3085
3359
  const a = typeof v === "string" ? clean(v).replace(/^§/, "").replace(/^#/, "") : "";
3086
3360
  return a ? { anchor: a } : {};
@@ -3211,6 +3485,7 @@ var init_v2 = __esm({
3211
3485
  init_text_index();
3212
3486
  init_engine();
3213
3487
  init_router();
3488
+ init_atoms();
3214
3489
  init_reflect();
3215
3490
  init_digest();
3216
3491
  init_reflect_context();
@@ -3251,8 +3526,8 @@ import fs5 from "node:fs";
3251
3526
  function version() {
3252
3527
  for (const rel of ["../package.json", "../../package.json"]) {
3253
3528
  try {
3254
- const file = new URL(rel, import.meta.url);
3255
- 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"));
3256
3531
  if (pkg.name === "@bunshin-cc/bunshin" && pkg.version) return pkg.version;
3257
3532
  } catch {
3258
3533
  }
@@ -3322,334 +3597,52 @@ var init_api = __esm({
3322
3597
  }
3323
3598
  });
3324
3599
 
3325
- // src/v2/repo.ts
3326
- import fs6 from "node:fs";
3327
- import path5 from "node:path";
3328
- import { execFileSync } from "node:child_process";
3329
- function git(cwd, args, timeout = 1500) {
3330
- try {
3331
- return execFileSync("git", ["-C", cwd, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout, maxBuffer: 64 * 1024 * 1024 });
3332
- } catch {
3333
- return null;
3334
- }
3335
- }
3336
- function repoRoot(cwd, storeRoot) {
3337
- const key = `${cwd}
3338
- ${storeRoot ?? ""}`;
3339
- const hit = rootCache.get(key);
3340
- if (hit) return hit;
3341
- const top = git(cwd, ["rev-parse", "--show-toplevel"])?.trim();
3342
- let root = top || "";
3343
- if (!root && storeRoot && path5.basename(storeRoot) === ".bunshin") {
3344
- const parent = path5.dirname(storeRoot);
3345
- if (path5.resolve(cwd).startsWith(path5.resolve(parent))) root = parent;
3346
- }
3347
- root = root || path5.resolve(cwd);
3348
- rootCache.set(key, root);
3349
- return root;
3350
- }
3351
- function parseRemote(url) {
3352
- const clean2 = url.trim().replace(/\.git$/, "").replace(/\/+$/, "");
3353
- if (!clean2) return null;
3354
- const scp = clean2.match(/^[^@/\s]+@[^:/\s]+:(.+)$/);
3355
- const pathPart = scp ? scp[1] : (() => {
3356
- try {
3357
- return new URL(clean2).pathname;
3358
- } catch {
3359
- return clean2;
3360
- }
3361
- })();
3362
- const segs = pathPart.split("/").filter(Boolean);
3363
- if (segs.length >= 2) return `${segs[segs.length - 2]}/${segs[segs.length - 1]}`;
3364
- return segs[0] ?? null;
3365
- }
3366
- function repoName(root) {
3367
- const url = git(root, ["remote", "get-url", "origin"]);
3368
- return url && parseRemote(url) || path5.basename(root);
3369
- }
3370
- function repoCommit(root) {
3371
- return git(root, ["rev-parse", "HEAD"])?.trim() || void 0;
3372
- }
3373
- function listDocs(root) {
3374
- const listed = git(root, ["ls-files", "-co", "--exclude-standard", "-z"], 3e3);
3375
- if (listed !== null) return [...new Set(listed.split("\0").filter(Boolean).filter(isDoc))].filter((rel) => fs6.existsSync(path5.join(root, rel)) && !deployedSkill(root, rel)).sort();
3376
- const out = [];
3377
- let visited = 0;
3378
- const walk = (dir2, rel, depth) => {
3379
- if (depth > 8 || visited++ > 2e4) return;
3380
- let entries;
3381
- try {
3382
- entries = fs6.readdirSync(dir2, { withFileTypes: true });
3383
- } catch {
3384
- return;
3385
- }
3386
- for (const e of entries) {
3387
- if (e.isDirectory()) {
3388
- if (!SKIP_DIRS.has(e.name) && !fs6.existsSync(path5.join(dir2, e.name, ".git"))) walk(path5.join(dir2, e.name), rel ? `${rel}/${e.name}` : e.name, depth + 1);
3389
- } else if (e.isFile()) {
3390
- const r = rel ? `${rel}/${e.name}` : e.name;
3391
- if (isDoc(r) && !deployedSkill(root, r)) out.push(r);
3392
- }
3393
- }
3394
- };
3395
- walk(root, "", 0);
3396
- return out.sort();
3397
- }
3398
- function indexWorkingTree(v2, config, cwd, opts = {}) {
3399
- const root = repoRoot(cwd, v2.store.root);
3400
- const now = opts.now ?? Date.now();
3401
- const cached = v2.readRepoIndex(root);
3402
- const ownerTeam = config.ownerTeam || config.orgUnit || "unknown";
3403
- const source = sourceFor(root, v2.store.root);
3404
- const sameRepo = cached && cached.ownerTeam === ownerTeam && cached.format === INDEX_FORMAT;
3405
- const repo = sameRepo && cached.repo && !opts.force ? cached.repo : repoName(root);
3406
- const fresh = sameRepo && cached.repo === repo && cached.paths && cached.listedAt && now - Date.parse(cached.listedAt) < LIST_TTL_MS && !opts.force;
3407
- const paths = fresh ? cached.paths : listDocs(root);
3408
- let changed = !fresh || !sameRepo || cached.repo !== repo;
3409
- const files = {};
3410
- for (const rel of paths) {
3411
- const abs = path5.join(root, rel);
3412
- let stat;
3413
- try {
3414
- stat = fs6.statSync(abs);
3415
- } catch {
3416
- changed = true;
3417
- continue;
3418
- }
3419
- const prev = sameRepo && cached.repo === repo ? cached.files[rel] : void 0;
3420
- if (prev && prev.mtimeMs === stat.mtimeMs && prev.size === stat.size) {
3421
- files[rel] = prev;
3422
- continue;
3423
- }
3424
- changed = true;
3425
- try {
3426
- const text2 = fs6.readFileSync(abs, "utf8");
3427
- files[rel] = { mtimeMs: stat.mtimeMs, size: stat.size, sections: parseRepoDoc({ repo, path: rel, text: text2 }, { orgId: config.orgId, ownerTeam, layer: source ? sourceLayer(source) : "org" }) };
3428
- } catch {
3429
- }
3430
- }
3431
- const index = {
3432
- format: INDEX_FORMAT,
3433
- repo,
3434
- ownerTeam,
3435
- listedAt: fresh ? cached.listedAt : new Date(now).toISOString(),
3436
- paths,
3437
- files
3438
- };
3439
- if (changed) {
3440
- try {
3441
- v2.writeRepoIndex(root, index);
3442
- } catch {
3443
- }
3600
+ // ../core/src/types.ts
3601
+ var init_types2 = __esm({
3602
+ "../core/src/types.ts"() {
3603
+ "use strict";
3444
3604
  }
3445
- return { root, index, sections: Object.values(files).flatMap((f) => f.sections) };
3446
- }
3447
- function relativeToRoot(root, file, cwd = root) {
3448
- if (!file) return null;
3449
- const abs = path5.isAbsolute(file) ? file : path5.resolve(cwd, file);
3450
- let real = abs;
3451
- let realRoot = root;
3452
- try {
3453
- realRoot = fs6.realpathSync(root);
3454
- } catch {
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
+ );
3455
3617
  }
3456
- try {
3457
- real = fs6.realpathSync(abs);
3458
- } catch {
3459
- try {
3460
- real = path5.join(fs6.realpathSync(path5.dirname(abs)), path5.basename(abs));
3461
- } catch {
3462
- }
3618
+ });
3619
+
3620
+ // ../core/src/metrics.ts
3621
+ var init_metrics = __esm({
3622
+ "../core/src/metrics.ts"() {
3623
+ "use strict";
3463
3624
  }
3464
- for (const [r, f] of [
3465
- [realRoot, real],
3466
- [root, abs]
3467
- ]) {
3468
- const rel = path5.relative(r, f);
3469
- if (rel && !rel.startsWith("..") && !path5.isAbsolute(rel)) return rel.split(path5.sep).join("/");
3625
+ });
3626
+
3627
+ // ../core/src/lesson/id.ts
3628
+ var init_id = __esm({
3629
+ "../core/src/lesson/id.ts"() {
3630
+ "use strict";
3470
3631
  }
3471
- return null;
3472
- }
3473
- var DOC_NAMES, SKIP_DIRS, LIST_TTL_MS, rootCache, isDoc, deployedSkill, INDEX_FORMAT;
3474
- var init_repo = __esm({
3475
- "src/v2/repo.ts"() {
3632
+ });
3633
+
3634
+ // ../core/src/lesson/markdown.ts
3635
+ var init_markdown2 = __esm({
3636
+ "../core/src/lesson/markdown.ts"() {
3476
3637
  "use strict";
3477
- init_v22();
3478
- init_source();
3479
- DOC_NAMES = /* @__PURE__ */ new Set(["spec.md", "testing.md", "skill.md"]);
3480
- SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", "dist", ".bunshin"]);
3481
- LIST_TTL_MS = 6e4;
3482
- rootCache = /* @__PURE__ */ new Map();
3483
- isDoc = (rel) => {
3484
- const parts = rel.split("/");
3485
- if (parts.some((p) => SKIP_DIRS.has(p))) return false;
3486
- return DOC_NAMES.has(parts[parts.length - 1].toLowerCase());
3487
- };
3488
- deployedSkill = (root, rel) => /(^|\/)SKILL\.md$/i.test(rel) && fs6.existsSync(path5.join(root, path5.posix.dirname(rel), ".bunshin.json"));
3489
- INDEX_FORMAT = 2;
3490
3638
  }
3491
3639
  });
3492
3640
 
3493
- // src/v2/source.ts
3494
- var source_exports = {};
3495
- __export(source_exports, {
3496
- cwdInPool: () => cwdInPool,
3497
- inPool: () => inPool,
3498
- listFolders: () => listFolders,
3499
- projectRootFor: () => projectRootFor,
3500
- select: () => select,
3501
- sourceFor: () => sourceFor,
3502
- storeHome: () => storeHome,
3503
- topFolder: () => topFolder
3504
- });
3505
- import fs7 from "node:fs";
3506
- import path6 from "node:path";
3507
- import { execFileSync as execFileSync2 } from "node:child_process";
3508
- function storeHome(storeRoot) {
3509
- return path6.dirname(path6.resolve(storeRoot));
3510
- }
3511
- function topFolder(cwd, storeRoot) {
3512
- const rel = path6.relative(storeHome(storeRoot), path6.resolve(cwd));
3513
- if (!rel || rel.startsWith("..") || path6.isAbsolute(rel)) return "";
3514
- return rel.split(path6.sep)[0] ?? "";
3515
- }
3516
- function inPool(selection, folder) {
3517
- if (!folder || !selection) return true;
3518
- if (selection.exclude?.includes(folder)) return false;
3519
- return selection.only ? selection.only.includes(folder) : true;
3520
- }
3521
- function cwdInPool(config, cwd, storeRoot) {
3522
- return inPool(config.sources, topFolder(cwd, storeRoot));
3523
- }
3524
- function git2(cwd, args) {
3525
- try {
3526
- return execFileSync2("git", ["-C", cwd, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 1500 }).trim() || null;
3527
- } catch {
3528
- return null;
3529
- }
3530
- }
3531
- function sourceFor(cwd, storeRoot, ctx) {
3532
- if (ctx?.kind === "robot") return sourceId("robot", ctx.id);
3533
- const key = `${path6.resolve(cwd)}
3534
- ${storeRoot}`;
3535
- if (sourceCache.has(key)) return sourceCache.get(key);
3536
- const found = findSource(cwd, storeRoot);
3537
- sourceCache.set(key, found);
3538
- return found;
3539
- }
3540
- function findSource(cwd, storeRoot) {
3541
- const home = storeHome(storeRoot);
3542
- const top = git2(cwd, ["rev-parse", "--show-toplevel"]);
3543
- if (top) {
3544
- const remote = git2(top, ["remote", "get-url", "origin"]);
3545
- const named = remote ? parseRemote(remote) : null;
3546
- if (named) return sourceId("repo", named);
3547
- const rel = path6.relative(home, top);
3548
- return sourceId("folder", rel && !rel.startsWith("..") && !path6.isAbsolute(rel) ? rel.split(path6.sep).join("/") : path6.basename(top));
3549
- }
3550
- const folder = topFolder(cwd, storeRoot);
3551
- return folder ? sourceId("folder", folder) : void 0;
3552
- }
3553
- function projectRootFor(cwd, storeRoot) {
3554
- const home = storeHome(storeRoot);
3555
- const top = git2(cwd, ["rev-parse", "--show-toplevel"]);
3556
- if (top) {
3557
- const rel = path6.relative(home, top);
3558
- if (!rel.startsWith("..") && !path6.isAbsolute(rel)) return top;
3559
- }
3560
- const folder = topFolder(cwd, storeRoot);
3561
- return folder ? path6.join(home, folder) : home;
3562
- }
3563
- function listFolders(storeRoot, selection, opts = {}) {
3564
- const home = storeHome(storeRoot);
3565
- let names = [];
3566
- try {
3567
- names = fs7.readdirSync(home, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name).sort((a, b) => a.localeCompare(b));
3568
- } catch {
3569
- }
3570
- return names.map((folder) => ({
3571
- folder,
3572
- included: inPool(selection, folder),
3573
- ...opts.sources ? { source: sourceFor(path6.join(home, folder), storeRoot) } : {}
3574
- }));
3575
- }
3576
- function select(current, action, folders) {
3577
- const uniq = (xs) => [...new Set(xs)].sort((a, b) => a.localeCompare(b));
3578
- const only = current?.only;
3579
- const exclude = current?.exclude ?? [];
3580
- let next;
3581
- switch (action) {
3582
- case "all":
3583
- return void 0;
3584
- case "only":
3585
- next = { only: uniq(folders) };
3586
- break;
3587
- case "include":
3588
- next = { ...only ? { only: uniq([...only, ...folders]) } : {}, exclude: exclude.filter((f) => !folders.includes(f)) };
3589
- break;
3590
- case "exclude":
3591
- next = { ...only ? { only: only.filter((f) => !folders.includes(f)) } : {}, exclude: uniq([...exclude, ...folders]) };
3592
- break;
3593
- }
3594
- if (!next.exclude?.length) delete next.exclude;
3595
- return next.only || next.exclude ? next : void 0;
3596
- }
3597
- var sourceCache;
3598
- var init_source = __esm({
3599
- "src/v2/source.ts"() {
3600
- "use strict";
3601
- init_v22();
3602
- init_repo();
3603
- sourceCache = /* @__PURE__ */ new Map();
3604
- }
3605
- });
3606
-
3607
- // ../core/src/types.ts
3608
- var init_types2 = __esm({
3609
- "../core/src/types.ts"() {
3610
- "use strict";
3611
- }
3612
- });
3613
-
3614
- // ../core/src/gate.ts
3615
- var CURRENT_CHAT_PREFIX, ANAPHORIC_QUESTION;
3616
- var init_gate = __esm({
3617
- "../core/src/gate.ts"() {
3618
- "use strict";
3619
- CURRENT_CHAT_PREFIX = "(?:(?:so\\s+)?(?:in|within)\\s+(?:this|the)\\s+(?:chat|conversation|session)\\s*,?\\s*)?";
3620
- ANAPHORIC_QUESTION = new RegExp(
3621
- "^" + CURRENT_CHAT_PREFIX + "(?:(?:and\\s+)?(?:does|do|did|is|are|was|were|can|could|would|will|has|have|had)\\s+.*\\b(?:this|that|it|these|those|they)\\b.*|(?:and\\s+)?(?:does|do|did|is|are|was|were|can|could|would|will|has|have|had)\\b.*\\b(?:also|too|as\\s+well)\\b.*|(?:what|why|how|where|when)\\s+(?:does|do|did|is|are|was|were)\\s+(?:this|that|it|these|those|they)\\b.*|(?:can|could|would)\\s+you\\s+(?:explain|clarify|show)\\s+(?:this|that|it)\\b.*)$",
3622
- "i"
3623
- );
3624
- }
3625
- });
3626
-
3627
- // ../core/src/metrics.ts
3628
- var init_metrics = __esm({
3629
- "../core/src/metrics.ts"() {
3630
- "use strict";
3631
- }
3632
- });
3633
-
3634
- // ../core/src/lesson/id.ts
3635
- var init_id = __esm({
3636
- "../core/src/lesson/id.ts"() {
3637
- "use strict";
3638
- }
3639
- });
3640
-
3641
- // ../core/src/lesson/markdown.ts
3642
- var init_markdown2 = __esm({
3643
- "../core/src/lesson/markdown.ts"() {
3644
- "use strict";
3645
- }
3646
- });
3647
-
3648
- // ../core/src/lesson/index.ts
3649
- var init_lesson = __esm({
3650
- "../core/src/lesson/index.ts"() {
3651
- "use strict";
3652
- }
3641
+ // ../core/src/lesson/index.ts
3642
+ var init_lesson = __esm({
3643
+ "../core/src/lesson/index.ts"() {
3644
+ "use strict";
3645
+ }
3653
3646
  });
3654
3647
 
3655
3648
  // ../core/src/serve/score.ts
@@ -4132,8 +4125,8 @@ __export(store_exports, {
4132
4125
  hexId: () => hexId,
4133
4126
  normalizeSession: () => normalizeSession
4134
4127
  });
4135
- import fs8 from "node:fs";
4136
- import path7 from "node:path";
4128
+ import fs6 from "node:fs";
4129
+ import path5 from "node:path";
4137
4130
  import { createHash as createHash2, randomBytes as randomBytes3 } from "node:crypto";
4138
4131
  function hexId(prefix) {
4139
4132
  return `${prefix}_${randomBytes3(6).toString("hex")}`;
@@ -4167,12 +4160,12 @@ var init_store2 = __esm({
4167
4160
  V2Store = class {
4168
4161
  constructor(store) {
4169
4162
  this.store = store;
4170
- this.dir = path7.join(store.root, "v2");
4163
+ this.dir = path5.join(store.root, "v2");
4171
4164
  }
4172
4165
  store;
4173
4166
  dir;
4174
4167
  p(...parts) {
4175
- return path7.join(this.dir, ...parts);
4168
+ return path5.join(this.dir, ...parts);
4176
4169
  }
4177
4170
  // ── context / bundle / params ──
4178
4171
  readContext() {
@@ -4253,9 +4246,9 @@ var init_store2 = __esm({
4253
4246
  const dir2 = this.p("sessions");
4254
4247
  if (!fileExists(dir2)) return [];
4255
4248
  const out = [];
4256
- for (const f of fs8.readdirSync(dir2)) {
4249
+ for (const f of fs6.readdirSync(dir2)) {
4257
4250
  if (!f.endsWith(".json") || f === "current.json") continue;
4258
- const raw = readJson(path7.join(dir2, f), null);
4251
+ const raw = readJson(path5.join(dir2, f), null);
4259
4252
  if (raw?.sessionId) out.push(normalizeSession(raw.sessionId, raw));
4260
4253
  }
4261
4254
  return out;
@@ -4283,7 +4276,7 @@ var init_store2 = __esm({
4283
4276
  let at = raw.at;
4284
4277
  if (!at) {
4285
4278
  try {
4286
- at = fs8.statSync(this.p("outcome", `${fileSafe(sessionId)}.json`)).mtime.toISOString();
4279
+ at = fs6.statSync(this.p("outcome", `${fileSafe(sessionId)}.json`)).mtime.toISOString();
4287
4280
  } catch {
4288
4281
  at = (/* @__PURE__ */ new Date()).toISOString();
4289
4282
  }
@@ -4309,14 +4302,14 @@ var init_store2 = __esm({
4309
4302
  }
4310
4303
  /** Exclusive lock file; returns a release function, or null when another process holds it. */
4311
4304
  tryLock(name, staleMs = 10 * 6e4) {
4312
- const file = this.p("locks", `${fileSafe(name)}.lock`);
4313
- ensureDir(path7.dirname(file));
4305
+ const file2 = this.p("locks", `${fileSafe(name)}.lock`);
4306
+ ensureDir(path5.dirname(file2));
4314
4307
  for (let attempt = 0; attempt < 2; attempt++) {
4315
4308
  try {
4316
- fs8.writeFileSync(file, String(process.pid), { flag: "wx" });
4309
+ fs6.writeFileSync(file2, String(process.pid), { flag: "wx" });
4317
4310
  return () => {
4318
4311
  try {
4319
- fs8.unlinkSync(file);
4312
+ fs6.unlinkSync(file2);
4320
4313
  } catch {
4321
4314
  }
4322
4315
  };
@@ -4324,8 +4317,8 @@ var init_store2 = __esm({
4324
4317
  if (err.code !== "EEXIST") return null;
4325
4318
  let stale = false;
4326
4319
  try {
4327
- const owner = Number(fs8.readFileSync(file, "utf8"));
4328
- 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;
4329
4322
  if (age > staleMs) stale = true;
4330
4323
  else if (Number.isInteger(owner) && owner > 0) {
4331
4324
  try {
@@ -4339,7 +4332,7 @@ var init_store2 = __esm({
4339
4332
  }
4340
4333
  if (!stale) return null;
4341
4334
  try {
4342
- fs8.unlinkSync(file);
4335
+ fs6.unlinkSync(file2);
4343
4336
  } catch {
4344
4337
  }
4345
4338
  }
@@ -4356,31 +4349,447 @@ var init_store2 = __esm({
4356
4349
  const dir2 = this.p(name);
4357
4350
  if (!fileExists(dir2)) return [];
4358
4351
  const out = [];
4359
- for (const f of fs8.readdirSync(dir2)) {
4352
+ for (const f of fs6.readdirSync(dir2)) {
4360
4353
  if (!f.endsWith(".json")) continue;
4361
- const v = readJson(path7.join(dir2, f), null);
4354
+ const v = readJson(path5.join(dir2, f), null);
4362
4355
  if (v) out.push(v);
4363
4356
  }
4364
4357
  return out;
4365
4358
  }
4366
4359
  };
4367
- 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);
4368
4361
  addUnique = (list2, ...ids) => {
4369
4362
  for (const id of ids) if (id && !list2.includes(id)) list2.push(id);
4370
4363
  };
4371
4364
  }
4372
4365
  });
4373
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
+
4374
4783
  // src/v2/deploy.ts
4375
4784
  import { execFileSync as execFileSync3 } from "node:child_process";
4376
4785
  import { createHash as createHash3 } from "node:crypto";
4377
- import fs9 from "node:fs";
4786
+ import fs10 from "node:fs";
4378
4787
  import os2 from "node:os";
4379
- import path8 from "node:path";
4788
+ import path9 from "node:path";
4380
4789
  function deployWorkspace(env = process.env) {
4381
- 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);
4382
4791
  try {
4383
- 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;
4384
4793
  return typeof ws === "string" && ws ? ws : null;
4385
4794
  } catch {
4386
4795
  return null;
@@ -4389,46 +4798,46 @@ function deployWorkspace(env = process.env) {
4389
4798
  function deployPaths(env = process.env, orgId) {
4390
4799
  const home = env.BUNSHIN_DEPLOY_HOME || os2.homedir();
4391
4800
  const ws = deployWorkspace(env);
4392
- const state = path8.join(home, ".bunshin", "deploy");
4393
- const shared = { claude: path8.join(ws ?? home, ".claude", "skills"), codex: path8.join(ws ?? home, ".codex", "skills") };
4394
- const org = orgId ? path8.join(state, orgKey(orgId)) : null;
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;
4395
4804
  return {
4396
4805
  home,
4397
- claudeSkills: org ? path8.join(org, "claude-skills") : shared.claude,
4398
- codexSkills: org ? path8.join(org, "codex-skills") : shared.codex,
4399
- ...org ? { legacy: [.../* @__PURE__ */ new Set([shared.claude, shared.codex, path8.join(home, ".claude", "skills"), path8.join(home, ".codex", "skills"), path8.join(home, ".bunshin", "library")])] } : {},
4400
- claudeMd: ws ? path8.join(ws, "CLAUDE.md") : path8.join(home, ".claude", "CLAUDE.md"),
4401
- agentsMd: ws ? path8.join(ws, "AGENTS.md") : path8.join(home, ".codex", "AGENTS.md"),
4402
- library: org ? path8.join(org, "library") : path8.join(home, ".bunshin", "library"),
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"),
4403
4812
  // Pack executables are linked into one folder on PATH (shared by name; their files are per organization).
4404
- bin: path8.join(home, ".bunshin", "bin"),
4813
+ bin: path9.join(home, ".bunshin", "bin"),
4405
4814
  state
4406
4815
  };
4407
4816
  }
4408
4817
  function statePath(p, orgId) {
4409
- return path8.join(p.state, `${orgKey(orgId)}.json`);
4818
+ return path9.join(p.state, `${orgKey(orgId)}.json`);
4410
4819
  }
4411
4820
  function readState(p, orgId) {
4412
4821
  const s = readJson(statePath(p, orgId), null);
4413
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 } : {} };
4414
4823
  }
4415
- function readText(file) {
4824
+ function readText(file2) {
4416
4825
  try {
4417
- return fs9.readFileSync(file, "utf8");
4826
+ return fs10.readFileSync(file2, "utf8");
4418
4827
  } catch {
4419
4828
  return null;
4420
4829
  }
4421
4830
  }
4422
- function writeFile(file, content, mode) {
4423
- writeTextAtomic(file, content);
4831
+ function writeFile(file2, content, mode) {
4832
+ writeTextAtomic(file2, content);
4424
4833
  try {
4425
- fs9.chmodSync(file, mode === "x" ? 493 : 420);
4834
+ fs10.chmodSync(file2, mode === "x" ? 493 : 420);
4426
4835
  } catch {
4427
4836
  }
4428
4837
  }
4429
- function removeFile(file) {
4838
+ function removeFile(file2) {
4430
4839
  try {
4431
- fs9.unlinkSync(file);
4840
+ fs10.unlinkSync(file2);
4432
4841
  } catch {
4433
4842
  }
4434
4843
  }
@@ -4436,33 +4845,33 @@ function pruneDirs(dir2, stop) {
4436
4845
  let d = dir2;
4437
4846
  while (d.startsWith(stop) && d !== stop) {
4438
4847
  try {
4439
- if (fs9.readdirSync(d).length) return;
4440
- fs9.rmdirSync(d);
4848
+ if (fs10.readdirSync(d).length) return;
4849
+ fs10.rmdirSync(d);
4441
4850
  } catch {
4442
4851
  return;
4443
4852
  }
4444
- d = path8.dirname(d);
4853
+ d = path9.dirname(d);
4445
4854
  }
4446
4855
  }
4447
4856
  function listFiles(dir2, base = dir2) {
4448
4857
  let entries;
4449
4858
  try {
4450
- entries = fs9.readdirSync(dir2, { withFileTypes: true });
4859
+ entries = fs10.readdirSync(dir2, { withFileTypes: true });
4451
4860
  } catch {
4452
4861
  return [];
4453
4862
  }
4454
4863
  const out = [];
4455
4864
  for (const e of entries) {
4456
- const abs = path8.join(dir2, e.name);
4865
+ const abs = path9.join(dir2, e.name);
4457
4866
  if (e.isDirectory()) out.push(...listFiles(abs, base));
4458
- 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("/"));
4459
4868
  }
4460
4869
  return out.sort();
4461
4870
  }
4462
4871
  function childDir(root, name) {
4463
4872
  if (!name || !SAFE_NAME.test(name)) return null;
4464
- const dir2 = path8.join(root, name);
4465
- return path8.dirname(path8.resolve(dir2)) === path8.resolve(root) && insideRoot(root, dir2) ? dir2 : null;
4873
+ const dir2 = path9.join(root, name);
4874
+ return path9.dirname(path9.resolve(dir2)) === path9.resolve(root) && insideRoot(root, dir2) ? dir2 : null;
4466
4875
  }
4467
4876
  function layerRank(layer, tree) {
4468
4877
  const kind = layerKind(layer);
@@ -4543,8 +4952,8 @@ function planDeploy(bundle, p, harnesses) {
4543
4952
  }
4544
4953
  return plan;
4545
4954
  }
4546
- function readBlock(file) {
4547
- const text2 = readText(file);
4955
+ function readBlock(file2) {
4956
+ const text2 = readText(file2);
4548
4957
  if (text2 === null) return null;
4549
4958
  const start = text2.indexOf(BLOCK_BEGIN);
4550
4959
  const end = text2.indexOf(BLOCK_END);
@@ -4566,25 +4975,25 @@ ${neutralizeMarkers(d.text).replace(/\n*$/, "\n")}`),
4566
4975
  ];
4567
4976
  return parts.join("\n");
4568
4977
  }
4569
- function removeBlock(file) {
4570
- const text2 = readText(file);
4978
+ function removeBlock(file2) {
4979
+ const text2 = readText(file2);
4571
4980
  if (text2 === null) return false;
4572
4981
  const start = text2.indexOf(BLOCK_BEGIN);
4573
4982
  const end = text2.indexOf(BLOCK_END);
4574
4983
  if (start < 0 || end < start) return false;
4575
4984
  const rest = (text2.slice(0, start).replace(/\s*$/, "") + "\n" + text2.slice(end + BLOCK_END.length).replace(/^\s*/, "")).trim();
4576
- if (rest) writeTextAtomic(file, rest + "\n");
4577
- else fs9.unlinkSync(file);
4985
+ if (rest) writeTextAtomic(file2, rest + "\n");
4986
+ else fs10.unlinkSync(file2);
4578
4987
  return true;
4579
4988
  }
4580
- function writeBlock(file, block2) {
4581
- const text2 = readText(file) ?? "";
4989
+ function writeBlock(file2, block2) {
4990
+ const text2 = readText(file2) ?? "";
4582
4991
  const start = text2.indexOf(BLOCK_BEGIN);
4583
4992
  const end = text2.indexOf(BLOCK_END);
4584
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}
4585
4994
  `;
4586
4995
  if (next === text2) return false;
4587
- writeTextAtomic(file, next);
4996
+ writeTextAtomic(file2, next);
4588
4997
  return true;
4589
4998
  }
4590
4999
  function skillIndex(skills, p) {
@@ -4595,7 +5004,7 @@ function skillIndex(skills, p) {
4595
5004
  "",
4596
5005
  "When a task matches a skill below, read its SKILL.md and follow it before doing the work by hand.",
4597
5006
  "",
4598
- ...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()}`)
4599
5008
  ];
4600
5009
  return lines.join("\n");
4601
5010
  }
@@ -4644,7 +5053,7 @@ function captureDoc(c, doc, out) {
4644
5053
  for (const dir2 of doc.dirs ?? []) {
4645
5054
  for (const rel of listFiles(dir2)) {
4646
5055
  if (rel === "SKILL.md" || rel === MANIFEST || seen.has(`file:${rel}`)) continue;
4647
- const abs = path8.join(dir2, rel);
5056
+ const abs = path9.join(dir2, rel);
4648
5057
  const content = readText(abs);
4649
5058
  if (content === null || Buffer.byteLength(content) > MAX_FILE) continue;
4650
5059
  byRel.set(`file:${rel}`, { target: { abs, rel, role: "file", sha: "", ...isExecutable(abs) ? { mode: "x" } : {} }, content });
@@ -4683,18 +5092,18 @@ function captureNewSkills(c, state, roots, owned, incoming, out, layer, only) {
4683
5092
  for (const root of roots) {
4684
5093
  let names = [];
4685
5094
  try {
4686
- 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);
4687
5096
  } catch {
4688
5097
  continue;
4689
5098
  }
4690
5099
  for (const name of names) {
4691
- const dir2 = path8.join(root, name);
5100
+ const dir2 = path9.join(root, name);
4692
5101
  if (owned.has(dir2) || incoming.has(name) || only && name !== only) continue;
4693
- const skillMd = readText(path8.join(dir2, "SKILL.md"));
5102
+ const skillMd = readText(path9.join(dir2, "SKILL.md"));
4694
5103
  if (skillMd === null) continue;
4695
5104
  let born = 0;
4696
5105
  try {
4697
- const st = fs9.statSync(path8.join(dir2, "SKILL.md"));
5106
+ const st = fs10.statSync(path9.join(dir2, "SKILL.md"));
4698
5107
  born = Math.min(st.birthtimeMs || st.mtimeMs, st.mtimeMs);
4699
5108
  } catch {
4700
5109
  continue;
@@ -4703,8 +5112,8 @@ function captureNewSkills(c, state, roots, owned, incoming, out, layer, only) {
4703
5112
  const files = {};
4704
5113
  for (const rel of listFiles(dir2).filter((r) => !r.split("/").some((seg) => seg.startsWith(".")))) {
4705
5114
  if (rel === "SKILL.md" || rel === MANIFEST) continue;
4706
- const content = readText(path8.join(dir2, rel));
4707
- if (content !== null && Buffer.byteLength(content) <= MAX_FILE) files[rel] = { content, ...isExecutable(path8.join(dir2, rel)) ? { mode: "x" } : {} };
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" } : {} };
4708
5117
  }
4709
5118
  const hash = sha(JSON.stringify([skillMd, files]));
4710
5119
  if (state.created[name]?.hash === hash) continue;
@@ -4752,15 +5161,15 @@ function captureEdits(v2, config, ctx, opts = {}) {
4752
5161
  }
4753
5162
  function lockDeploy(p) {
4754
5163
  ensureDir(p.state);
4755
- const file = path8.join(p.state, ".lock");
5164
+ const file2 = path9.join(p.state, ".lock");
4756
5165
  for (let i = 0; i < 2; i++) {
4757
5166
  try {
4758
- fs9.writeFileSync(file, String(process.pid), { flag: "wx" });
4759
- return () => removeFile(file);
5167
+ fs10.writeFileSync(file2, String(process.pid), { flag: "wx" });
5168
+ return () => removeFile(file2);
4760
5169
  } catch {
4761
5170
  try {
4762
- const age = Date.now() - fs9.statSync(file).mtimeMs;
4763
- const pid = Number(readText(file));
5171
+ const age = Date.now() - fs10.statSync(file2).mtimeMs;
5172
+ const pid = Number(readText(file2));
4764
5173
  let alive = age < 12e4;
4765
5174
  if (alive && pid > 0) {
4766
5175
  try {
@@ -4770,7 +5179,7 @@ function lockDeploy(p) {
4770
5179
  }
4771
5180
  }
4772
5181
  if (alive) return null;
4773
- removeFile(file);
5182
+ removeFile(file2);
4774
5183
  } catch {
4775
5184
  }
4776
5185
  }
@@ -4826,7 +5235,7 @@ function deployLocked(v2, config, ctx, bundle, opts, p, harnesses, now) {
4826
5235
  const foreign = /* @__PURE__ */ new Set();
4827
5236
  if (d.kind === "skill" && !prev) {
4828
5237
  for (const dir2 of d.dirs ?? []) {
4829
- const cur = readText(path8.join(dir2, "SKILL.md"));
5238
+ const cur = readText(path9.join(dir2, "SKILL.md"));
4830
5239
  if (cur === null || cur === d.section.body || state.created[d.name]) continue;
4831
5240
  foreign.add(dir2);
4832
5241
  report.warnings.push(`${dir2} is not managed by Bunshin; the library's ${d.name} skill was not installed there`);
@@ -4838,7 +5247,7 @@ function deployLocked(v2, config, ctx, bundle, opts, p, harnesses, now) {
4838
5247
  targets.push({ ...t, sha: sha(neutralizeMarkers(d.section.body).replace(/\n*$/, "\n")) });
4839
5248
  continue;
4840
5249
  }
4841
- if ([...foreign].some((dir2) => t.abs.startsWith(dir2 + path8.sep))) continue;
5250
+ if ([...foreign].some((dir2) => t.abs.startsWith(dir2 + path9.sep))) continue;
4842
5251
  if (!(d.dirs ?? (d.root ? [d.root] : [])).some((r) => insideRoot(r, t.abs))) {
4843
5252
  report.warnings.push(`${t.abs} not written: it leads outside its folder`);
4844
5253
  continue;
@@ -4847,10 +5256,10 @@ function deployLocked(v2, config, ctx, bundle, opts, p, harnesses, now) {
4847
5256
  const existing = readText(t.abs);
4848
5257
  try {
4849
5258
  if (existing !== content) {
4850
- ensureDir(path8.dirname(t.abs));
5259
+ ensureDir(path9.dirname(t.abs));
4851
5260
  writeFile(t.abs, content, t.mode);
4852
5261
  report.written++;
4853
- } 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);
4854
5263
  } catch (err) {
4855
5264
  report.warnings.push(`${t.abs} not written: ${err instanceof Error ? err.message : String(err)}`);
4856
5265
  continue;
@@ -4863,19 +5272,19 @@ function deployLocked(v2, config, ctx, bundle, opts, p, harnesses, now) {
4863
5272
  const cur = readText(old.abs);
4864
5273
  if (cur !== null && sha(cur) === old.sha) {
4865
5274
  removeFile(old.abs);
4866
- 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);
4867
5276
  report.removed++;
4868
5277
  }
4869
5278
  }
4870
5279
  if (d.kind === "skill") {
4871
5280
  for (const dir2 of prev?.dirs ?? []) {
4872
5281
  if ((d.dirs ?? []).includes(dir2) || !removable(dir2)) continue;
4873
- removeFile(path8.join(dir2, MANIFEST));
4874
- pruneDirs(dir2, path8.dirname(dir2));
5282
+ removeFile(path9.join(dir2, MANIFEST));
5283
+ pruneDirs(dir2, path9.dirname(dir2));
4875
5284
  }
4876
5285
  for (const dir2 of d.dirs ?? []) {
4877
5286
  const manifest = safeJoin(dir2, MANIFEST);
4878
- 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;
4879
5288
  writeJsonAtomic(manifest, { sectionId: id, name: d.name, version: d.section.version, libraryVersion: bundle.libraryVersion ?? null, managedBy: "bunshin sync" });
4880
5289
  }
4881
5290
  report.skills++;
@@ -4900,12 +5309,12 @@ function deployLocked(v2, config, ctx, bundle, opts, p, harnesses, now) {
4900
5309
  }
4901
5310
  for (const dir2 of doc.dirs ?? []) {
4902
5311
  if (!removable(dir2)) continue;
4903
- removeFile(path8.join(dir2, MANIFEST));
4904
- pruneDirs(dir2, path8.dirname(dir2));
4905
- if (fs9.existsSync(dir2)) {
5312
+ removeFile(path9.join(dir2, MANIFEST));
5313
+ pruneDirs(dir2, path9.dirname(dir2));
5314
+ if (fs10.existsSync(dir2)) {
4906
5315
  const left = listFiles(dir2);
4907
5316
  if (left.length) report.warnings.push(`${dir2} kept: it has files Bunshin did not write`);
4908
- else pruneDirs(dir2, path8.dirname(dir2));
5317
+ else pruneDirs(dir2, path9.dirname(dir2));
4909
5318
  }
4910
5319
  }
4911
5320
  }
@@ -4921,17 +5330,17 @@ function deployLocked(v2, config, ctx, bundle, opts, p, harnesses, now) {
4921
5330
  if (d.kind === "skill") continue;
4922
5331
  for (const t of d.targets) {
4923
5332
  if (t.role === "block" || t.mode !== "x" || !/(^|\/)bin\/[^/]+$/.test(t.rel) || !owned(t.abs)) continue;
4924
- const link = path8.join(p.bin, path8.basename(t.abs));
5333
+ const link = path9.join(p.bin, path9.basename(t.abs));
4925
5334
  ensureDir(p.bin);
4926
5335
  try {
4927
- const cur = fs9.readlinkSync(link);
5336
+ const cur = fs10.readlinkSync(link);
4928
5337
  if (cur !== t.abs) {
4929
- fs9.unlinkSync(link);
4930
- fs9.symlinkSync(t.abs, link);
5338
+ fs10.unlinkSync(link);
5339
+ fs10.symlinkSync(t.abs, link);
4931
5340
  }
4932
5341
  } catch {
4933
5342
  try {
4934
- if (!fs9.existsSync(link)) fs9.symlinkSync(t.abs, link);
5343
+ if (!fs10.existsSync(link)) fs10.symlinkSync(t.abs, link);
4935
5344
  } catch {
4936
5345
  }
4937
5346
  }
@@ -4942,19 +5351,19 @@ function deployLocked(v2, config, ctx, bundle, opts, p, harnesses, now) {
4942
5351
  if (harnesses.has("claude-code")) {
4943
5352
  for (const pack of packs) {
4944
5353
  const dir2 = childDir(p.library, pack);
4945
- if (!dir2 || !insideRoot(dir2, path8.join(dir2, ".claude", "x"))) continue;
4946
- const link = path8.join(dir2, ".claude", "skills");
5354
+ if (!dir2 || !insideRoot(dir2, path9.join(dir2, ".claude", "x"))) continue;
5355
+ const link = path9.join(dir2, ".claude", "skills");
4947
5356
  try {
4948
- fs9.lstatSync(link);
4949
- if (fs9.readlinkSync(link) !== p.claudeSkills) {
4950
- fs9.unlinkSync(link);
4951
- 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);
4952
5361
  }
4953
5362
  } catch {
4954
- ensureDir(path8.dirname(link));
5363
+ ensureDir(path9.dirname(link));
4955
5364
  ensureDir(p.claudeSkills);
4956
5365
  try {
4957
- fs9.symlinkSync(p.claudeSkills, link);
5366
+ fs10.symlinkSync(p.claudeSkills, link);
4958
5367
  } catch {
4959
5368
  }
4960
5369
  }
@@ -4963,8 +5372,8 @@ function deployLocked(v2, config, ctx, bundle, opts, p, harnesses, now) {
4963
5372
  for (const old of state.links) {
4964
5373
  if (links.has(old)) continue;
4965
5374
  try {
4966
- const target = fs9.readlinkSync(old);
4967
- if (!fs9.existsSync(target)) fs9.unlinkSync(old);
5375
+ const target = fs10.readlinkSync(old);
5376
+ if (!fs10.existsSync(target)) fs10.unlinkSync(old);
4968
5377
  } catch {
4969
5378
  }
4970
5379
  }
@@ -4972,7 +5381,7 @@ function deployLocked(v2, config, ctx, bundle, opts, p, harnesses, now) {
4972
5381
  if (p.legacy) {
4973
5382
  const deployed = Object.values(next).filter((d) => d.kind === "skill" && (d.dirs ?? []).length);
4974
5383
  const layerOf = new Map(plan.skills.map((x) => [x.skill.name, x.layer]));
4975
- const roots = [.../* @__PURE__ */ new Set([...linked, ...opts.linkRoot ? [path8.resolve(opts.linkRoot)] : []])];
5384
+ const roots = [.../* @__PURE__ */ new Set([...linked, ...opts.linkRoot ? [path9.resolve(opts.linkRoot)] : []])];
4976
5385
  linked = [];
4977
5386
  for (const root of roots) {
4978
5387
  let source;
@@ -5003,13 +5412,13 @@ function materialize(sections, dir2) {
5003
5412
  const put = (rel, content, mode) => {
5004
5413
  const abs = safeJoin(dir2, rel);
5005
5414
  if (!abs) return;
5006
- ensureDir(path8.dirname(abs));
5415
+ ensureDir(path9.dirname(abs));
5007
5416
  writeFile(abs, content, mode);
5008
5417
  files++;
5009
5418
  };
5010
5419
  for (const s of sections.filter((x) => x.status === "active" || x.status === "stale")) {
5011
5420
  if (s.skill) {
5012
- 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}`;
5013
5422
  put(`${base}/SKILL.md`, s.body);
5014
5423
  for (const [rel, f] of Object.entries(s.skill.files ?? {})) put(`${base}/${rel}`, f.content, f.mode);
5015
5424
  continue;
@@ -5021,51 +5430,51 @@ function materialize(sections, dir2) {
5021
5430
  }
5022
5431
  function linkSkills(p, root, harnesses, names) {
5023
5432
  const out = { linked: 0, removed: 0, kept: false, warnings: [] };
5024
- const abs = path8.resolve(root);
5025
- if (abs === path8.resolve(p.home) || abs === path8.resolve(os2.homedir()) || !fs9.existsSync(abs)) return out;
5026
- const managed = (target) => target.startsWith(path8.resolve(p.state) + path8.sep);
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);
5027
5436
  const excluded = [];
5028
5437
  for (const h of harnesses) {
5029
5438
  const spec = LINK_DIRS[h];
5030
5439
  if (!spec) continue;
5031
- const dir2 = path8.join(abs, spec.rel);
5032
- const canonical = path8.resolve(p[spec.key]);
5033
- const want = new Set(names.filter((n) => SAFE_NAME.test(n) && fs9.existsSync(path8.join(canonical, n, "SKILL.md"))));
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"))));
5034
5443
  let entries = [];
5035
5444
  try {
5036
- entries = fs9.readdirSync(dir2, { withFileTypes: true });
5445
+ entries = fs10.readdirSync(dir2, { withFileTypes: true });
5037
5446
  } catch {
5038
5447
  }
5039
5448
  for (const e of entries) {
5040
5449
  if (!e.isSymbolicLink()) continue;
5041
- const link = path8.join(dir2, e.name);
5450
+ const link = path9.join(dir2, e.name);
5042
5451
  let target = "";
5043
5452
  try {
5044
- target = path8.resolve(dir2, fs9.readlinkSync(link));
5453
+ target = path9.resolve(dir2, fs10.readlinkSync(link));
5045
5454
  } catch {
5046
5455
  continue;
5047
5456
  }
5048
5457
  if (!managed(target)) continue;
5049
- if (want.has(e.name) && target === path8.join(canonical, e.name)) {
5458
+ if (want.has(e.name) && target === path9.join(canonical, e.name)) {
5050
5459
  want.delete(e.name);
5051
- excluded.push(path8.join(spec.rel, e.name));
5460
+ excluded.push(path9.join(spec.rel, e.name));
5052
5461
  continue;
5053
5462
  }
5054
5463
  removeFile(link);
5055
5464
  out.removed++;
5056
5465
  }
5057
5466
  for (const name of want) {
5058
- const link = path8.join(dir2, name);
5467
+ const link = path9.join(dir2, name);
5059
5468
  try {
5060
- fs9.lstatSync(link);
5469
+ fs10.lstatSync(link);
5061
5470
  out.warnings.push(`${link} is the project's own; the library's ${name} skill was not linked there`);
5062
5471
  continue;
5063
5472
  } catch {
5064
5473
  }
5065
5474
  try {
5066
5475
  ensureDir(dir2);
5067
- fs9.symlinkSync(path8.join(canonical, name), link, "dir");
5068
- excluded.push(path8.join(spec.rel, name));
5476
+ fs10.symlinkSync(path9.join(canonical, name), link, "dir");
5477
+ excluded.push(path9.join(spec.rel, name));
5069
5478
  out.linked++;
5070
5479
  } catch (err) {
5071
5480
  out.warnings.push(`${link} not linked: ${err instanceof Error ? err.message : String(err)}`);
@@ -5078,26 +5487,26 @@ function linkSkills(p, root, harnesses, names) {
5078
5487
  return out;
5079
5488
  }
5080
5489
  function gitExclude(root, rels) {
5081
- if (!fs9.existsSync(path8.join(root, ".git"))) return;
5082
- let file;
5490
+ if (!fs10.existsSync(path9.join(root, ".git"))) return;
5491
+ let file2;
5083
5492
  try {
5084
- file = path8.resolve(root, execFileSync3("git", ["-C", root, "rev-parse", "--git-path", "info/exclude"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 2e3 }).trim());
5493
+ file2 = path9.resolve(root, execFileSync3("git", ["-C", root, "rev-parse", "--git-path", "info/exclude"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 2e3 }).trim());
5085
5494
  } catch {
5086
5495
  return;
5087
5496
  }
5088
- const cur = readText(file) ?? "";
5497
+ const cur = readText(file2) ?? "";
5089
5498
  const start = cur.indexOf(EXCLUDE_BEGIN);
5090
5499
  const end = start >= 0 ? cur.indexOf(EXCLUDE_END, start) : -1;
5091
5500
  const rest = start >= 0 && end >= 0 ? cur.slice(0, start) + cur.slice(end + EXCLUDE_END.length).replace(/^\n/, "") : cur;
5092
5501
  const block2 = rels.length ? `${EXCLUDE_BEGIN}
5093
- ${[...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")}
5094
5503
  ${EXCLUDE_END}
5095
5504
  ` : "";
5096
5505
  const next = block2 ? `${rest}${rest && !rest.endsWith("\n") ? "\n" : ""}${block2}` : rest;
5097
5506
  if (next === cur) return;
5098
5507
  try {
5099
- ensureDir(path8.dirname(file));
5100
- fs9.writeFileSync(file, next);
5508
+ ensureDir(path9.dirname(file2));
5509
+ fs10.writeFileSync(file2, next);
5101
5510
  } catch {
5102
5511
  }
5103
5512
  }
@@ -5109,16 +5518,16 @@ var init_deploy = __esm({
5109
5518
  init_source();
5110
5519
  init_util();
5111
5520
  init_store2();
5112
- settingsFile = (home) => path8.join(home, ".bunshin", "deploy", "settings.json");
5521
+ settingsFile = (home) => path9.join(home, ".bunshin", "deploy", "settings.json");
5113
5522
  orgKey = (orgId) => orgId.replace(/[^A-Za-z0-9._-]/g, "_") || "org";
5114
5523
  sha = (text2) => createHash3("sha256").update(text2).digest("hex");
5115
5524
  BLOCK_BEGIN = "<!-- bunshin:begin -->";
5116
5525
  BLOCK_END = "<!-- bunshin:end -->";
5117
5526
  MANIFEST = ".bunshin.json";
5118
5527
  MAX_FILE = 2 * 1024 * 1024;
5119
- isExecutable = (file) => {
5528
+ isExecutable = (file2) => {
5120
5529
  try {
5121
- return (fs9.statSync(file).mode & 73) !== 0;
5530
+ return (fs10.statSync(file2).mode & 73) !== 0;
5122
5531
  } catch {
5123
5532
  return false;
5124
5533
  }
@@ -5129,8 +5538,8 @@ var init_deploy = __esm({
5129
5538
  docMarker = (id, version2) => `<!-- bunshin:doc id=${id} v=${version2} -->`;
5130
5539
  BORN_SLACK_MS = 2e3;
5131
5540
  LINK_DIRS = {
5132
- "claude-code": { rel: path8.join(".claude", "skills"), key: "claudeSkills" },
5133
- 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" }
5134
5543
  };
5135
5544
  EXCLUDE_BEGIN = "# >>> bunshin: library skills linked here (managed by bunshin sync)";
5136
5545
  EXCLUDE_END = "# <<< bunshin";
@@ -5242,11 +5651,11 @@ var init_live = __esm({
5242
5651
  });
5243
5652
 
5244
5653
  // src/transcript.ts
5245
- import fs10 from "node:fs";
5246
- function parseTranscript(file) {
5654
+ import fs11 from "node:fs";
5655
+ function parseTranscript(file2) {
5247
5656
  let raw = "";
5248
5657
  try {
5249
- raw = fs10.readFileSync(file, "utf8");
5658
+ raw = fs11.readFileSync(file2, "utf8");
5250
5659
  } catch {
5251
5660
  return { turns: [], userMessages: 0, toolCalls: 0, toolFailures: 0 };
5252
5661
  }
@@ -5444,8 +5853,8 @@ function traceChunks(turns, maxBytes = 1e6) {
5444
5853
  if (cur) out.push(cur);
5445
5854
  return out;
5446
5855
  }
5447
- function recentContext(file, { turns = 2, maxChars = 6e3 } = {}) {
5448
- const facts = parseTranscript(file);
5856
+ function recentContext(file2, { turns = 2, maxChars = 6e3 } = {}) {
5857
+ const facts = parseTranscript(file2);
5449
5858
  const visible = facts.turns.filter((t) => t.role !== "tool");
5450
5859
  const userIdx = visible.map((t, i) => t.role === "user" ? i : -1).filter((i) => i >= 0);
5451
5860
  const start = userIdx.length > turns ? userIdx[userIdx.length - turns] : 0;
@@ -5566,7 +5975,7 @@ var init_view = __esm({
5566
5975
  });
5567
5976
 
5568
5977
  // src/v2/apply.ts
5569
- import fs11 from "node:fs";
5978
+ import fs12 from "node:fs";
5570
5979
  function appendedText(op) {
5571
5980
  return op.condition ? `- **${op.condition}:** ${op.text.trim()}` : op.text.trim();
5572
5981
  }
@@ -5619,14 +6028,14 @@ function applyLocally(v2, view, s) {
5619
6028
  const section = s.target.sectionId ? view.byId.get(s.target.sectionId) : void 0;
5620
6029
  if (!section) return { applied: false, target: s.target.sectionId ?? "?", reason: "target section not in the local view" };
5621
6030
  if (section.storage.type === "repo") {
5622
- const file = isDoc(section.storage.path) ? containedPath(view.root, section.storage.path) : null;
6031
+ const file2 = isDoc(section.storage.path) ? containedPath(view.root, section.storage.path) : null;
5623
6032
  const ours = !view.repo || section.storage.repo === view.repo;
5624
- if (ours && file && fs11.existsSync(file)) {
5625
- const before = fs11.readFileSync(file, "utf8");
6033
+ if (ours && file2 && fs12.existsSync(file2)) {
6034
+ const before = fs12.readFileSync(file2, "utf8");
5626
6035
  const res2 = applyOpToMarkdown(before, section.storage.anchor, op);
5627
6036
  if (res2.ok) {
5628
6037
  const changed = res2.text !== before;
5629
- if (changed) fs11.writeFileSync(file, res2.text);
6038
+ if (changed) fs12.writeFileSync(file2, res2.text);
5630
6039
  const overlay2 = { ...base, kind: "working-tree", sectionId: section.id, file: section.storage.path, anchor: section.storage.anchor, changed };
5631
6040
  upsertOverlay(v2, overlay2);
5632
6041
  return { applied: true, target: describeTarget(s, view), overlay: overlay2 };
@@ -5643,11 +6052,11 @@ function applyLocally(v2, view, s) {
5643
6052
  function revertWorkingTree(root, o) {
5644
6053
  if (o.changed === false) return { reverted: false, reason: "edit was a no-op" };
5645
6054
  if (!o.file) return { reverted: false, reason: "no file" };
5646
- const file = containedPath(root, o.file);
5647
- if (!file) return { reverted: false, reason: "path outside the repository" };
6055
+ const file2 = containedPath(root, o.file);
6056
+ if (!file2) return { reverted: false, reason: "path outside the repository" };
5648
6057
  let text2;
5649
6058
  try {
5650
- text2 = fs11.readFileSync(file, "utf8");
6059
+ text2 = fs12.readFileSync(file2, "utf8");
5651
6060
  } catch {
5652
6061
  return { reverted: false, reason: "file missing" };
5653
6062
  }
@@ -5667,7 +6076,7 @@ ${appendedText(o.op)}`;
5667
6076
  if (once(text2, o.op.text) >= 0 && !text2.includes(o.op.find)) next = text2.replace(o.op.text, o.op.find);
5668
6077
  }
5669
6078
  if (next === null) return { reverted: false, reason: "file changed since the trial edit" };
5670
- fs11.writeFileSync(file, next);
6079
+ fs12.writeFileSync(file2, next);
5671
6080
  return { reverted: true };
5672
6081
  }
5673
6082
  function revertParam(v2, o) {
@@ -5741,7 +6150,7 @@ var init_apply = __esm({
5741
6150
  });
5742
6151
 
5743
6152
  // src/v2/signals.ts
5744
- import fs12 from "node:fs";
6153
+ import fs13 from "node:fs";
5745
6154
  function isCorrection(text2) {
5746
6155
  const t = text2.trim().slice(0, 600);
5747
6156
  return !!t && CORRECTION_RE.test(t);
@@ -5758,16 +6167,16 @@ function codeOf(input) {
5758
6167
  if (v && typeof v === "object" && typeof v.code === "string") return v.code;
5759
6168
  return null;
5760
6169
  }
5761
- function scanTranscript(file) {
6170
+ function scanTranscript(file2) {
5762
6171
  const empty = { facts: { turns: [], userMessages: 0, toolCalls: 0, toolFailures: 0 }, snippets: [] };
5763
- if (!file) return empty;
6172
+ if (!file2) return empty;
5764
6173
  let raw;
5765
6174
  try {
5766
- raw = fs12.readFileSync(file, "utf8");
6175
+ raw = fs13.readFileSync(file2, "utf8");
5767
6176
  } catch {
5768
6177
  return empty;
5769
6178
  }
5770
- const out = { facts: parseTranscript(file), snippets: [] };
6179
+ const out = { facts: parseTranscript(file2), snippets: [] };
5771
6180
  for (const text2 of raw.split("\n")) {
5772
6181
  if (!text2.trim()) continue;
5773
6182
  let line;
@@ -5847,8 +6256,28 @@ var init_signals = __esm({
5847
6256
  });
5848
6257
 
5849
6258
  // src/v2/ui.ts
5850
- import fs13 from "node:fs";
5851
- 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";
5852
6281
  function feedPath(v2, sessionId) {
5853
6282
  return v2.p("ui", `${safe(sessionId)}.json`);
5854
6283
  }
@@ -5864,7 +6293,7 @@ function emptyFeed(v2, sessionId, now) {
5864
6293
  }
5865
6294
  function cliArgv() {
5866
6295
  const entry = process.argv[1];
5867
- return entry ? [process.execPath, path9.resolve(entry)] : ["bunshin"];
6296
+ return entry ? [process.execPath, path10.resolve(entry)] : ["bunshin"];
5868
6297
  }
5869
6298
  function updateFeed(v2, sessionId, patch, now = (/* @__PURE__ */ new Date()).toISOString()) {
5870
6299
  if (!sessionId || sessionId === "no-session") return null;
@@ -5879,7 +6308,7 @@ function updateFeed(v2, sessionId, patch, now = (/* @__PURE__ */ new Date()).toI
5879
6308
  f.cli = cliArgv();
5880
6309
  f.served = f.served.slice(0, MAX_SERVED);
5881
6310
  f.events = f.events.slice(-MAX_EVENTS);
5882
- fs13.mkdirSync(path9.dirname(feedPath(v2, sessionId)), { recursive: true });
6311
+ fs14.mkdirSync(path10.dirname(feedPath(v2, sessionId)), { recursive: true });
5883
6312
  writeJsonAtomic(feedPath(v2, sessionId), f);
5884
6313
  return f;
5885
6314
  } catch {
@@ -5980,16 +6409,16 @@ function latestFeed(v2) {
5980
6409
  const dir2 = v2.p("ui");
5981
6410
  let best = null;
5982
6411
  try {
5983
- for (const f2 of fs13.readdirSync(dir2)) {
6412
+ for (const f2 of fs14.readdirSync(dir2)) {
5984
6413
  if (!f2.endsWith(".json") || f2.endsWith(".mod.json")) continue;
5985
- const m = fs13.statSync(path9.join(dir2, f2)).mtimeMs;
6414
+ const m = fs14.statSync(path10.join(dir2, f2)).mtimeMs;
5986
6415
  if (!best || m > best.m) best = { f: f2, m };
5987
6416
  }
5988
6417
  } catch {
5989
6418
  return null;
5990
6419
  }
5991
6420
  if (!best) return null;
5992
- const f = readJson(path9.join(dir2, best.f), null);
6421
+ const f = readJson(path10.join(dir2, best.f), null);
5993
6422
  return f && f.v === UI_FEED_VERSION ? f : null;
5994
6423
  }
5995
6424
  var UI_FEED_VERSION, MAX_SERVED, MAX_EVENTS, MOD_FRESH_MS, DEFAULT_MODES;
@@ -6014,8 +6443,8 @@ __export(sync_exports, {
6014
6443
  syncV2: () => syncV2,
6015
6444
  uploadIndex: () => uploadIndex
6016
6445
  });
6017
- import fs14 from "node:fs";
6018
- import path10 from "node:path";
6446
+ import fs15 from "node:fs";
6447
+ import path11 from "node:path";
6019
6448
  function episodePayload(e) {
6020
6449
  const { orgId: _o, uploaded: _u, servedReported: _s, reportedServed: _rs, reportedLoaded: _rl, transcriptPath: _tp, ...rest } = e;
6021
6450
  void _o, _u, _s, _rs, _rl, _tp;
@@ -6048,15 +6477,15 @@ function markForRetrace(v2, { days = 30, now = Date.now() } = {}) {
6048
6477
  for (const e of v2.listEpisodes()) {
6049
6478
  if (e.upload === "header-only" || e.cliVersion || !e.transcript) continue;
6050
6479
  if (now - Date.parse(e.endedAt || e.startedAt) > days * 864e5) continue;
6051
- const file = e.transcriptPath ?? v2.readSession(e.sessionId)?.transcriptPath;
6052
- if (!file || !fs14.existsSync(file)) {
6480
+ const file2 = e.transcriptPath ?? v2.readSession(e.sessionId)?.transcriptPath;
6481
+ if (!file2 || !fs15.existsSync(file2)) {
6053
6482
  missing++;
6054
6483
  continue;
6055
6484
  }
6056
- const turns = e.turns ?? parseTranscript(file).turns.length;
6485
+ const turns = e.turns ?? parseTranscript(file2).turns.length;
6057
6486
  const { transcript: _t, ...rest } = e;
6058
6487
  void _t;
6059
- 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 });
6060
6489
  queued++;
6061
6490
  }
6062
6491
  return { queued, missing };
@@ -6064,7 +6493,7 @@ function markForRetrace(v2, { days = 30, now = Date.now() } = {}) {
6064
6493
  async function syncV2(store, opts = {}) {
6065
6494
  const v2 = new V2Store(store);
6066
6495
  const config = store.config();
6067
- const cwd = opts.cwd ?? path10.dirname(store.root);
6496
+ const cwd = opts.cwd ?? path11.dirname(store.root);
6068
6497
  const report = { offline: !canCall(config), uploadedEpisodes: 0, deferredTraces: 0, uploadedSuggestions: 0, trialUpdates: 0, bundle: v2.readBundle() ? "cached" : "none", settled: [], errors: [] };
6069
6498
  const deadline = Date.now() + (opts.budgetMs ?? 24e4);
6070
6499
  if (report.offline) {
@@ -6211,7 +6640,7 @@ async function uploadIndex(store, cwd, deadline = Date.now() + 3e4) {
6211
6640
  const { root, index } = indexWorkingTree(v2, config, cwd, { force: true });
6212
6641
  const docs = (index.paths ?? Object.keys(index.files)).flatMap((rel) => {
6213
6642
  try {
6214
- return [{ path: rel, text: fs14.readFileSync(path10.join(root, rel), "utf8") }];
6643
+ return [{ path: rel, text: fs15.readFileSync(path11.join(root, rel), "utf8") }];
6215
6644
  } catch {
6216
6645
  return [];
6217
6646
  }
@@ -6242,7 +6671,7 @@ var init_sync = __esm({
6242
6671
  // src/v2/reflect.ts
6243
6672
  import { spawn as spawn3 } from "node:child_process";
6244
6673
  import { createHash as createHash4 } from "node:crypto";
6245
- import fs15 from "node:fs";
6674
+ import fs16 from "node:fs";
6246
6675
  function episodeIdFor(contextId, sessionId) {
6247
6676
  return `e_${createHash4("sha256").update(`${contextId}
6248
6677
  ${sessionId}`).digest("hex").slice(0, 16)}`;
@@ -6277,7 +6706,7 @@ function runClaudeFork(sessionId, prompt, { cwd, model, timeoutMs = FORK_TIMEOUT
6277
6706
  };
6278
6707
  let child;
6279
6708
  try {
6280
- 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"] });
6281
6710
  } catch (e) {
6282
6711
  resolve({ ok: false, error: e instanceof Error ? e.message : String(e) });
6283
6712
  return;
@@ -6319,10 +6748,10 @@ function reflectionIndex(view, ids, task, focus, humanTurns = []) {
6319
6748
  } catch {
6320
6749
  }
6321
6750
  }
6322
- 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 } : {} }));
6323
6752
  }
6324
6753
  function humanTurnsOf(transcriptPath) {
6325
- if (!transcriptPath || !fs15.existsSync(transcriptPath)) return [];
6754
+ if (!transcriptPath || !fs16.existsSync(transcriptPath)) return [];
6326
6755
  try {
6327
6756
  return parseTranscript(transcriptPath).turns.filter((t) => t.role === "user" && t.text.trim()).map((t) => t.text.slice(0, 1e3));
6328
6757
  } catch {
@@ -6330,7 +6759,7 @@ function humanTurnsOf(transcriptPath) {
6330
6759
  }
6331
6760
  }
6332
6761
  function readFacts(transcriptPath) {
6333
- if (!transcriptPath || !fs15.existsSync(transcriptPath)) return null;
6762
+ if (!transcriptPath || !fs16.existsSync(transcriptPath)) return null;
6334
6763
  try {
6335
6764
  return parseTranscript(transcriptPath);
6336
6765
  } catch {
@@ -6393,7 +6822,7 @@ async function runReflectionV2(store, opts) {
6393
6822
  result.method = "fork";
6394
6823
  } else result.error = fork.error;
6395
6824
  }
6396
- if (result.method === "none" && session.transcriptPath && fs15.existsSync(session.transcriptPath)) {
6825
+ if (result.method === "none" && session.transcriptPath && fs16.existsSync(session.transcriptPath)) {
6397
6826
  const transcriptDigest = digest(facts ?? parseTranscript(session.transcriptPath), { from, maxChars: 4e4 });
6398
6827
  const res = await askJson(config, {
6399
6828
  system: "You are Bunshin's reflection pass. Follow the instructions in the user message and reply with one JSON object only.",
@@ -6522,11 +6951,11 @@ __export(route_exports, {
6522
6951
  });
6523
6952
  import { spawn as spawn4 } from "node:child_process";
6524
6953
  import { createHash as createHash5 } from "node:crypto";
6525
- import fs16 from "node:fs";
6526
- import path11 from "node:path";
6527
- function readJson2(file) {
6954
+ import fs17 from "node:fs";
6955
+ import path12 from "node:path";
6956
+ function readJson2(file2) {
6528
6957
  try {
6529
- return JSON.parse(fs16.readFileSync(file, "utf8"));
6958
+ return JSON.parse(fs17.readFileSync(file2, "utf8"));
6530
6959
  } catch {
6531
6960
  return null;
6532
6961
  }
@@ -6534,12 +6963,12 @@ function readJson2(file) {
6534
6963
  function lastReply(transcriptPath, maxBytes = 256e3) {
6535
6964
  if (!transcriptPath) return void 0;
6536
6965
  try {
6537
- const fd = fs16.openSync(transcriptPath, "r");
6966
+ const fd = fs17.openSync(transcriptPath, "r");
6538
6967
  try {
6539
- const size = fs16.fstatSync(fd).size;
6968
+ const size = fs17.fstatSync(fd).size;
6540
6969
  const len = Math.min(size, maxBytes);
6541
6970
  const buf = Buffer.alloc(len);
6542
- fs16.readSync(fd, buf, 0, len, size - len);
6971
+ fs17.readSync(fd, buf, 0, len, size - len);
6543
6972
  const lines = buf.toString("utf8").split("\n");
6544
6973
  for (let i = lines.length - 1; i >= 0; i--) {
6545
6974
  let m;
@@ -6554,7 +6983,7 @@ function lastReply(transcriptPath, maxBytes = 256e3) {
6554
6983
  if (text2.trim()) return redact2(text2.trim()).slice(0, 1500);
6555
6984
  }
6556
6985
  } finally {
6557
- fs16.closeSync(fd);
6986
+ fs17.closeSync(fd);
6558
6987
  }
6559
6988
  } catch {
6560
6989
  }
@@ -6566,9 +6995,13 @@ function promptContext(session) {
6566
6995
  const reply = lastReply(session.transcriptPath);
6567
6996
  return { ...session.task ? { first: session.task.slice(0, 1e3) } : {}, recent, ...reply ? { reply } : {} };
6568
6997
  }
6998
+ function withReply(session) {
6999
+ const reply = lastReply(session.transcriptPath);
7000
+ return reply ? { reply } : {};
7001
+ }
6569
7002
  async function routerIndex(store, v2, source) {
6570
- const file = path11.join(dir(v2), `index-${createHash5("sha256").update(source).digest("hex").slice(0, 12)}.json`);
6571
- const cached = readJson2(file);
7003
+ const file2 = path12.join(dir(v2), `index-${createHash5("sha256").update(source).digest("hex").slice(0, 12)}.json`);
7004
+ const cached = readJson2(file2);
6572
7005
  if (cached && Date.now() - Date.parse(cached.fetchedAt) < INDEX_TTL_MS) return cached;
6573
7006
  try {
6574
7007
  const res = await v2api(
@@ -6580,7 +7013,7 @@ async function routerIndex(store, v2, source) {
6580
7013
  );
6581
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() };
6582
7015
  if (!next.system) throw new Error("the server sent no index");
6583
- writeJsonAtomic(file, next);
7016
+ writeJsonAtomic(file2, next);
6584
7017
  return next;
6585
7018
  } catch (err) {
6586
7019
  if (cached) return cached;
@@ -6643,15 +7076,16 @@ async function routeJob(store, sessionId, seq) {
6643
7076
  if (!job || job.seq !== seq || job.cancelled) return null;
6644
7077
  const started = Date.parse(job.at) || Date.now();
6645
7078
  const model = config.recall.routerModel || process.env.BUNSHIN_ROUTER_MODEL || ROUTER_MODEL;
6646
- 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;
6647
7081
  const answer = { seq, at: (/* @__PURE__ */ new Date()).toISOString(), ms: Date.now() - started, ...picks };
6648
7082
  writeJsonAtomic(answerFile(v2, sessionId, seq), answer);
6649
7083
  const dense = (readJob(v2, sessionId) ?? job).dense;
6650
- v2.log("v2-router", { session: sessionId, seq, serve: answer.serve ?? null, rules: answer.rules ?? [], hint: answer.hint ?? [], ms: answer.ms, modelMs: answer.modelMs, error: answer.error, dense: dense?.serve ?? null, denseHint: dense?.hint ?? [], usage: answer.usage, costUsd: answer.costUsd });
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 });
6651
7085
  await recordStats(v2, sessionId, answer, model, indexHash);
6652
7086
  return answer;
6653
7087
  }
6654
- async function askRouter(store, v2, sessionId, model) {
7088
+ async function askRouter(store, v2, sessionId, model, kind) {
6655
7089
  const config = store.config();
6656
7090
  let indexHash;
6657
7091
  try {
@@ -6661,13 +7095,14 @@ async function askRouter(store, v2, sessionId, model) {
6661
7095
  const index = await routerIndex(store, v2, session.source ?? "");
6662
7096
  if (!/^[\w-]{1,64}$/.test(index.hash)) return { picks: { error: "the router index came back with a malformed hash" } };
6663
7097
  indexHash = index.hash;
6664
- const systemFile = path11.join(dir(v2), `system-${index.hash}.txt`);
6665
- if (!fs16.existsSync(systemFile)) fs16.writeFileSync(systemFile, index.system);
6666
- const cwd = path11.join(dir(v2), "cwd");
6667
- fs16.mkdirSync(cwd, { recursive: true });
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 });
6668
7102
  const inContext2 = session.inContext ?? [...session.loaded, ...session.pushed];
6669
7103
  const titles = new Map((v2.readBundle()?.sections ?? []).map((s) => [s.id, s.skill?.name ?? s.title]));
6670
- const message = routerMessage(session.lastPrompt, promptContext(session), inContext2.map((id) => titles.get(id)).filter((t) => !!t));
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);
6671
7106
  const res = await askClaude(systemFile, message, model, cwd);
6672
7107
  const u = res.usage ?? {};
6673
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 } : {} };
@@ -6702,7 +7137,7 @@ async function recordStats(v2, sessionId, a, model, indexHash) {
6702
7137
  add(stats.sessions[sessionId] ??= emptyTally());
6703
7138
  stats.model = model;
6704
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 } : {} };
6705
- writeJsonAtomic(path11.join(dir(v2), "stats.json"), stats);
7140
+ writeJsonAtomic(path12.join(dir(v2), "stats.json"), stats);
6706
7141
  } catch {
6707
7142
  } finally {
6708
7143
  release?.();
@@ -6710,10 +7145,10 @@ async function recordStats(v2, sessionId, a, model, indexHash) {
6710
7145
  }
6711
7146
  function sweepRouter(v2, now = Date.now()) {
6712
7147
  try {
6713
- for (const f of fs16.readdirSync(dir(v2))) {
7148
+ for (const f of fs17.readdirSync(dir(v2))) {
6714
7149
  if (!/\.(job|answer)\.json$/.test(f)) continue;
6715
- const p = path11.join(dir(v2), f);
6716
- if (now - fs16.statSync(p).mtimeMs > 864e5) fs16.rmSync(p, { force: true });
7150
+ const p = path12.join(dir(v2), f);
7151
+ if (now - fs17.statSync(p).mtimeMs > 864e5) fs17.rmSync(p, { force: true });
6717
7152
  }
6718
7153
  } catch {
6719
7154
  }
@@ -6731,16 +7166,16 @@ var init_route = __esm({
6731
7166
  ROUTER_MODEL = "claude-haiku-5-5";
6732
7167
  INDEX_TTL_MS = 10 * 6e4;
6733
7168
  CLAUDE_TIMEOUT_MS = 6e4;
6734
- dir = (v2) => path11.join(v2.dir, "router");
7169
+ dir = (v2) => path12.join(v2.dir, "router");
6735
7170
  safe2 = (id) => id.replace(/[^\w.-]/g, "_");
6736
- jobFile = (v2, session) => path11.join(dir(v2), `${safe2(session)}.job.json`);
6737
- answerFile = (v2, session, seq) => path11.join(dir(v2), `${safe2(session)}.${seq}.answer.json`);
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`);
6738
7173
  readJob = (v2, session) => readJson2(jobFile(v2, session));
6739
7174
  writeJob = (v2, session, job) => writeJsonAtomic(jobFile(v2, session), job);
6740
7175
  readAnswer = (v2, session, seq) => readJson2(answerFile(v2, session, seq));
6741
7176
  emptyTally = () => ({ calls: 0, errors: 0, costUsd: 0, input: 0, cacheRead: 0, cacheWrite: 0, output: 0, msTotal: 0 });
6742
7177
  localDay = (d = /* @__PURE__ */ new Date()) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
6743
- readStats = (v2) => readJson2(path11.join(dir(v2), "stats.json"));
7178
+ readStats = (v2) => readJson2(path12.join(dir(v2), "stats.json"));
6744
7179
  }
6745
7180
  });
6746
7181
 
@@ -6756,51 +7191,51 @@ __export(uicmd_exports, {
6756
7191
  modSource: () => modSource
6757
7192
  });
6758
7193
  import { spawnSync } from "node:child_process";
6759
- import fs17 from "node:fs";
7194
+ import fs18 from "node:fs";
6760
7195
  import os3 from "node:os";
6761
- import path12 from "node:path";
7196
+ import path13 from "node:path";
6762
7197
  import { fileURLToPath } from "node:url";
6763
7198
  function modHome(home = process.env.BUNSHIN_DEPLOY_HOME || os3.homedir()) {
6764
- return path12.join(home, ".bunshin", "claude-code-ui");
7199
+ return path13.join(home, ".bunshin", "claude-code-ui");
6765
7200
  }
6766
7201
  function modSource() {
6767
- const here = path12.dirname(fileURLToPath(import.meta.url));
6768
- for (const dir2 of [path12.join(here, "claude-code-ui"), path12.join(here, "..", "claude-code-ui"), path12.resolve(here, "../../../../adapters/claude-code-ui")]) {
6769
- if (fs17.existsSync(path12.join(dir2, ".claude-plugin", "plugin.json"))) return dir2;
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;
6770
7205
  }
6771
7206
  return null;
6772
7207
  }
6773
7208
  function installedModVersion(home) {
6774
7209
  try {
6775
- 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;
6776
7211
  } catch {
6777
7212
  return null;
6778
7213
  }
6779
7214
  }
6780
7215
  function copyDir(from, to) {
6781
- fs17.mkdirSync(to, { recursive: true });
6782
- 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 })) {
6783
7218
  if (e.name === "types" && from.endsWith(".claude-plugin")) continue;
6784
7219
  if (e.name === "node_modules") continue;
6785
- const a = path12.join(from, e.name);
6786
- const b = path12.join(to, e.name);
7220
+ const a = path13.join(from, e.name);
7221
+ const b = path13.join(to, e.name);
6787
7222
  if (e.isDirectory()) copyDir(a, b);
6788
- else fs17.copyFileSync(a, b);
7223
+ else fs18.copyFileSync(a, b);
6789
7224
  }
6790
7225
  }
6791
7226
  function installMod(version2, opts = {}) {
6792
7227
  const src = modSource();
6793
7228
  if (!src) throw new Error("the bunshin-ui mod is not in this build of the CLI");
6794
7229
  const home = modHome(opts.home);
6795
- const dir2 = path12.join(home, MOD_PLUGIN);
6796
- fs17.rmSync(dir2, { recursive: true, force: true });
7230
+ const dir2 = path13.join(home, MOD_PLUGIN);
7231
+ fs18.rmSync(dir2, { recursive: true, force: true });
6797
7232
  copyDir(src, dir2);
6798
- const manifest = path12.join(dir2, ".claude-plugin", "plugin.json");
6799
- const m = JSON.parse(fs17.readFileSync(manifest, "utf8"));
6800
- fs17.writeFileSync(manifest, JSON.stringify({ ...m, version: version2 }, null, 2) + "\n");
6801
- fs17.mkdirSync(path12.join(home, ".claude-plugin"), { recursive: true });
6802
- fs17.writeFileSync(
6803
- path12.join(home, ".claude-plugin", "marketplace.json"),
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"),
6804
7239
  JSON.stringify({ name: MOD_MARKETPLACE, owner: { name: "Bunshin" }, plugins: [{ name: MOD_PLUGIN, source: `./${MOD_PLUGIN}`, description: m.description }] }, null, 2) + "\n"
6805
7240
  );
6806
7241
  const run2 = opts.run ?? spawnSync;
@@ -6813,7 +7248,10 @@ function installMod(version2, opts = {}) {
6813
7248
  return r.status === 0;
6814
7249
  };
6815
7250
  if (!step(["plugin", "marketplace", "add", home])) step(["plugin", "marketplace", "update", MOD_MARKETPLACE]);
6816
- if (!step(["plugin", "install", `${MOD_PLUGIN}@${MOD_MARKETPLACE}`, "--scope", "user"])) step(["plugin", "update", `${MOD_PLUGIN}@${MOD_MARKETPLACE}`]);
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 });
6817
7255
  return { dir: dir2, version: version2, steps };
6818
7256
  }
6819
7257
  async function cmdUi(store, args, out, err, version2) {
@@ -6835,7 +7273,7 @@ async function cmdUi(store, args, out, err, version2) {
6835
7273
  `);
6836
7274
  for (const s of res.steps) out(` ${s.ok ? "\u2713" : "\xB7"} ${s.command}${s.ok ? "" : `: ${s.output.split("\n")[0] ?? ""}`}
6837
7275
  `);
6838
- out(installed ? "The mod loads in new Claude Code sessions (and after /reload-plugins): a Bunshin band above the prompt, /bunshin, toasts.\nUntil it runs, Bunshin prints one short line per event instead.\n" : "Could not install with `claude plugin`; install it yourself:\n claude plugin marketplace add " + path12.dirname(res.dir) + "\n claude plugin install bunshin-ui@bunshin-local --scope user\n");
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");
6839
7277
  }
6840
7278
  return installed || !failed.length ? 0 : 1;
6841
7279
  }
@@ -6893,7 +7331,7 @@ Claude Code mod: ${v ? `bunshin-ui ${v} (${modHome()})` : "not installed (bunshi
6893
7331
  show();
6894
7332
  return 0;
6895
7333
  }
6896
- var str2, bool, MOD_PLUGIN, MOD_MARKETPLACE, HARNESSES, MODES;
7334
+ var str2, bool, MOD_PLUGIN, MOD_MARKETPLACE, HARNESSES, MODES, INSTALLED_MARKER;
6897
7335
  var init_uicmd = __esm({
6898
7336
  "src/v2/uicmd.ts"() {
6899
7337
  "use strict";
@@ -6905,6 +7343,7 @@ var init_uicmd = __esm({
6905
7343
  MOD_MARKETPLACE = "bunshin-local";
6906
7344
  HARNESSES = ["claude-code", "codex", "pi", "other"];
6907
7345
  MODES = ["auto", "mod", "widget", "lines", "off"];
7346
+ INSTALLED_MARKER = ".installed-version";
6908
7347
  }
6909
7348
  });
6910
7349
 
@@ -6916,19 +7355,19 @@ __export(update_exports, {
6916
7355
  updateCheckDue: () => updateCheckDue,
6917
7356
  updateNotice: () => updateNotice
6918
7357
  });
6919
- import fs18 from "node:fs";
6920
- import path13 from "node:path";
7358
+ import fs19 from "node:fs";
7359
+ import path14 from "node:path";
6921
7360
  function readState2() {
6922
7361
  try {
6923
- return JSON.parse(fs18.readFileSync(stateFile(), "utf8"));
7362
+ return JSON.parse(fs19.readFileSync(stateFile(), "utf8"));
6924
7363
  } catch {
6925
7364
  return {};
6926
7365
  }
6927
7366
  }
6928
7367
  function writeState(s) {
6929
7368
  try {
6930
- fs18.mkdirSync(path13.dirname(stateFile()), { recursive: true });
6931
- 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");
6932
7371
  } catch {
6933
7372
  }
6934
7373
  }
@@ -6978,14 +7417,14 @@ var init_update = __esm({
6978
7417
  PKG = "@bunshin-cc/bunshin";
6979
7418
  LATEST_URL = `https://registry.npmjs.org/${PKG.replace("/", "%2f")}/latest`;
6980
7419
  DAY = 864e5;
6981
- stateFile = () => path13.join(homeDir(), ".bunshin", "update.json");
7420
+ stateFile = () => path14.join(homeDir(), ".bunshin", "update.json");
6982
7421
  disabled = () => process.env.BUNSHIN_NO_UPDATE_CHECK === "1" || process.env.BUNSHIN_NO_UPDATE_CHECK === "true";
6983
7422
  }
6984
7423
  });
6985
7424
 
6986
7425
  // src/v2/hooks.ts
6987
- import fs19 from "node:fs";
6988
- import path14 from "node:path";
7426
+ import fs20 from "node:fs";
7427
+ import path15 from "node:path";
6989
7428
  function inContext(s) {
6990
7429
  return s.inContext ?? [...s.loaded, ...s.pushed];
6991
7430
  }
@@ -7052,10 +7491,13 @@ async function keepModCurrent(ctx, config) {
7052
7491
  const { version: version2 } = await Promise.resolve().then(() => (init_cli(), cli_exports));
7053
7492
  const current = version2();
7054
7493
  if (!modSource2() || installedModVersion2() === current) return;
7055
- const marker = path14.join(modHome2(), `.attempted-${current}`);
7056
- if (fs19.existsSync(marker)) return;
7057
- fs19.mkdirSync(modHome2(), { recursive: true });
7058
- fs19.writeFileSync(marker, (/* @__PURE__ */ new Date()).toISOString());
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());
7059
7501
  ctx.detach(["--root", ctx.store.root, "ui", "install", "--quiet"], { cwd: ctx.cwd });
7060
7502
  } catch {
7061
7503
  }
@@ -7182,7 +7624,7 @@ function liveUpdate(v2, ctx, session) {
7182
7624
  }
7183
7625
  function skillHint(sec, others) {
7184
7626
  const also = others.length ? ` Also possibly relevant: ${others.map((t) => `"${t}"`).join(", ")}.` : "";
7185
- return `Bunshin: the \`${sec.skill.name}\` skill may apply: ${sec.skill.description.replace(/\s+/g, " ").trim()} If it does, invoke it (Skill tool, or \`/${sec.skill.name}\`) before doing this by hand.${also}`;
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}`;
7186
7628
  }
7187
7629
  async function remoteAuto(ctx, prompt, exclude, source, context) {
7188
7630
  const config = ctx.store.config();
@@ -7207,11 +7649,18 @@ function invokedSkill(prompt, sections) {
7207
7649
  const name = m[1].split(":").pop().toLowerCase();
7208
7650
  return sections.find((s) => s.skill && s.skill.name.toLowerCase() === name);
7209
7651
  }
7210
- 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) {
7211
7657
  const prev = readJob(v2, sessionId);
7212
7658
  if (prev && !prev.delivered && !prev.cancelled) v2.log("v2-router-undelivered", { session: sessionId, seq: prev.seq, answered: !!readAnswer(v2, sessionId, prev.seq) });
7213
- const job = { seq: (prev?.seq ?? 0) + 1, at: now };
7659
+ const job = { seq: (prev?.seq ?? 0) + 1, at: now, ...kind ? { kind } : {} };
7214
7660
  writeJob(v2, sessionId, job);
7661
+ v2.updateSession(sessionId, ctx.cwd, (s) => {
7662
+ s.routeCalls = s.toolCalls ?? 0;
7663
+ });
7215
7664
  ctx.detach(["--root", ctx.store.root, "route", "--session", sessionId, "--seq", String(job.seq), "--quiet"], { cwd: ctx.cwd });
7216
7665
  return job;
7217
7666
  }
@@ -7236,7 +7685,7 @@ async function onPrompt(ctx) {
7236
7685
  const config = ctx.store.config();
7237
7686
  const view = localView(v2, config, ctx.cwd, session.source !== void 0 ? { source: session.source } : {});
7238
7687
  const injected = inContext(session);
7239
- 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;
7240
7689
  const named = invokedSkill(prompt, view.sections);
7241
7690
  if (named && job) writeJob(v2, session.sessionId, { ...job, cancelled: true });
7242
7691
  if (named) {
@@ -7253,7 +7702,8 @@ async function onPrompt(ctx) {
7253
7702
  addServed(f, { id: named.id, title: named.title, kind: named.kind, skill: named.skill.name, how: "load", why });
7254
7703
  addEvent(f, "served", `loaded ${label({ skill: named.skill.name, title: named.title, kind: named.kind })} \u2014 ${why}`);
7255
7704
  });
7256
- 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")));
7257
7707
  }
7258
7708
  const res = auto(view.sections, view.reader, prompt, { exclude: injected });
7259
7709
  const recent = session.recentPrompts ?? [];
@@ -7314,7 +7764,7 @@ async function onPrompt(ctx) {
7314
7764
  addServed(f, { id: sec.id, title: sec.title, kind: sec.kind, ...sec.skill ? { skill: sec.skill.name } : {}, how: "auto", why });
7315
7765
  addEvent(f, "served", `served ${label({ ...sec.skill ? { skill: sec.skill.name } : {}, title: sec.title, kind: sec.kind })} \u2014 ${why}`);
7316
7766
  });
7317
- 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"));
7318
7768
  }
7319
7769
  const fresh = res.hint.filter((h) => !session.hinted?.includes(h.id) && !rules.some((r) => r.id === h.id)).slice(0, 3);
7320
7770
  if (!fresh.length) return withLessons("");
@@ -7343,15 +7793,20 @@ function toolPaths(input) {
7343
7793
  }
7344
7794
  return [...new Set(out)];
7345
7795
  }
7346
- async function routedText(v2, ctx, session) {
7796
+ async function routedText(v2, ctx, session, callText) {
7347
7797
  const config = ctx.store.config();
7348
- if (config.recall.router !== "claude-cli") return "";
7798
+ if (recallRouter(config) !== "claude-cli") return "";
7349
7799
  const job = readJob(v2, session.sessionId);
7350
7800
  if (!job || job.delivered || job.cancelled) return "";
7351
7801
  const answer = readAnswer(v2, session.sessionId, job.seq);
7352
7802
  if (!answer) return "";
7803
+ const checkpoint = job.kind === "checkpoint";
7353
7804
  const fallback = !!answer.error;
7354
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
+ }
7355
7810
  const seen = new Set(inContext(session));
7356
7811
  const view = localView(v2, config, ctx.cwd, session.source !== void 0 ? { source: session.source } : {});
7357
7812
  const find = async (id) => {
@@ -7363,48 +7818,98 @@ async function routedText(v2, ctx, session) {
7363
7818
  return void 0;
7364
7819
  }
7365
7820
  };
7366
- const serveId = fallback ? job.dense?.serve : answer.serve;
7821
+ const serveId = checkpoint ? void 0 : fallback ? job.dense?.serve : answer.serve;
7367
7822
  const fresh = (ids2) => [...new Set(ids2.filter((id) => !!id && !seen.has(id)))];
7368
7823
  const [doc] = await Promise.all(fresh([serveId]).map(find));
7369
7824
  const rules = (await Promise.all(fresh(fallback ? [] : answer.rules ?? []).filter((id) => id !== doc?.id).map(find))).filter((s) => !!s);
7370
- const hints = fresh(fallback ? job.dense?.hint ?? [] : answer.hint ?? []).filter((id) => id !== doc?.id && !session.hinted?.includes(id));
7825
+ const hints = checkpoint ? [] : fresh(fallback ? job.dense?.hint ?? [] : answer.hint ?? []).filter((id) => id !== doc?.id && !session.hinted?.includes(id));
7371
7826
  const hintTitles = hints.map((id) => view.sections.find((s) => s.id === id)?.title).filter((t) => !!t);
7372
- v2.log("v2-router-delivered", { session: session.sessionId, seq: job.seq, tool: ctx.input.tool_name, afterMs: Date.now() - Date.parse(job.at), serve: doc?.id ?? null, rules: rules.map((r) => r.id), hint: hints, fallback, dense: job.dense?.serve ?? null, ...answer.error ? { error: answer.error } : {} });
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 } : {} });
7373
7828
  const ids = [...doc ? [doc.id] : [], ...rules.map((r) => r.id)];
7374
7829
  if (!ids.length && !hintTitles.length) return "";
7830
+ const judged = routerFires(rules, session.toolCalls ?? 0, callText);
7375
7831
  v2.updateSession(session.sessionId, ctx.cwd, (s) => {
7376
7832
  addUnique(s.served, ...ids, ...hints);
7377
7833
  addUnique(s.loaded, ...ids);
7378
7834
  markInContext(s, ...ids);
7379
7835
  s.hinted = s.hinted ?? [];
7380
7836
  addUnique(s.hinted, ...hints);
7837
+ if (judged.fires.length) s.fires = [...s.fires ?? [], ...judged.fires].slice(-40);
7381
7838
  });
7839
+ recordTriggers(v2, judged.updates);
7382
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";
7383
7842
  updateFeed(v2, session.sessionId, (f) => {
7384
- for (const r of [...rules].reverse()) addServed(f, { id: r.id, title: r.title, kind: r.kind, how: "auto", why: "a lesson learned before applies here" });
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" });
7385
7844
  if (doc) addServed(f, { id: doc.id, title: doc.title, kind: doc.kind, ...doc.skill ? { skill: doc.skill.name } : {}, how: "auto", why });
7386
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"}`);
7387
- 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(", ")}`);
7388
7847
  });
7389
7848
  return [
7390
7849
  doc ? renderSection(doc, why, { deployed: !!doc.skill && deployEnabled(config, view.ctx) }) : "",
7391
- ...rules.map((r) => renderSection(r, "a lesson learned before applies to this work", { deployed: false })),
7850
+ doc ? cardIndex(view.sections, doc, config.harness) : "",
7851
+ ...rules.map((r) => renderSection(r, ruleWhy, { deployed: false })),
7392
7852
  hintTitles.length ? hintLine(hintTitles, config.harness) : ""
7393
7853
  ].filter(Boolean).join("\n\n");
7394
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
+ }
7395
7887
  async function onPreToolUse(ctx) {
7396
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 = [];
7397
7892
  const session = touch(v2, ctx, (s) => {
7398
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);
7399
7897
  });
7898
+ recordTriggers(v2, judged);
7400
7899
  const live = liveUpdate(v2, ctx, session);
7401
7900
  let routed = "";
7402
7901
  try {
7403
- 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);
7404
7909
  } catch {
7405
7910
  }
7406
7911
  const withLive = (out) => {
7407
- 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");
7408
7913
  return text3 === (out.hookSpecificOutput?.additionalContext ?? "") ? out : additional("PreToolUse", text3);
7409
7914
  };
7410
7915
  const raw = toolPaths(ctx.input.tool_input);
@@ -7442,6 +7947,15 @@ function onStop(ctx) {
7442
7947
  s.lastActivityAt = now.toISOString();
7443
7948
  });
7444
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
+ }
7445
7959
  if (ctx.input.stop_hook_active) return {};
7446
7960
  const scan = scanTranscript(ctx.input.transcript_path ?? session.transcriptPath);
7447
7961
  if (canCall(config) && checkpointDue(session, scan, now)) {
@@ -7655,9 +8169,11 @@ var init_hooks = __esm({
7655
8169
  "src/v2/hooks.ts"() {
7656
8170
  "use strict";
7657
8171
  init_v22();
8172
+ init_store();
7658
8173
  init_redact2();
7659
8174
  init_version();
7660
8175
  init_api();
8176
+ init_atoms2();
7661
8177
  init_deploy();
7662
8178
  init_live();
7663
8179
  init_reflect3();
@@ -7682,8 +8198,8 @@ var init_hooks = __esm({
7682
8198
  });
7683
8199
 
7684
8200
  // src/hooks.ts
7685
- import fs20 from "node:fs";
7686
- import path15 from "node:path";
8201
+ import fs21 from "node:fs";
8202
+ import path16 from "node:path";
7687
8203
  function normalizeEvent(raw) {
7688
8204
  return EVENT_NAMES[String(raw ?? "").trim().toLowerCase().replace(/_/g, "-")] ?? null;
7689
8205
  }
@@ -7751,17 +8267,17 @@ async function handleHook(rawEvent, input, opts = {}) {
7751
8267
  }
7752
8268
  function deferToProject(cwd, env = process.env) {
7753
8269
  if (env.BUNSHIN_HOOK_SCOPE !== "user") return false;
7754
- let dir2 = path15.resolve(cwd);
8270
+ let dir2 = path16.resolve(cwd);
7755
8271
  for (let i = 0; i < 40; i++) {
7756
8272
  for (const f of [".claude/settings.local.json", ".claude/settings.json", ".codex/hooks.json"]) {
7757
8273
  try {
7758
- const text2 = fs20.readFileSync(path15.join(dir2, f), "utf8");
8274
+ const text2 = fs21.readFileSync(path16.join(dir2, f), "utf8");
7759
8275
  if (/\bbunshin\b[^"]*\bhook\b/.test(text2) && !/BUNSHIN_HOOK_SCOPE=user/.test(text2)) return true;
7760
8276
  } catch {
7761
8277
  }
7762
8278
  }
7763
- if (fs20.existsSync(path15.join(dir2, ".git"))) return false;
7764
- const up = path15.dirname(dir2);
8279
+ if (fs21.existsSync(path16.join(dir2, ".git"))) return false;
8280
+ const up = path16.dirname(dir2);
7765
8281
  if (up === dir2) return false;
7766
8282
  dir2 = up;
7767
8283
  }
@@ -7809,11 +8325,11 @@ var init_hooks2 = __esm({
7809
8325
  });
7810
8326
 
7811
8327
  // src/project-hooks.ts
7812
- import fs21 from "node:fs";
7813
- import path16 from "node:path";
8328
+ import fs22 from "node:fs";
8329
+ import path17 from "node:path";
7814
8330
  import { execFileSync as execFileSync4 } from "node:child_process";
7815
8331
  function codexProjectHooks(cwd) {
7816
- const legacyFile = path16.join(cwd, ".codex", "hooks.json");
8332
+ const legacyFile = path17.join(cwd, ".codex", "hooks.json");
7817
8333
  const git5 = (...args) => execFileSync4("git", ["-C", cwd, "rev-parse", ...args], {
7818
8334
  encoding: "utf8",
7819
8335
  stdio: ["ignore", "pipe", "ignore"],
@@ -7827,15 +8343,15 @@ function codexProjectHooks(cwd) {
7827
8343
  } catch {
7828
8344
  return { file: legacyFile, shared: false, legacyFile };
7829
8345
  }
7830
- const linked = fs21.realpathSync(common) !== fs21.realpathSync(directory);
8346
+ const linked = fs22.realpathSync(common) !== fs22.realpathSync(directory);
7831
8347
  if (linked) {
7832
- if (path16.basename(common) !== ".git" || !fs21.statSync(common).isDirectory()) {
8348
+ if (path17.basename(common) !== ".git" || !fs22.statSync(common).isDirectory()) {
7833
8349
  throw new Error("Codex hooks in a worktree of a bare repository are not supported yet. Use a full checkout for Bunshin setup.");
7834
8350
  }
7835
- root = path16.dirname(common);
8351
+ root = path17.dirname(common);
7836
8352
  }
7837
- const file = fs21.realpathSync(root) === fs21.realpathSync(cwd) ? legacyFile : path16.join(root, ".codex", "hooks.json");
7838
- 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 };
7839
8355
  }
7840
8356
  var init_project_hooks = __esm({
7841
8357
  "src/project-hooks.ts"() {
@@ -7868,8 +8384,8 @@ __export(init_exports, {
7868
8384
  runInit: () => runInit
7869
8385
  });
7870
8386
  import { execFileSync as execFileSync5 } from "node:child_process";
7871
- import fs22 from "node:fs";
7872
- import path17 from "node:path";
8387
+ import fs23 from "node:fs";
8388
+ import path18 from "node:path";
7873
8389
  import { fileURLToPath as fileURLToPath2, pathToFileURL } from "node:url";
7874
8390
  function isBunshinEntry(entry) {
7875
8391
  return entry?._bunshin === true || typeof entry?.command === "string" && /\bbunshin\b.*\bhook\b/.test(entry.command);
@@ -7915,17 +8431,17 @@ function countBunshinHooks(settings) {
7915
8431
  );
7916
8432
  }
7917
8433
  function claudeSettingsPath() {
7918
- return path17.join(homeDir(), ".claude", "settings.json");
8434
+ return path18.join(homeDir(), ".claude", "settings.json");
7919
8435
  }
7920
8436
  function installPiExtension(cwd, remove = false, scope = "repo") {
7921
- const file = scope === "global" ? path17.join(homeDir(), ".pi/agent/extensions/bunshin.js") : path17.join(cwd, ".pi/extensions/bunshin.js");
8437
+ const file2 = scope === "global" ? path18.join(homeDir(), ".pi/agent/extensions/bunshin.js") : path18.join(cwd, ".pi/extensions/bunshin.js");
7922
8438
  const marker = "// Managed by Bunshin setup.";
7923
8439
  try {
7924
- const previous = fileExists(file) ? fs22.readFileSync(file, "utf8") : "";
8440
+ const previous = fileExists(file2) ? fs23.readFileSync(file2, "utf8") : "";
7925
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.");
7926
8442
  if (remove) {
7927
- if (previous) fs22.unlinkSync(file);
7928
- return { file, installed: 0, changed: !!previous };
8443
+ if (previous) fs23.unlinkSync(file2);
8444
+ return { file: file2, installed: 0, changed: !!previous };
7929
8445
  }
7930
8446
  const extension = fileURLToPath2(new URL("./pi-extension.js", import.meta.url));
7931
8447
  if (!fileExists(extension)) throw new Error("The packaged Pi extension is missing. Reinstall @bunshin-cc/bunshin.");
@@ -7933,64 +8449,64 @@ function installPiExtension(cwd, remove = false, scope = "repo") {
7933
8449
  export { default } from ${JSON.stringify(pathToFileURL(extension).href)};
7934
8450
  `;
7935
8451
  if (text2 !== previous) {
7936
- ensureDir(path17.dirname(file));
7937
- fs22.writeFileSync(file, text2);
8452
+ ensureDir(path18.dirname(file2));
8453
+ fs23.writeFileSync(file2, text2);
7938
8454
  }
7939
- return { file, installed: 1, changed: text2 !== previous };
8455
+ return { file: file2, installed: 1, changed: text2 !== previous };
7940
8456
  } catch (error) {
7941
- 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) };
7942
8458
  }
7943
8459
  }
7944
- 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 } = {}) {
7945
8461
  try {
7946
- const before = fileExists(file) ? JSON.parse(fs22.readFileSync(file, "utf8")) : {};
8462
+ const before = fileExists(file2) ? JSON.parse(fs23.readFileSync(file2, "utf8")) : {};
7947
8463
  const after = remove ? removeBunshinHooks(before) : mergeClaudeSettings(before, { bin, harness, user, allTools });
7948
8464
  const changed = JSON.stringify(before) !== JSON.stringify(after);
7949
8465
  if (changed) {
7950
- ensureDir(path17.dirname(file));
7951
- if (fileExists(file)) {
8466
+ ensureDir(path18.dirname(file2));
8467
+ if (fileExists(file2)) {
7952
8468
  try {
7953
- fs22.copyFileSync(file, `${file}.bunshin-backup`);
8469
+ fs23.copyFileSync(file2, `${file2}.bunshin-backup`);
7954
8470
  } catch {
7955
8471
  }
7956
8472
  }
7957
- writeJsonAtomic(file, after);
8473
+ writeJsonAtomic(file2, after);
7958
8474
  }
7959
- return { file, installed: countBunshinHooks(after), changed };
8475
+ return { file: file2, installed: countBunshinHooks(after), changed };
7960
8476
  } catch (err) {
7961
- 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) };
7962
8478
  }
7963
8479
  }
7964
8480
  function mcpLauncher(bin) {
7965
8481
  if (!bin || /^[\w./@+-]+$/.test(bin)) return { command: bin || "bunshin", args: ["mcp"] };
7966
8482
  let script = process.argv[1] ?? "";
7967
8483
  try {
7968
- script = fs22.realpathSync(script);
8484
+ script = fs23.realpathSync(script);
7969
8485
  } catch {
7970
8486
  }
7971
8487
  return { command: process.execPath, args: [script, "mcp"] };
7972
8488
  }
7973
- function installLearnCommand({ file, remove = false, content = LEARN_COMMAND }) {
8489
+ function installLearnCommand({ file: file2, remove = false, content = LEARN_COMMAND }) {
7974
8490
  try {
7975
- const current = fileExists(file) ? fs22.readFileSync(file, "utf8") : null;
8491
+ const current = fileExists(file2) ? fs23.readFileSync(file2, "utf8") : null;
7976
8492
  const ours = current === null || current === content;
7977
8493
  if (remove) {
7978
- if (current !== null && ours) fs22.unlinkSync(file);
7979
- 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 };
7980
8496
  }
7981
- 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` };
7982
8498
  if (current === null) {
7983
- fs22.mkdirSync(path17.dirname(file), { recursive: true });
7984
- fs22.writeFileSync(file, content);
8499
+ fs23.mkdirSync(path18.dirname(file2), { recursive: true });
8500
+ fs23.writeFileSync(file2, content);
7985
8501
  }
7986
- return { file, installed: 1, changed: current === null };
8502
+ return { file: file2, installed: 1, changed: current === null };
7987
8503
  } catch (err) {
7988
- 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) };
7989
8505
  }
7990
8506
  }
7991
- function installMcpConfig({ file, launcher, remove = false }) {
8507
+ function installMcpConfig({ file: file2, launcher, remove = false }) {
7992
8508
  try {
7993
- const before = fileExists(file) ? JSON.parse(fs22.readFileSync(file, "utf8")) : {};
8509
+ const before = fileExists(file2) ? JSON.parse(fs23.readFileSync(file2, "utf8")) : {};
7994
8510
  const servers = { ...before.mcpServers ?? {} };
7995
8511
  if (remove) delete servers.bunshin;
7996
8512
  else servers.bunshin = { type: "stdio", command: launcher.command, args: launcher.args, env: { BUNSHIN_HARNESS: "claude-code" } };
@@ -7998,16 +8514,16 @@ function installMcpConfig({ file, launcher, remove = false }) {
7998
8514
  if (!Object.keys(servers).length) delete after.mcpServers;
7999
8515
  const changed = JSON.stringify(before) !== JSON.stringify(after);
8000
8516
  if (changed) {
8001
- if (!Object.keys(after).length && fileExists(file)) fs22.unlinkSync(file);
8002
- 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);
8003
8519
  }
8004
- return { file, installed: servers.bunshin ? 1 : 0, changed };
8520
+ return { file: file2, installed: servers.bunshin ? 1 : 0, changed };
8005
8521
  } catch (err) {
8006
- 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) };
8007
8523
  }
8008
8524
  }
8009
8525
  function installUserMcp({ launcher, remove = false, claude = "claude" }) {
8010
- const file = path17.join(homeDir(), ".claude.json");
8526
+ const file2 = path18.join(homeDir(), ".claude.json");
8011
8527
  const run2 = (args) => execFileSync5(claude, args, { stdio: ["ignore", "pipe", "pipe"], timeout: 2e4, env: { ...process.env, BUNSHIN_CHILD: "1" } }).toString();
8012
8528
  try {
8013
8529
  let had = false;
@@ -8022,33 +8538,33 @@ function installUserMcp({ launcher, remove = false, claude = "claude" }) {
8022
8538
  } catch {
8023
8539
  }
8024
8540
  }
8025
- if (remove) return { file, installed: 0, changed: had };
8541
+ if (remove) return { file: file2, installed: 0, changed: had };
8026
8542
  run2(["mcp", "add-json", "bunshin", JSON.stringify({ type: "stdio", command: launcher.command, args: launcher.args, env: { BUNSHIN_HARNESS: "claude-code" } }), "-s", "user"]);
8027
- return { file, installed: 1, changed: true };
8543
+ return { file: file2, installed: 1, changed: true };
8028
8544
  } catch (err) {
8029
- 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) };
8030
8546
  }
8031
8547
  }
8032
8548
  function runInit(opts = {}) {
8033
8549
  const cwd = opts.cwd ?? process.cwd();
8034
8550
  const warnings = [];
8035
8551
  const scope = opts.scope ?? "repo";
8036
- const root = scope === "global" ? path17.join(homeDir(), ".bunshin") : path17.join(cwd, ".bunshin");
8037
- if (fs22.existsSync(root) && !new Store(root).trusted && fs22.readdirSync(root).length) {
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) {
8038
8554
  const aside = `${root}.untrusted-${Date.now()}`;
8039
- fs22.renameSync(root, aside);
8555
+ fs23.renameSync(root, aside);
8040
8556
  warnings.push(`moved ${root} aside to ${aside}: this user did not create it`);
8041
8557
  }
8042
- const existed = fileExists(path17.join(root, "config.json"));
8558
+ const existed = fileExists(path18.join(root, "config.json"));
8043
8559
  const store = new Store(root);
8044
8560
  store.ensureLayout();
8045
- fs22.chmodSync(root, 448);
8561
+ fs23.chmodSync(root, 448);
8046
8562
  const hookScope = opts.hooks ?? (scope === "global" ? "user" : (existed && store.trusted ? store.config().hooks : void 0) ?? "project");
8047
- if (scope === "repo" && (hookScope === "project" || fileExists(path17.join(cwd, ".git")))) {
8048
- const ignore = path17.join(cwd, ".gitignore");
8049
- const current = fileExists(ignore) ? fs22.readFileSync(ignore, "utf8") : "";
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") : "";
8050
8566
  if (!current.split(/\r?\n/).some((line) => /^\/?\.bunshin\/?$/.test(line.trim()))) {
8051
- fs22.appendFileSync(ignore, `${current && !current.endsWith("\n") ? "\n" : ""}.bunshin/
8567
+ fs23.appendFileSync(ignore, `${current && !current.endsWith("\n") ? "\n" : ""}.bunshin/
8052
8568
  `);
8053
8569
  }
8054
8570
  }
@@ -8078,17 +8594,17 @@ function runInit(opts = {}) {
8078
8594
  }
8079
8595
  if ((opts.removeHooks || !opts.noHooks) && (config.harness === "codex" || config.harness === "claude-code")) {
8080
8596
  const projectHooks = config.harness === "codex" && hookScope === "project" && !opts.settingsFile ? codexProjectHooks(cwd) : void 0;
8081
- const file = opts.settingsFile ?? (config.harness === "codex" ? projectHooks?.file ?? path17.join(process.env.CODEX_HOME ?? path17.join(homeDir(), ".codex"), "hooks.json") : hookScope === "project" ? path17.join(cwd, ".claude", "settings.local.json") : claudeSettingsPath());
8082
- hooks = installClaudeHooks({ file, bin: opts.bin, remove: opts.removeHooks, harness: config.harness, user: hookScope === "user" && !opts.settingsFile, allTools: config.recall.router === "claude-cli" });
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" });
8083
8599
  if (!opts.removeHooks && !opts.settingsFile && hookScope === "user" && config.harness === "claude-code") {
8084
- const local = path17.join(cwd, ".claude", "settings.local.json");
8085
- if (fileExists(local) && path17.resolve(local) !== path17.resolve(file)) installClaudeHooks({ file: local, remove: true });
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 });
8086
8602
  }
8087
8603
  if (projectHooks?.shared) {
8088
8604
  hooks.sharedWithWorktrees = true;
8089
- if (!hooks.error && !opts.removeHooks) ensureDir(path17.dirname(projectHooks.legacyFile));
8605
+ if (!hooks.error && !opts.removeHooks) ensureDir(path18.dirname(projectHooks.legacyFile));
8090
8606
  }
8091
- 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)) {
8092
8608
  const old = installClaudeHooks({ file: projectHooks.legacyFile, remove: true, harness: "codex" });
8093
8609
  if (old.error) hooks.error = `Could not remove old Bunshin hooks from ${old.file}: ${old.error}`;
8094
8610
  }
@@ -8098,17 +8614,17 @@ function runInit(opts = {}) {
8098
8614
  let learnCommand;
8099
8615
  if ((opts.removeHooks || !opts.noHooks) && config.harness === "claude-code") {
8100
8616
  const user = hookScope === "user";
8101
- mcp = user ? installUserMcp({ launcher: opts.mcp ?? mcpLauncher(opts.bin), remove: opts.removeHooks }) : installMcpConfig({ file: path17.join(cwd, ".mcp.json"), launcher: opts.mcp ?? mcpLauncher(opts.bin), remove: opts.removeHooks });
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 });
8102
8618
  if (mcp.error) warnings.push(`could not update ${mcp.file}: ${mcp.error}`);
8103
- learnCommand = installLearnCommand({ file: path17.join(user ? path17.join(homeDir(), ".claude") : path17.join(cwd, ".claude"), "commands", "learn.md"), remove: opts.removeHooks });
8619
+ learnCommand = installLearnCommand({ file: path18.join(user ? path18.join(homeDir(), ".claude") : path18.join(cwd, ".claude"), "commands", "learn.md"), remove: opts.removeHooks });
8104
8620
  if (learnCommand.error) warnings.push(`/learn not installed at ${learnCommand.file}: ${learnCommand.error}`);
8105
8621
  }
8106
8622
  let borrowCommand;
8107
8623
  if (opts.removeHooks || !opts.noHooks) {
8108
8624
  const user = hookScope === "user";
8109
- const file = config.harness === "claude-code" ? path17.join(user ? path17.join(homeDir(), ".claude") : path17.join(cwd, ".claude"), "commands", "borrow.md") : config.harness === "codex" ? path17.join(process.env.CODEX_HOME ?? path17.join(homeDir(), ".codex"), "prompts", "borrow.md") : config.harness === "pi" ? user ? path17.join(homeDir(), ".pi", "agent", "prompts", "borrow.md") : path17.join(cwd, ".pi", "prompts", "borrow.md") : null;
8110
- if (file) {
8111
- borrowCommand = installLearnCommand({ file, remove: opts.removeHooks, content: BORROW_COMMAND });
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 });
8112
8628
  if (borrowCommand.error) warnings.push(`/borrow not installed at ${borrowCommand.file}: ${borrowCommand.error}`);
8113
8629
  }
8114
8630
  }
@@ -8264,8 +8780,8 @@ __export(commands_exports, {
8264
8780
  setupRobot: () => setupRobot,
8265
8781
  v2Status: () => v2Status
8266
8782
  });
8267
- import fs23 from "node:fs";
8268
- import path18 from "node:path";
8783
+ import fs24 from "node:fs";
8784
+ import path19 from "node:path";
8269
8785
  import { createHash as createHash6, randomBytes as randomBytes4 } from "node:crypto";
8270
8786
  function cmdReview(store, args, cwd, out, err) {
8271
8787
  const v2 = new V2Store(store);
@@ -8436,13 +8952,13 @@ function cmdSuggest(store, args, cwd, out, err) {
8436
8952
  err('bunshin suggest: usage: bunshin suggest --code <harness-relative path> [--file <local file>] [--rationale "<text>"]\n');
8437
8953
  return 1;
8438
8954
  }
8439
- const harnessDir = path18.resolve(cwd, str3(args.flags["harness-dir"]) ?? ".");
8440
- const file = str3(args.flags.file) ? path18.resolve(cwd, str3(args.flags.file)) : path18.join(harnessDir, rel);
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);
8441
8957
  let content;
8442
8958
  try {
8443
- content = fs23.readFileSync(file, "utf8");
8959
+ content = fs24.readFileSync(file2, "utf8");
8444
8960
  } catch {
8445
- err(`bunshin suggest: cannot read ${file}
8961
+ err(`bunshin suggest: cannot read ${file2}
8446
8962
  `);
8447
8963
  return 1;
8448
8964
  }
@@ -8561,26 +9077,26 @@ async function cmdQuestions(store, args, out, err) {
8561
9077
  return 0;
8562
9078
  }
8563
9079
  function saveCredential(storeRoot, apiUrl, apiKey, id) {
8564
- const dir2 = path18.join(homeDir(), ".config/bunshin/credentials");
8565
- fs23.mkdirSync(dir2, { recursive: true, mode: 448 });
8566
- fs23.chmodSync(dir2, 448);
8567
- const file = path18.join(dir2, `${createHash6("sha256").update(`${storeRoot}
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}
8568
9084
  ${apiUrl}
8569
9085
  ${id}`).digest("hex")}.json`);
8570
- const tmp = `${file}.${randomBytes4(4).toString("hex")}.tmp`;
8571
- fs23.writeFileSync(tmp, JSON.stringify({ apiUrl, apiKey }) + "\n", { mode: 384, flag: "wx" });
8572
- fs23.renameSync(tmp, file);
8573
- return file;
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;
8574
9090
  }
8575
9091
  async function setupRobot(opts) {
8576
9092
  if (!/^[A-Za-z0-9._-]{1,100}$/.test(opts.robotId)) throw new Error("--robot-id must be letters, digits, '.', '_' or '-'");
8577
9093
  const existing = Store.discover(opts.cwd);
8578
9094
  let store;
8579
9095
  const harness = opts.harness ?? "other";
8580
- 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;
8581
9097
  else {
8582
9098
  runInit({ cwd: opts.cwd, harness, noHooks: harness === "other", ...opts.apiUrl ? { apiUrl: opts.apiUrl } : {} });
8583
- store = new Store(path18.join(opts.cwd, ".bunshin"));
9099
+ store = new Store(path19.join(opts.cwd, ".bunshin"));
8584
9100
  }
8585
9101
  let config = store.config();
8586
9102
  const apiUrl = (opts.apiUrl ?? config.apiUrl ?? "").replace(/\/$/, "");
@@ -8734,16 +9250,16 @@ __export(setup_exports, {
8734
9250
  setupProject: () => setupProject,
8735
9251
  shellQuote: () => shellQuote
8736
9252
  });
8737
- import fs24 from "node:fs";
8738
- import path19 from "node:path";
9253
+ import fs25 from "node:fs";
9254
+ import path20 from "node:path";
8739
9255
  import { createHash as createHash7, randomBytes as randomBytes5 } from "node:crypto";
8740
9256
  function executable(name) {
8741
- 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")];
8742
9258
  for (const directory of directories) {
8743
- const file = path19.resolve(directory, name);
9259
+ const file2 = path20.resolve(directory, name);
8744
9260
  try {
8745
- fs24.accessSync(file, fs24.constants.X_OK);
8746
- if (fs24.statSync(file).isFile()) return file;
9261
+ fs25.accessSync(file2, fs25.constants.X_OK);
9262
+ if (fs25.statSync(file2).isFile()) return file2;
8747
9263
  } catch {
8748
9264
  }
8749
9265
  }
@@ -8751,8 +9267,8 @@ function executable(name) {
8751
9267
  }
8752
9268
  function hookBinary(harness) {
8753
9269
  const agent = executable(harness === "claude-code" ? "claude" : harness);
8754
- const directories = [.../* @__PURE__ */ new Set([path19.dirname(process.execPath), path19.join(homeDir(), ".local/bin"), ...agent ? [path19.dirname(agent)] : []])];
8755
- return `PATH=${shellQuote(directories.join(path19.delimiter))}:"$PATH" ${shellQuote(process.execPath)} ${shellQuote(fs24.realpathSync(process.argv[1]))}`;
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]))}`;
8756
9272
  }
8757
9273
  function apiAddress(raw) {
8758
9274
  const url = new URL(raw);
@@ -8822,23 +9338,23 @@ async function setupProject(opts) {
8822
9338
  const apiKey = opts.apiKey.trim();
8823
9339
  if (!apiKey || /\s/.test(apiKey)) throw new Error("Paste the complete agent key from your Bunshin workspace.");
8824
9340
  const profile = await connectionProfile(apiUrl, apiKey);
8825
- const root = path19.join(opts.cwd, ".bunshin");
9341
+ const root = path20.join(opts.cwd, ".bunshin");
8826
9342
  const store = new Store(root);
8827
9343
  const previous = store.config();
8828
9344
  if ((previous.orgId !== profile.orgId || previous.userId !== profile.userId) && (store.listLessons().length || store.allTraces().length || store.listRecallLessons().length)) {
8829
9345
  throw new Error("This project has lessons or activity from another profile. Use a fresh project to connect this workspace.");
8830
9346
  }
8831
- const credentialDirectory = path19.join(homeDir(), ".config/bunshin/credentials");
8832
- fs24.mkdirSync(credentialDirectory, { recursive: true, mode: 448 });
8833
- 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);
8834
9350
  const name = createHash7("sha256").update(`${root}
8835
9351
  ${apiUrl}
8836
9352
  ${profile.orgId}
8837
9353
  ${profile.userId}`).digest("hex");
8838
- const credentialFile = path19.join(credentialDirectory, `${name}.json`);
9354
+ const credentialFile = path20.join(credentialDirectory, `${name}.json`);
8839
9355
  const temporary = `${credentialFile}.${randomBytes5(4).toString("hex")}.tmp`;
8840
- fs24.writeFileSync(temporary, JSON.stringify({ apiUrl, apiKey }) + "\n", { mode: 384, flag: "wx" });
8841
- fs24.renameSync(temporary, credentialFile);
9356
+ fs25.writeFileSync(temporary, JSON.stringify({ apiUrl, apiKey }) + "\n", { mode: 384, flag: "wx" });
9357
+ fs25.renameSync(temporary, credentialFile);
8842
9358
  const result = runInit({
8843
9359
  cwd: opts.cwd,
8844
9360
  harness: opts.harness,
@@ -9191,8 +9707,8 @@ __export(sync_exports2, {
9191
9707
  runSync: () => runSync
9192
9708
  });
9193
9709
  import { createHash as createHash8 } from "node:crypto";
9194
- import path20 from "node:path";
9195
- import fs25 from "node:fs";
9710
+ import path21 from "node:path";
9711
+ import fs26 from "node:fs";
9196
9712
  async function api(config, method, route, body, timeoutMs = 1e4) {
9197
9713
  const ctrl = new AbortController();
9198
9714
  const timer = setTimeout(() => ctrl.abort(), timeoutMs);
@@ -9230,22 +9746,22 @@ async function mothershipLookup(config, ids, timeoutMs = 8e3) {
9230
9746
  }
9231
9747
  }
9232
9748
  async function runSync(store) {
9233
- const lock = path20.join(store.root, "sync.lock");
9749
+ const lock = path21.join(store.root, "sync.lock");
9234
9750
  const deadline = Date.now() + 12e4;
9235
9751
  for (; ; ) {
9236
9752
  try {
9237
- fs25.writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 });
9753
+ fs26.writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 });
9238
9754
  break;
9239
9755
  } catch (error) {
9240
9756
  if (error.code !== "EEXIST") throw error;
9241
9757
  try {
9242
- const owner = Number(fs25.readFileSync(lock, "utf8"));
9758
+ const owner = Number(fs26.readFileSync(lock, "utf8"));
9243
9759
  if (Number.isInteger(owner) && owner > 0) {
9244
9760
  try {
9245
9761
  process.kill(owner, 0);
9246
9762
  } catch (error2) {
9247
9763
  if (error2.code === "ESRCH") {
9248
- fs25.unlinkSync(lock);
9764
+ fs26.unlinkSync(lock);
9249
9765
  continue;
9250
9766
  }
9251
9767
  }
@@ -9264,7 +9780,7 @@ async function runSync(store) {
9264
9780
  return await syncStore(store);
9265
9781
  } finally {
9266
9782
  try {
9267
- fs25.unlinkSync(lock);
9783
+ fs26.unlinkSync(lock);
9268
9784
  } catch {
9269
9785
  }
9270
9786
  }
@@ -9292,7 +9808,7 @@ async function syncStore(store) {
9292
9808
  result.errors.push(String(e instanceof Error ? e.message : e));
9293
9809
  }
9294
9810
  }
9295
- const acknowledgementsFile = path20.join(store.root, "synced-traces.json");
9811
+ const acknowledgementsFile = path21.join(store.root, "synced-traces.json");
9296
9812
  const acknowledgements = readJson(acknowledgementsFile, {});
9297
9813
  const fingerprint2 = (trace) => createHash8("sha256").update(JSON.stringify(trace)).digest("hex");
9298
9814
  const traces = store.allTraces().filter((t) => acknowledgements[t.id] !== fingerprint2(t)).slice(0, 50);
@@ -9547,11 +10063,11 @@ __export(demo_exports, {
9547
10063
  runDemo: () => runDemo
9548
10064
  });
9549
10065
  import assert from "node:assert/strict";
9550
- import fs26 from "node:fs";
10066
+ import fs27 from "node:fs";
9551
10067
  import os4 from "node:os";
9552
- import path21 from "node:path";
10068
+ import path22 from "node:path";
9553
10069
  async function runDemo(write) {
9554
- const root = fs26.mkdtempSync(path21.join(os4.tmpdir(), "bunshin-demo-"));
10070
+ const root = fs27.mkdtempSync(path22.join(os4.tmpdir(), "bunshin-demo-"));
9555
10071
  try {
9556
10072
  const store = Store.init(root, { ...APR_ENGINEER, apiUrl: "" });
9557
10073
  const { lessons, constraint, workflow } = aprScenario();
@@ -9568,7 +10084,7 @@ Task: ${APR_TASK}
9568
10084
  write(result.text);
9569
10085
  write("\nPASS: Collections constraint and workflow recalled; C-suite, other-company, and superseded lessons excluded.\n");
9570
10086
  } finally {
9571
- fs26.rmSync(root, { recursive: true, force: true });
10087
+ fs27.rmSync(root, { recursive: true, force: true });
9572
10088
  }
9573
10089
  }
9574
10090
  var init_demo = __esm({
@@ -9581,21 +10097,21 @@ var init_demo = __esm({
9581
10097
  });
9582
10098
 
9583
10099
  // src/v2/gitremote.ts
9584
- import fs27 from "node:fs";
9585
- import path22 from "node:path";
10100
+ import fs28 from "node:fs";
10101
+ import path23 from "node:path";
9586
10102
  import { createHash as createHash9 } from "node:crypto";
9587
10103
  function saveGitCredential(apiUrl, apiKey) {
9588
- const file = gitCredentialFile();
9589
- fs27.mkdirSync(path22.dirname(file), { recursive: true, mode: 448 });
10104
+ const file2 = gitCredentialFile();
10105
+ fs28.mkdirSync(path23.dirname(file2), { recursive: true, mode: 448 });
9590
10106
  let all = {};
9591
10107
  try {
9592
- all = JSON.parse(fs27.readFileSync(file, "utf8"));
10108
+ all = JSON.parse(fs28.readFileSync(file2, "utf8"));
9593
10109
  } catch {
9594
10110
  }
9595
10111
  all[apiUrl.replace(/\/$/, "")] = apiKey;
9596
- const tmp = `${file}.${process.pid}.tmp`;
9597
- fs27.writeFileSync(tmp, JSON.stringify(all, null, 2) + "\n", { mode: 384 });
9598
- fs27.renameSync(tmp, file);
10112
+ const tmp = `${file2}.${process.pid}.tmp`;
10113
+ fs28.writeFileSync(tmp, JSON.stringify(all, null, 2) + "\n", { mode: 384 });
10114
+ fs28.renameSync(tmp, file2);
9599
10115
  }
9600
10116
  function resolveGitKey(apiUrl) {
9601
10117
  const base = apiUrl.replace(/\/$/, "");
@@ -9603,20 +10119,20 @@ function resolveGitKey(apiUrl) {
9603
10119
  const origin = urlOrigin(base);
9604
10120
  if (process.env.BUNSHIN_API_KEY && origin && trustedOrigins().has(origin)) return process.env.BUNSHIN_API_KEY;
9605
10121
  try {
9606
- const all = JSON.parse(fs27.readFileSync(gitCredentialFile(), "utf8"));
10122
+ const all = JSON.parse(fs28.readFileSync(gitCredentialFile(), "utf8"));
9607
10123
  if (all[base]) return all[base];
9608
10124
  } catch {
9609
10125
  }
9610
- const dir2 = path22.join(homeDir(), ".config/bunshin/credentials");
10126
+ const dir2 = path23.join(homeDir(), ".config/bunshin/credentials");
9611
10127
  let files = [];
9612
10128
  try {
9613
- files = fs27.readdirSync(dir2).filter((f) => f.endsWith(".json"));
10129
+ files = fs28.readdirSync(dir2).filter((f) => f.endsWith(".json"));
9614
10130
  } catch {
9615
10131
  return void 0;
9616
10132
  }
9617
10133
  for (const f of files.sort()) {
9618
10134
  try {
9619
- const c = JSON.parse(fs27.readFileSync(path22.join(dir2, f), "utf8"));
10135
+ const c = JSON.parse(fs28.readFileSync(path23.join(dir2, f), "utf8"));
9620
10136
  if (c.apiKey && c.apiUrl?.replace(/\/$/, "") === base) return c.apiKey;
9621
10137
  } catch {
9622
10138
  }
@@ -9637,7 +10153,7 @@ var init_gitremote = __esm({
9637
10153
  ZERO_SHA = "0".repeat(40);
9638
10154
  REMOTE_PATH = "/v1/git/repos/";
9639
10155
  remoteUrl = (apiUrl, repo) => `bunshin::${apiUrl.replace(/\/$/, "")}${REMOTE_PATH}${repo}`;
9640
- gitCredentialFile = () => path22.join(homeDir(), ".config/bunshin/git-credentials.json");
10156
+ gitCredentialFile = () => path23.join(homeDir(), ".config/bunshin/git-credentials.json");
9641
10157
  GitApiError = class extends Error {
9642
10158
  constructor(status, message, body = null) {
9643
10159
  super(message);
@@ -9729,8 +10245,8 @@ __export(gitrepo_exports, {
9729
10245
  githubReferences: () => githubReferences,
9730
10246
  repoFromUrl: () => repoFromUrl
9731
10247
  });
9732
- import fs28 from "node:fs";
9733
- import path23 from "node:path";
10248
+ import fs29 from "node:fs";
10249
+ import path24 from "node:path";
9734
10250
  import { spawnSync as spawnSync2 } from "node:child_process";
9735
10251
  function git3(cwd, args, opts = {}) {
9736
10252
  const r = spawnSync2("git", ["-C", cwd, ...args], { encoding: "utf8", stdio: opts.inherit ? ["ignore", "inherit", "inherit"] : ["ignore", "pipe", "pipe"], maxBuffer: 256 * 1024 * 1024 });
@@ -9739,9 +10255,9 @@ function git3(cwd, args, opts = {}) {
9739
10255
  return res;
9740
10256
  }
9741
10257
  function onPath(name) {
9742
- for (const dir2 of (process.env.PATH ?? "").split(path23.delimiter)) {
10258
+ for (const dir2 of (process.env.PATH ?? "").split(path24.delimiter)) {
9743
10259
  try {
9744
- fs28.accessSync(path23.join(dir2, name), fs28.constants.X_OK);
10260
+ fs29.accessSync(path24.join(dir2, name), fs29.constants.X_OK);
9745
10261
  return true;
9746
10262
  } catch {
9747
10263
  }
@@ -9825,11 +10341,11 @@ function switchOrigin(root, url, out) {
9825
10341
  }
9826
10342
  async function cmdImport(args, cwd, out, err) {
9827
10343
  requireHelper();
9828
- 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));
9829
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");
9830
10346
  const rs = remotes(root);
9831
10347
  const originUrl = rs.get("origin");
9832
- const name = str4(args.flags.name) ?? (originUrl && !originUrl.startsWith("bunshin::") ? repoFromUrl(originUrl) : null) ?? `${path23.basename(path23.dirname(root))}/${path23.basename(root)}`;
10348
+ const name = str4(args.flags.name) ?? (originUrl && !originUrl.startsWith("bunshin::") ? repoFromUrl(originUrl) : null) ?? `${path24.basename(path24.dirname(root))}/${path24.basename(root)}`;
9833
10349
  const client = await connect(args, cwd);
9834
10350
  const url = remoteUrl(client.apiUrl, name);
9835
10351
  const fromOrigin = !!originUrl && !originUrl.startsWith("bunshin::") && !bool3(args.flags.local);
@@ -9905,7 +10421,7 @@ ${refsToGithub.length} line${refsToGithub.length === 1 ? "" : "s"} in the reposi
9905
10421
  if (refsToGithub.length > 40) out(` \u2026 and ${refsToGithub.length - 40} more (git grep for ${name})
9906
10422
  `);
9907
10423
  }
9908
- if (fs28.existsSync(path23.join(root, ".github"))) out(`
10424
+ if (fs29.existsSync(path24.join(root, ".github"))) out(`
9909
10425
  Note: .github/ (Actions, CODEOWNERS, templates) only works on GitHub; Bunshin does not run it.
9910
10426
  `);
9911
10427
  out(`
@@ -9916,7 +10432,7 @@ New machines clone with: bunshin repo clone ${name}
9916
10432
  }
9917
10433
  async function cmdAttach(args, cwd, out, err) {
9918
10434
  requireHelper();
9919
- const root = toplevel(path23.resolve(str4(args.flags.path) ?? cwd));
10435
+ const root = toplevel(path24.resolve(str4(args.flags.path) ?? cwd));
9920
10436
  const rs = remotes(root);
9921
10437
  const originUrl = rs.get("origin");
9922
10438
  const name = str4(args.flags.name) ?? args._[1] ?? (originUrl ? repoFromUrl(originUrl) : null);
@@ -9964,12 +10480,12 @@ async function cmdClone(args, cwd, out) {
9964
10480
  const dir2 = args._[2] ?? name.split("/")[1];
9965
10481
  const r = spawnSync2("git", ["clone", remoteUrl(client.apiUrl, name), dir2], { cwd, stdio: "inherit" });
9966
10482
  if (r.status !== 0) return r.status ?? 1;
9967
- out(`Cloned ${name} into ${path23.resolve(cwd, dir2)}
10483
+ out(`Cloned ${name} into ${path24.resolve(cwd, dir2)}
9968
10484
  `);
9969
10485
  return 0;
9970
10486
  }
9971
10487
  async function cmdVerify(args, cwd, out, err) {
9972
- const root = toplevel(path23.resolve(str4(args.flags.path) ?? cwd));
10488
+ const root = toplevel(path24.resolve(str4(args.flags.path) ?? cwd));
9973
10489
  const rs = remotes(root);
9974
10490
  const originUrl = rs.get("origin") ?? "";
9975
10491
  if (!originUrl.startsWith("bunshin::")) throw new Error("origin is not a Bunshin repository (run bunshin repo attach)");
@@ -10132,22 +10648,22 @@ __export(runner_exports, {
10132
10648
  setupText: () => setupText
10133
10649
  });
10134
10650
  import { spawnSync as spawnSync3 } from "node:child_process";
10135
- import fs29 from "node:fs";
10651
+ import fs30 from "node:fs";
10136
10652
  import os5 from "node:os";
10137
- import path24 from "node:path";
10653
+ import path25 from "node:path";
10138
10654
  function runnerHome(home = process.env.BUNSHIN_RUNNER_HOME || os5.homedir()) {
10139
- return path24.join(home, ".bunshin", "runner");
10655
+ return path25.join(home, ".bunshin", "runner");
10140
10656
  }
10141
10657
  function readInstalled(home) {
10142
10658
  try {
10143
- 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"));
10144
10660
  } catch {
10145
10661
  return null;
10146
10662
  }
10147
10663
  }
10148
10664
  function connection(args, cwd) {
10149
10665
  const saved = readInstalled();
10150
- 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);
10151
10667
  const config = store?.config();
10152
10668
  const key = str5(args.flags.key) || process.env.BUNSHIN_RUNNER_KEY || process.env.BUNSHIN_API_KEY || config?.apiKey || saved?.key || "";
10153
10669
  const apiUrl = (str5(args.flags["api-url"]) || process.env.BUNSHIN_API_URL || config?.apiUrl || saved?.apiUrl || DEFAULT_API).replace(/\/$/, "");
@@ -10207,9 +10723,9 @@ async function runOnce(c, args, out, err) {
10207
10723
  const [job] = await lease(c, args);
10208
10724
  if (!job) break;
10209
10725
  const started = Date.now();
10210
- const scratch = fs29.mkdtempSync(path24.join(os5.tmpdir(), "bunshin-job-"));
10726
+ const scratch = fs30.mkdtempSync(path25.join(os5.tmpdir(), "bunshin-job-"));
10211
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(
10212
- () => fs29.rmSync(scratch, { recursive: true, force: true })
10728
+ () => fs30.rmSync(scratch, { recursive: true, force: true })
10213
10729
  );
10214
10730
  const model = config.backend === "codex-cli" ? config.codexModel ?? "codex default" : config.backend === "pi-cli" ? config.piModel ?? "pi default" : config.model;
10215
10731
  if (!res.ok) {
@@ -10299,24 +10815,24 @@ function renderCheck(id, c) {
10299
10815
  }
10300
10816
  function logAnswer(entry) {
10301
10817
  try {
10302
- fs29.mkdirSync(runnerHome(), { recursive: true });
10303
- 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 })}
10304
10820
  `);
10305
10821
  } catch {
10306
10822
  }
10307
10823
  }
10308
10824
  function which(name) {
10309
- for (const d of [...(process.env.PATH || "").split(path24.delimiter), path24.join(os5.homedir(), ".local", "bin")]) {
10310
- if (d && fs29.existsSync(path24.join(d, name))) return path24.join(d, name);
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);
10311
10827
  }
10312
10828
  return null;
10313
10829
  }
10314
10830
  function scheduledCommand(backend) {
10315
- const node = path24.dirname(process.execPath);
10316
- const npx = fs29.existsSync(path24.join(node, "npx")) ? path24.join(node, "npx") : which("npx") ?? "npx";
10831
+ const node = path25.dirname(process.execPath);
10832
+ const npx = fs30.existsSync(path25.join(node, "npx")) ? path25.join(node, "npx") : which("npx") ?? "npx";
10317
10833
  const bin = BIN_OF[backend] ? which(BIN_OF[backend]) : null;
10318
- const dirs = [.../* @__PURE__ */ new Set([node, ...bin ? [path24.dirname(bin)] : [], path24.join(os5.homedir(), ".local", "bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"])];
10319
- return { argv: [npx, "-y", PKG2, "runner", "--once"], path: dirs.join(path24.delimiter) };
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) };
10320
10836
  }
10321
10837
  function launchdPlist(backend, everyMinutes, home = runnerHome()) {
10322
10838
  const cmd = scheduledCommand(backend);
@@ -10331,8 +10847,8 @@ function launchdPlist(backend, everyMinutes, home = runnerHome()) {
10331
10847
  <dict><key>PATH</key><string>${xml(cmd.path)}</string></dict>
10332
10848
  <key>WorkingDirectory</key><string>${xml(home)}</string>
10333
10849
  <key>StartInterval</key><integer>${everyMinutes * 60}</integer>
10334
- <key>StandardOutPath</key><string>${xml(path24.join(home, "runner.log"))}</string>
10335
- <key>StandardErrorPath</key><string>${xml(path24.join(home, "runner.log"))}</string>
10850
+ <key>StandardOutPath</key><string>${xml(path25.join(home, "runner.log"))}</string>
10851
+ <key>StandardErrorPath</key><string>${xml(path25.join(home, "runner.log"))}</string>
10336
10852
  <key>ProcessType</key><string>Background</string>
10337
10853
  <key>LowPriorityIO</key><true/>
10338
10854
  </dict>
@@ -10343,19 +10859,19 @@ function cronLine(backend, everyMinutes, home = runnerHome()) {
10343
10859
  const cmd = scheduledCommand(backend);
10344
10860
  const when = everyMinutes >= 60 ? `17 */${Math.max(1, Math.round(everyMinutes / 60))} * * *` : `*/${everyMinutes} * * * *`;
10345
10861
  const q = (v) => `'${v.replace(/'/g, `'\\''`)}'`;
10346
- return `${when} cd ${q(home)} && PATH=${q(cmd.path)} ${cmd.argv.map(q).join(" ")} >> ${q(path24.join(home, "runner.log"))} 2>&1 ${CRON_MARK}`;
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}`;
10347
10863
  }
10348
10864
  function launchAgentsDir(opts) {
10349
- 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");
10350
10866
  }
10351
10867
  function installSchedule(backend, everyMinutes, opts = {}) {
10352
10868
  const platform = opts.platform ?? process.platform;
10353
10869
  const run2 = opts.run ?? realRun;
10354
10870
  if (platform === "darwin") {
10355
10871
  const dir2 = launchAgentsDir(opts);
10356
- const plist = path24.join(dir2, `${LAUNCHD_LABEL}.plist`);
10357
- fs29.mkdirSync(dir2, { recursive: true });
10358
- fs29.writeFileSync(plist, launchdPlist(backend, everyMinutes));
10872
+ const plist = path25.join(dir2, `${LAUNCHD_LABEL}.plist`);
10873
+ fs30.mkdirSync(dir2, { recursive: true });
10874
+ fs30.writeFileSync(plist, launchdPlist(backend, everyMinutes));
10359
10875
  const domain = `gui/${process.getuid?.() ?? 501}`;
10360
10876
  run2("launchctl", ["bootout", `${domain}/${LAUNCHD_LABEL}`]);
10361
10877
  const r = run2("launchctl", ["bootstrap", domain, plist]);
@@ -10375,10 +10891,10 @@ function removeSchedule(opts = {}) {
10375
10891
  const platform = opts.platform ?? process.platform;
10376
10892
  const run2 = opts.run ?? realRun;
10377
10893
  if (platform === "darwin") {
10378
- const plist = path24.join(launchAgentsDir(opts), `${LAUNCHD_LABEL}.plist`);
10894
+ const plist = path25.join(launchAgentsDir(opts), `${LAUNCHD_LABEL}.plist`);
10379
10895
  run2("launchctl", ["bootout", `gui/${process.getuid?.() ?? 501}/${LAUNCHD_LABEL}`]);
10380
- if (!fs29.existsSync(plist)) return "no schedule";
10381
- fs29.rmSync(plist, { force: true });
10896
+ if (!fs30.existsSync(plist)) return "no schedule";
10897
+ fs30.rmSync(plist, { force: true });
10382
10898
  return `removed ${plist}`;
10383
10899
  }
10384
10900
  const current = run2("crontab", ["-l"]);
@@ -10405,10 +10921,10 @@ async function install(args, cwd, out, err, opts = {}) {
10405
10921
  }
10406
10922
  const every = Math.max(15, Number(str5(args.flags.every) ?? 60) || 60);
10407
10923
  const home = runnerHome();
10408
- fs29.mkdirSync(home, { recursive: true, mode: 448 });
10924
+ fs30.mkdirSync(home, { recursive: true, mode: 448 });
10409
10925
  const saved = { apiUrl: c.apiUrl, key: c.key, backend, ...config.model && str5(args.flags.model) ? { model: config.model } : {}, name: c.name, every };
10410
- fs29.writeFileSync(path24.join(home, "config.json"), JSON.stringify(saved, null, 2) + "\n", { mode: 384 });
10411
- fs29.chmodSync(path24.join(home, "config.json"), 384);
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);
10412
10928
  let schedule;
10413
10929
  try {
10414
10930
  schedule = installSchedule(backend, every, opts);
@@ -10421,7 +10937,7 @@ Run it yourself: npx -y ${PKG2} runner --once
10421
10937
  out(`\u2713 Runner "${c.name}" answers ${c.apiUrl}'s model jobs with ${BACKEND_NAME[backend] ?? backend} on this computer.
10422
10938
  `);
10423
10939
  out(schedule.kind === "none" ? ` No scheduler here: run \`npx -y ${PKG2} runner --once\` on a schedule yourself.
10424
- ` : ` Every ${every} minutes while this computer is on (${schedule.kind}). Log: ${path24.join(home, "runner.log")}
10940
+ ` : ` Every ${every} minutes while this computer is on (${schedule.kind}). Log: ${path25.join(home, "runner.log")}
10425
10941
  `);
10426
10942
  out(` Stop: npx -y ${PKG2} runner uninstall
10427
10943
  `);
@@ -10438,10 +10954,10 @@ Answering what waits now\u2026
10438
10954
  function uninstall(out, opts = {}) {
10439
10955
  out(`${removeSchedule(opts)}
10440
10956
  `);
10441
- const file = path24.join(runnerHome(), "config.json");
10442
- if (fs29.existsSync(file)) {
10443
- fs29.rmSync(file, { force: true });
10444
- out(`removed ${file} (revoke the key in the console: Agent keys)
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)
10445
10961
  `);
10446
10962
  }
10447
10963
  return 0;
@@ -10615,17 +11131,17 @@ async function cmdRunner(args, cwd, out, err, opts = {}) {
10615
11131
  }
10616
11132
  const cmd = invocation();
10617
11133
  const text2 = renderJob(job, cmd);
10618
- const file = str5(args.flags.out);
10619
- if (!file) {
11134
+ const file2 = str5(args.flags.out);
11135
+ if (!file2) {
10620
11136
  out(text2);
10621
11137
  return 0;
10622
11138
  }
10623
- fs29.writeFileSync(file, text2, { mode: 384 });
11139
+ fs30.writeFileSync(file2, text2, { mode: 384 });
10624
11140
  const left = Math.round((Date.parse(job.leaseUntil) - Date.now()) / 6e4);
10625
11141
  out(
10626
11142
  [
10627
11143
  `JOB ${job.id} (${job.kind}), attempt ${job.attempts}, answer before ${job.leaseUntil} (${left} min left)`,
10628
- `written to ${file}: ${text2.split("\n").length.toLocaleString("en")} lines`,
11144
+ `written to ${file2}: ${text2.split("\n").length.toLocaleString("en")} lines`,
10629
11145
  `size and effort: ${effortOf(job)}`,
10630
11146
  ...jobIndex(text2).map((l) => ` ${l}`),
10631
11147
  `when done: ${cmd} runner validate ${job.id} <answer.json> && ${cmd} runner submit ${job.id} <answer.json>`,
@@ -10636,18 +11152,18 @@ async function cmdRunner(args, cwd, out, err, opts = {}) {
10636
11152
  }
10637
11153
  if (sub === "validate" || sub === "check") {
10638
11154
  const id = args._[2];
10639
- const file = args._[3] ?? "-";
11155
+ const file2 = args._[3] ?? "-";
10640
11156
  if (!id) throw new Error("usage: bunshin runner validate <job id> <file|->");
10641
- const text2 = file === "-" ? fs29.readFileSync(0, "utf8") : fs29.readFileSync(file, "utf8");
11157
+ const text2 = file2 === "-" ? fs30.readFileSync(0, "utf8") : fs30.readFileSync(file2, "utf8");
10642
11158
  const r = await call(c, "POST", `/jobs/${id}/check`, { answer: text2, runner: c.name }, 12e4);
10643
11159
  out(renderCheck(id, r.body));
10644
11160
  return r.body.ok ? 0 : 1;
10645
11161
  }
10646
11162
  if (sub === "submit") {
10647
11163
  const id = args._[2];
10648
- const file = args._[3] ?? "-";
11164
+ const file2 = args._[3] ?? "-";
10649
11165
  if (!id) throw new Error("usage: bunshin runner submit <job id> <file|-> [--force]");
10650
- const text2 = file === "-" ? fs29.readFileSync(0, "utf8") : fs29.readFileSync(file, "utf8");
11166
+ const text2 = file2 === "-" ? fs30.readFileSync(0, "utf8") : fs30.readFileSync(file2, "utf8");
10651
11167
  const check = await call(c, "POST", `/jobs/${id}/check`, { answer: text2, runner: c.name }, 12e4).catch(() => null);
10652
11168
  if (check?.body && (check.status < 400 || check.body.problems)) {
10653
11169
  out(renderCheck(id, check.body));
@@ -10671,7 +11187,7 @@ async function cmdRunner(args, cwd, out, err, opts = {}) {
10671
11187
  const since = Date.parse(str5(args.flags.since) ?? "") || Date.now() - 12 * 36e5;
10672
11188
  const entries = (() => {
10673
11189
  try {
10674
- return fs29.readFileSync(path24.join(runnerHome(), "log.jsonl"), "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l)).filter((e) => Date.parse(e.at) >= since);
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);
10675
11191
  } catch {
10676
11192
  return [];
10677
11193
  }
@@ -10741,8 +11257,8 @@ var init_runner = __esm({
10741
11257
 
10742
11258
  // src/v2/importer.ts
10743
11259
  import { execFileSync as execFileSync6 } from "node:child_process";
10744
- import fs30 from "node:fs";
10745
- import path25 from "node:path";
11260
+ import fs31 from "node:fs";
11261
+ import path26 from "node:path";
10746
11262
  function rewriteRepoPaths(text2, repoName2, pack) {
10747
11263
  const re = new RegExp(`(?<=^|[\\s\`'"(=:])(?:~|\\$\\{?[A-Za-z_][A-Za-z0-9_]*\\}?)?(?:/[\\w.@+-]+)*/${escapeRe(repoName2)}(?=[/\\s\`'")\\]]|[.,;:](?:\\s|$)|$)`, "gm");
10748
11264
  return text2.replace(re, `~/.bunshin/library/${pack}`);
@@ -10781,7 +11297,7 @@ function buildDocs(files, opts) {
10781
11297
  const main2 = `${dir2}/SKILL.md`;
10782
11298
  const text2 = rw(files.get(main2).content);
10783
11299
  const fm = frontmatterDescription(text2);
10784
- const name = path25.posix.basename(dir2);
11300
+ const name = path26.posix.basename(dir2);
10785
11301
  const bundle = {};
10786
11302
  for (const p of all.filter((x) => x.startsWith(`${dir2}/`))) {
10787
11303
  claimed.add(p);
@@ -10879,22 +11395,22 @@ function isGitRepo(root) {
10879
11395
  function workingTreeFiles(root) {
10880
11396
  const out = /* @__PURE__ */ new Map();
10881
11397
  const list2 = isGitRepo(root) ? git4(root, ["ls-files", "-z"]).split("\0").filter(Boolean) : (function walk(dir2, base = "") {
10882
- return fs30.readdirSync(dir2, { withFileTypes: true }).flatMap((e) => {
11398
+ return fs31.readdirSync(dir2, { withFileTypes: true }).flatMap((e) => {
10883
11399
  if (e.name === ".git" || e.name === "node_modules") return [];
10884
11400
  const rel = base ? `${base}/${e.name}` : e.name;
10885
- 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] : [];
10886
11402
  });
10887
11403
  })(root);
10888
11404
  for (const rel of list2) {
10889
- const abs = path25.join(root, rel);
11405
+ const abs = path26.join(root, rel);
10890
11406
  let buf;
10891
11407
  try {
10892
- buf = fs30.readFileSync(abs);
11408
+ buf = fs31.readFileSync(abs);
10893
11409
  } catch {
10894
11410
  continue;
10895
11411
  }
10896
11412
  if (!isText(buf)) continue;
10897
- const exec = (fs30.statSync(abs).mode & 73) !== 0;
11413
+ const exec = (fs31.statSync(abs).mode & 73) !== 0;
10898
11414
  out.set(rel, { content: buf.toString("utf8"), ...exec ? { mode: "x" } : {} });
10899
11415
  }
10900
11416
  return out;
@@ -10928,7 +11444,7 @@ function diffDocs(prev, next) {
10928
11444
  return { docs: next.filter((d) => before.get(d.path) !== fingerprint(d)), removed: [...before.keys()].filter((p) => !after.has(p)) };
10929
11445
  }
10930
11446
  function readSkillSystem(root, opts) {
10931
- const repoName2 = path25.basename(path25.resolve(root));
11447
+ const repoName2 = path26.basename(path26.resolve(root));
10932
11448
  const build = (files2) => buildDocs(files2, { pack: opts.pack, repoName: repoName2, ...opts.rewrite === false ? { rewrite: false } : {} });
10933
11449
  const tree = build(workingTreeFiles(root));
10934
11450
  if (!opts.history || !isGitRepo(root)) return { versions: [{ summary: `import ${opts.pack}`, docs: tree, removed: [], complete: true }], docs: tree };
@@ -11005,7 +11521,7 @@ var init_importer = __esm({
11005
11521
  escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
11006
11522
  looksGenerated = (text2) => /generated by|do not edit( by hand)?/i.test(text2.slice(0, 600));
11007
11523
  isStopHook = (text2) => /"decision"\s*:\s*"block"|decision.{0,4}block/.test(text2) && /REASON=/.test(text2);
11008
- isUpdateHook = (p, text2) => /auto-?update/i.test(path25.basename(p)) || /git (pull|fetch)/.test(text2) && /SessionStart|session start/i.test(text2);
11524
+ isUpdateHook = (p, text2) => /auto-?update/i.test(path26.basename(p)) || /git (pull|fetch)/.test(text2) && /SessionStart|session start/i.test(text2);
11009
11525
  fingerprint = (d) => JSON.stringify(d);
11010
11526
  REWRITE_SYSTEM = `You adapt a company's skill documents after its skill system moved into Bunshin.
11011
11527
 
@@ -11041,8 +11557,8 @@ __export(skills_exports, {
11041
11557
  cmdSkill: () => cmdSkill,
11042
11558
  parsePin: () => parsePin
11043
11559
  });
11044
- import fs31 from "node:fs";
11045
- import path26 from "node:path";
11560
+ import fs32 from "node:fs";
11561
+ import path27 from "node:path";
11046
11562
  function requireOnline(store, what) {
11047
11563
  if (!canCall(store.config())) throw new Error(`${what} needs the hosted library: run \`bunshin setup\` first`);
11048
11564
  }
@@ -11051,9 +11567,9 @@ async function cmdImport2(store, args, cwd, out, err) {
11051
11567
  err("usage: bunshin import skills <dir> [--pack <name>] [--layer org|team:<unit>] [--owner-team <unit>] [--no-history] [--dry-run] [--propose-rewrites]\n");
11052
11568
  return 1;
11053
11569
  }
11054
- const root = path26.resolve(cwd, args._[2]);
11055
- if (!fs31.existsSync(root)) throw new Error(`${root} does not exist`);
11056
- const pack = str6(args.flags.pack) ?? path26.basename(root);
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);
11057
11573
  const history = args.flags.history !== false && !bool4(args.flags["no-history"]);
11058
11574
  const read = readSkillSystem(root, { pack, history, ...str6(args.flags.since) ? { since: str6(args.flags.since) } : {} });
11059
11575
  const kinds = /* @__PURE__ */ new Map();
@@ -11088,7 +11604,7 @@ async function cmdImport2(store, args, cwd, out, err) {
11088
11604
  const propose = args.flags["propose-rewrites"];
11089
11605
  if (propose) {
11090
11606
  const only = typeof propose === "string" && propose !== "true" ? propose.split(",").map((x) => x.trim()).filter(Boolean) : [];
11091
- await proposeRewrites(store, read.docs.filter((d) => !only.length || only.some((o) => d.path.includes(o))), pack, path26.basename(root), out, err);
11607
+ await proposeRewrites(store, read.docs.filter((d) => !only.length || only.some((o) => d.path.includes(o))), pack, path27.basename(root), out, err);
11092
11608
  }
11093
11609
  out("Run `bunshin sync` on each machine (it runs at session start) to install the skills, instructions and files.\n");
11094
11610
  return 0;
@@ -11228,7 +11744,7 @@ ${report.skills} skills, ${report.references} references, ${report.errors.length
11228
11744
  }
11229
11745
  const graph = str6(args.flags.graph) ?? (bool4(args.flags.graph) ? "SKILLS-GRAPH.md" : void 0);
11230
11746
  if (graph) {
11231
- fs31.writeFileSync(path26.resolve(cwd, graph), renderSkillGraph(report));
11747
+ fs32.writeFileSync(path27.resolve(cwd, graph), renderSkillGraph(report));
11232
11748
  out(`graph written to ${graph}
11233
11749
  `);
11234
11750
  }
@@ -11250,12 +11766,138 @@ ${report.skills} skills, ${report.references} references, ${report.errors.length
11250
11766
  `);
11251
11767
  return r.errors.length ? 1 : 0;
11252
11768
  }
11769
+ case "split":
11770
+ return await splitSkill(store, args, byName(args._[2]), args._[2], out, err);
11253
11771
  default:
11254
- err(`bunshin skill: unknown subcommand "${sub}" (list, show, log, lint, push)
11772
+ err(`bunshin skill: unknown subcommand "${sub}" (list, show, log, lint, push, split)
11255
11773
  `);
11256
11774
  return 1;
11257
11775
  }
11258
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
+ }
11259
11901
  function sinceCutoff(since) {
11260
11902
  const m = /^(\d+)\.?(day|days|week|weeks|month|months|year|years)$/.exec(since.replace(/\s+/g, ""));
11261
11903
  if (m) {
@@ -11316,12 +11958,12 @@ async function cmdLibrary(store, args, cwd, out, err) {
11316
11958
  const res = await v2api(config, "GET", "/library?limit=1");
11317
11959
  const line = `bunshin: lib@${res.version}
11318
11960
  `;
11319
- const file = str6(args.flags.write) ?? (bool4(args.flags.write) ? ".claude/skills-version" : void 0);
11320
- if (file) {
11321
- const abs = path26.resolve(cwd, file);
11322
- fs31.mkdirSync(path26.dirname(abs), { recursive: true });
11323
- fs31.writeFileSync(abs, line);
11324
- out(`${file}: ${line}`);
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}`);
11325
11967
  } else out(line);
11326
11968
  return 0;
11327
11969
  }
@@ -11330,12 +11972,12 @@ async function cmdLibrary(store, args, cwd, out, err) {
11330
11972
  const to = str6(args.flags.to);
11331
11973
  if (!to) throw new Error("--to <dir> is required");
11332
11974
  const pinFile = str6(args.flags.pin);
11333
- const pin = str6(args.flags.git) ? { git: str6(args.flags.git) } : pinFile ? parsePin(fs31.readFileSync(path26.resolve(cwd, pinFile), "utf8")) : parsePin(args._[2] ?? "");
11975
+ const pin = str6(args.flags.git) ? { git: str6(args.flags.git) } : pinFile ? parsePin(fs32.readFileSync(path27.resolve(cwd, pinFile), "utf8")) : parsePin(args._[2] ?? "");
11334
11976
  const q = pin.git ? `git=${pin.git}` : pin.version ? `version=${pin.version}` : "";
11335
11977
  if (!q) throw new Error("name a version: lib@N, --git <sha>, or --pin <file>");
11336
11978
  const snap = await v2api(config, "GET", `/library/snapshot?${q}`, void 0, { timeoutMs: 12e4 });
11337
- const dir2 = path26.resolve(cwd, to);
11338
- if (fs31.existsSync(dir2) && fs31.readdirSync(dir2).length && !bool4(args.flags.force)) throw new Error(`${dir2} is not empty (use --force)`);
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)`);
11339
11981
  const pack = str6(args.flags.pack);
11340
11982
  const docs = snap.sections.filter((s) => !pack || s.pack === pack);
11341
11983
  const res = materialize(docs, dir2);
@@ -11349,7 +11991,7 @@ async function cmdLibrary(store, args, cwd, out, err) {
11349
11991
  return 1;
11350
11992
  }
11351
11993
  }
11352
- var str6, bool4, skillsOf;
11994
+ var str6, bool4, skillsOf, words3, splitPaths;
11353
11995
  var init_skills = __esm({
11354
11996
  "src/v2/skills.ts"() {
11355
11997
  "use strict";
@@ -11364,6 +12006,11 @@ var init_skills = __esm({
11364
12006
  str6 = (v) => typeof v === "string" ? v : void 0;
11365
12007
  bool4 = (v) => v === true || v === "true";
11366
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
+ };
11367
12014
  }
11368
12015
  });
11369
12016
 
@@ -11374,27 +12021,27 @@ __export(reflect_exports, {
11374
12021
  buildLesson: () => buildLesson,
11375
12022
  runReflection: () => runReflection
11376
12023
  });
11377
- import fs32 from "node:fs";
11378
- import path27 from "node:path";
12024
+ import fs33 from "node:fs";
12025
+ import path28 from "node:path";
11379
12026
  import { createHash as createHash10 } from "node:crypto";
11380
12027
  async function runReflection(store, opts) {
11381
12028
  const empty = { lessonIds: [], used: [], missed: [], attribution: [] };
11382
- 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`);
11383
12030
  const deadline = Date.now() + 66e4;
11384
12031
  for (; ; ) {
11385
12032
  try {
11386
- fs32.writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 });
12033
+ fs33.writeFileSync(lock, String(process.pid), { flag: "wx", mode: 384 });
11387
12034
  break;
11388
12035
  } catch (error) {
11389
12036
  if (error.code !== "EEXIST") throw error;
11390
12037
  try {
11391
- const owner = Number(fs32.readFileSync(lock, "utf8"));
12038
+ const owner = Number(fs33.readFileSync(lock, "utf8"));
11392
12039
  if (Number.isInteger(owner) && owner > 0) {
11393
12040
  try {
11394
12041
  process.kill(owner, 0);
11395
12042
  } catch (error2) {
11396
12043
  if (error2.code === "ESRCH") {
11397
- fs32.unlinkSync(lock);
12044
+ fs33.unlinkSync(lock);
11398
12045
  continue;
11399
12046
  }
11400
12047
  }
@@ -11409,7 +12056,7 @@ async function runReflection(store, opts) {
11409
12056
  return await reflectSession(store, opts);
11410
12057
  } finally {
11411
12058
  try {
11412
- fs32.unlinkSync(lock);
12059
+ fs33.unlinkSync(lock);
11413
12060
  } catch {
11414
12061
  }
11415
12062
  }
@@ -11749,10 +12396,11 @@ __export(cli_exports, {
11749
12396
  HELP: () => HELP2,
11750
12397
  main: () => main,
11751
12398
  parseArgs: () => parseArgs,
12399
+ setupMod: () => setupMod,
11752
12400
  version: () => version
11753
12401
  });
11754
- import fs33 from "node:fs";
11755
- import path28 from "node:path";
12402
+ import fs34 from "node:fs";
12403
+ import path29 from "node:path";
11756
12404
  function parseArgs(argv) {
11757
12405
  const out = { _: [], flags: {} };
11758
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"]);
@@ -11852,7 +12500,7 @@ async function main(argv, opts = {}) {
11852
12500
  if (harness !== "codex" && harness !== "claude-code" && harness !== "pi") throw new Error("Choose your agent: bunshin setup --harness codex, claude-code, or pi.");
11853
12501
  const agent = harness === "claude-code" ? "claude" : harness;
11854
12502
  if (!executable2(agent)) throw new Error(`${agent} was not found. Install and sign in to your agent, then run setup again.`);
11855
- const prior = new Store(path28.join(cwd, ".bunshin"));
12503
+ const prior = new Store(path29.join(cwd, ".bunshin"));
11856
12504
  const existing = prior.trusted ? prior.config() : { apiUrl: "", apiKey: void 0 };
11857
12505
  const apiUrl = str7(args.flags["api-url"]);
11858
12506
  const key = bool5(args.flags["key-stdin"]) ? await new Promise((resolve, reject) => {
@@ -11881,7 +12529,7 @@ async function main(argv, opts = {}) {
11881
12529
  });
11882
12530
  if (result.config.hooks === "user" && !only && !exclude && !bool5(args.flags.all) && process.stdin.isTTY && !bool5(args.flags["key-stdin"])) {
11883
12531
  const { askSources: askSources2 } = await Promise.resolve().then(() => (init_setup(), setup_exports));
11884
- await askSources2(new Store(path28.join(cwd, ".bunshin")), out);
12532
+ await askSources2(new Store(path29.join(cwd, ".bunshin")), out);
11885
12533
  }
11886
12534
  out(`Connected as ${result.profile.role}${result.profile.orgUnit ? ` in ${result.profile.orgUnit}` : " (company-wide)"}.
11887
12535
  `);
@@ -11899,6 +12547,7 @@ Key saved privately outside the project.
11899
12547
  `);
11900
12548
  else if (result.learnCommand?.error) out(`/learn not installed: ${result.learnCommand.error} (${result.learnCommand.file})
11901
12549
  `);
12550
+ if (harness === "claude-code" && result.hooks) out(await setupMod(result.config));
11902
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");
11903
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");
11904
12553
  else if (harness === "pi" && result.hooks) out("Open Pi in this project and approve its project extension. Check it with /bunshin status.\n");
@@ -11918,7 +12567,7 @@ Key saved privately outside the project.
11918
12567
  if (cmd === "mcp") {
11919
12568
  const { runMcpServer: runMcpServer2 } = await Promise.resolve().then(() => (init_mcp(), mcp_exports));
11920
12569
  const root = str7(args.flags.root);
11921
- 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() });
11922
12571
  return 0;
11923
12572
  }
11924
12573
  if (cmd === "demo") {
@@ -12010,6 +12659,8 @@ Key saved privately outside the project.
12010
12659
  return await (await Promise.resolve().then(() => (init_skills(), skills_exports))).cmdSkill(store, args, cwd, out, err);
12011
12660
  case "library":
12012
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);
12013
12664
  case "ui":
12014
12665
  return await (await Promise.resolve().then(() => (init_uicmd(), uicmd_exports))).cmdUi(store, args, out, err, version());
12015
12666
  case "sources":
@@ -12030,7 +12681,7 @@ ${HELP2}`);
12030
12681
  function openStore(args, cwd) {
12031
12682
  const root = str7(args.flags.root);
12032
12683
  if (root) {
12033
- const store = new Store(path28.resolve(root));
12684
+ const store = new Store(path29.resolve(root));
12034
12685
  store.ensureLayout();
12035
12686
  return store;
12036
12687
  }
@@ -12046,7 +12697,7 @@ async function cmdInit(args, cwd, out, err) {
12046
12697
  orgId: str7(args.flags["org-id"]),
12047
12698
  userId: str7(args.flags["user-id"]),
12048
12699
  apiUrl: str7(args.flags["api-url"]),
12049
- apiKey: bool5(args.flags["key-stdin"]) ? fs33.readFileSync(0, "utf8").trim() || void 0 : str7(args.flags["api-key"]),
12700
+ apiKey: bool5(args.flags["key-stdin"]) ? fs34.readFileSync(0, "utf8").trim() || void 0 : str7(args.flags["api-key"]),
12050
12701
  scope: bool5(args.flags.global) ? "global" : str7(args.flags.scope),
12051
12702
  harness,
12052
12703
  noHooks: args.flags.hooks === false || bool5(args.flags["no-hooks"]),
@@ -12089,14 +12740,14 @@ function cmdStatus(store, args, out, v2) {
12089
12740
  const conflicts = store.listConflicts().filter((c) => c.status === "open");
12090
12741
  const metrics = store.readMetrics(void 0);
12091
12742
  const last50 = metrics?.windows?.find((w) => w.name === "last50");
12092
- const hookFiles = config.harness === "codex" ? [.../* @__PURE__ */ new Set([path28.join(process.env.CODEX_HOME ?? path28.join(homeDir(), ".codex"), "hooks.json"), codexProjectHooks(path28.dirname(store.root)).file])] : config.harness === "claude-code" ? [path28.join(homeDir(), ".claude", "settings.json"), path28.join(path28.dirname(store.root), ".claude", "settings.local.json")] : config.harness === "pi" ? [path28.join(homeDir(), ".pi/agent/extensions/bunshin.js"), path28.join(path28.dirname(store.root), ".pi/extensions/bunshin.js")] : [];
12093
- const hooks = config.harness === "pi" ? hookFiles.filter((file) => {
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) => {
12094
12745
  try {
12095
- return fs33.readFileSync(file, "utf8").startsWith("// Managed by Bunshin setup.");
12746
+ return fs34.readFileSync(file2, "utf8").startsWith("// Managed by Bunshin setup.");
12096
12747
  } catch {
12097
12748
  return false;
12098
12749
  }
12099
- }).length : hookFiles.reduce((total, file) => total + hookCount(file), 0);
12750
+ }).length : hookFiles.reduce((total, file2) => total + hookCount(file2), 0);
12100
12751
  const served = lessons.reduce((n, l) => n + l.stats.served, 0);
12101
12752
  const used = lessons.reduce((n, l) => n + l.stats.used, 0);
12102
12753
  const status = {
@@ -12109,8 +12760,9 @@ function cmdStatus(store, args, out, v2) {
12109
12760
  conflictsOpen: conflicts.length,
12110
12761
  mothership: config.apiUrl ? { apiUrl: config.apiUrl, key: config.apiKey ? "set" : "missing", lastSyncAt: config.lastSyncAt ?? null } : null,
12111
12762
  llmBackend: resolveBackend(config) ?? "none (set ANTHROPIC_API_KEY or install the claude/codex CLI)",
12763
+ recallRouter: recallRouter(config),
12112
12764
  hooks: { [config.harness]: hooks },
12113
- hookFiles: hookFiles.filter((file) => fs33.existsSync(file)),
12765
+ hookFiles: hookFiles.filter((file2) => fs34.existsSync(file2)),
12114
12766
  recallQuality: last50 ? { precision: last50.precision, recall: last50.recall, f1: last50.f1, traces: last50.traces } : null,
12115
12767
  v2
12116
12768
  };
@@ -12144,6 +12796,8 @@ function cmdStatus(store, args, out, v2) {
12144
12796
  out(`mothership ${config.apiUrl ? `${config.apiUrl} (key ${config.apiKey ? "set" : "MISSING"}, last sync ${config.lastSyncAt ?? "never"})` : "local only"}
12145
12797
  `);
12146
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"}
12147
12801
  `);
12148
12802
  out(`hooks ${config.harness}: ${hooks > 0 ? `${hooks} configured` : "not detected"}${config.harness === "codex" ? " (requires Codex hook trust)" : ""}
12149
12803
  `);
@@ -12151,9 +12805,9 @@ function cmdStatus(store, args, out, v2) {
12151
12805
  `);
12152
12806
  return 0;
12153
12807
  }
12154
- function hookCount(file) {
12808
+ function hookCount(file2) {
12155
12809
  try {
12156
- const raw = JSON.parse(fs33.readFileSync(file, "utf8"));
12810
+ const raw = JSON.parse(fs34.readFileSync(file2, "utf8"));
12157
12811
  let n = 0;
12158
12812
  for (const groups of Object.values(raw.hooks ?? {})) {
12159
12813
  for (const g of groups ?? []) {
@@ -12273,7 +12927,7 @@ function cmdLessonAdd(store, args, out, err) {
12273
12927
  let content = str7(args.flags.content) ?? "";
12274
12928
  if (!content || content === "-" || args._.includes("-")) {
12275
12929
  try {
12276
- content = fs33.readFileSync(0, "utf8");
12930
+ content = fs34.readFileSync(0, "utf8");
12277
12931
  } catch {
12278
12932
  }
12279
12933
  }
@@ -12339,7 +12993,7 @@ async function cmdReflect(store, args, cwd, out, err) {
12339
12993
  }
12340
12994
  const { runReflection: runReflection2 } = await Promise.resolve().then(() => (init_reflect4(), reflect_exports));
12341
12995
  const result = await runReflection2(store, {
12342
- sessionId: str7(args.flags.session) ?? path28.basename(transcript).replace(/\.jsonl?$/, ""),
12996
+ sessionId: str7(args.flags.session) ?? path29.basename(transcript).replace(/\.jsonl?$/, ""),
12343
12997
  transcriptPath: transcript,
12344
12998
  cwd,
12345
12999
  force: bool5(args.flags.force)
@@ -12445,6 +13099,30 @@ async function cmdConflict(store, args, out, err) {
12445
13099
  function store0HasKey(store) {
12446
13100
  return !!store.config().apiKey;
12447
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
+ }
12448
13126
  var str7, bool5, HELP2, untrustedNote;
12449
13127
  var init_cli = __esm({
12450
13128
  "src/cli.ts"() {
@@ -12502,6 +13180,11 @@ Usage: bunshin <command> [options]
12502
13180
  tools, history) into the library; the repository can then go
12503
13181
  skill list|show <name>|log [name] [--since 3.months]|lint [--graph [file]]|push [name] [--layer L]
12504
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
12505
13188
  library version|log|status|pin [--write [file]]|checkout <lib@N> --to <dir> [--git <sha>] [--pin <file>]
12506
13189
  library versions (lib@N), history, and exact reproductions
12507
13190
  library workspace (retired: each workspace keeps its own skills and links them into
@@ -12542,7 +13225,7 @@ Global: --root <dir> (use this .bunshin store) --version --help
12542
13225
  Env: BUNSHIN_API_KEY, BUNSHIN_HARNESS, BUNSHIN_DISABLE, BUNSHIN_CHILD, BUNSHIN_CLAUDE_BIN,
12543
13226
  CLAUDE_CODE_SESSION_ID (learn / mcp session), ANTHROPIC_API_KEY (non-fork reflection)
12544
13227
  `;
12545
- untrustedNote = (root) => `${root} was not created by you (e.g. it is committed to the repository), so Bunshin ignores it. If it is yours, run \`bunshin setup\` (or \`bunshin init\`) in ${path28.dirname(root)} to trust it.`;
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.`;
12546
13229
  }
12547
13230
  });
12548
13231