@bunshin-cc/bunshin 0.13.0 → 0.13.1

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 +86 -35
  2. package/package.json +1 -1
package/dist/bin.js CHANGED
@@ -1115,14 +1115,14 @@ function isScopeLayer(layer) {
1115
1115
  return k === "group" || k === "source";
1116
1116
  }
1117
1117
  function groupChain(tree, groupId) {
1118
- const byId = new Map(tree.groups.map((g) => [g.id, g]));
1118
+ const byId2 = new Map(tree.groups.map((g) => [g.id, g]));
1119
1119
  const out = [];
1120
1120
  const seen = /* @__PURE__ */ new Set();
1121
- let cur = groupId ? byId.get(groupId) : void 0;
1121
+ let cur = groupId ? byId2.get(groupId) : void 0;
1122
1122
  while (cur && !seen.has(cur.id)) {
1123
1123
  seen.add(cur.id);
1124
1124
  out.unshift(cur.id);
1125
- cur = cur.parent ? byId.get(cur.parent) : void 0;
1125
+ cur = cur.parent ? byId2.get(cur.parent) : void 0;
1126
1126
  }
1127
1127
  return out;
1128
1128
  }
@@ -1852,15 +1852,15 @@ var init_text_index = __esm({
1852
1852
 
1853
1853
  // ../core/src/v2/recall/engine.ts
1854
1854
  function servable(sections, reader) {
1855
- const byId = new Map(sections.map((s) => [s.id, s]));
1855
+ const byId2 = new Map(sections.map((s) => [s.id, s]));
1856
1856
  const out = /* @__PURE__ */ new Map();
1857
1857
  for (const s of sections) {
1858
1858
  if (s.status === "superseded" || s.status === "retired" || s.status === "pending") continue;
1859
- if (s.supersededBy && byId.get(s.supersededBy)?.status === "active") continue;
1859
+ if (s.supersededBy && byId2.get(s.supersededBy)?.status === "active") continue;
1860
1860
  if (!canRead(s, reader)) continue;
1861
1861
  let chosen = s;
1862
1862
  if (s.canonicalRoot && s.canonicalRoot !== s.id) {
1863
- const root = byId.get(s.canonicalRoot);
1863
+ const root = byId2.get(s.canonicalRoot);
1864
1864
  if (root && root.status !== "retired" && canRead(root, reader)) chosen = root;
1865
1865
  }
1866
1866
  out.set(chosen.id, chosen);
@@ -2159,8 +2159,8 @@ function cardsOf(spine, sections) {
2159
2159
  function renderCardIndex(spine, cards, opts = {}) {
2160
2160
  if (!cards.length) return "";
2161
2161
  const stepTitle = new Map((spine.outline ?? []).map((h) => [h.anchor, h.title]));
2162
- const oneLine = (t) => t.replace(/\s+/g, " ").trim().slice(0, 240);
2163
- 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)}`);
2162
+ const oneLine2 = (t) => t.replace(/\s+/g, " ").trim().slice(0, 240);
2163
+ const lines = cards.map((c) => `- ${c.title} (${c.kind}, id: ${c.id}${c.step ? `, step: ${stepTitle.get(c.step) ?? c.step}` : ""}) \u2014 when: ${oneLine2(c.when || c.title)}`);
2164
2164
  const load = opts.mcp ? `bunshin_load {"section_id": "<id>"}` : "`bunshin load <id>`";
2165
2165
  return [
2166
2166
  `### CARDS of ${spine.skill ? `the \`${spine.skill.name}\` skill` : spine.title}`,
@@ -2246,10 +2246,10 @@ function parseSplit(raw) {
2246
2246
  }
2247
2247
  function withSpineAtoms(chosen, sections, max = 30) {
2248
2248
  const have = new Set(chosen.map((s) => s.id));
2249
- const byId = new Map(sections.map((s) => [s.id, s]));
2249
+ const byId2 = new Map(sections.map((s) => [s.id, s]));
2250
2250
  const extra = [];
2251
2251
  for (const c of chosen) {
2252
- const s = byId.get(c.id);
2252
+ const s = byId2.get(c.id);
2253
2253
  if (!s?.skill) continue;
2254
2254
  for (const a of cardsOf(s, sections)) if (!have.has(a.id) && extra.length < max) have.add(a.id), extra.push(a);
2255
2255
  }
@@ -2312,6 +2312,33 @@ var init_atoms = __esm({
2312
2312
  });
2313
2313
 
2314
2314
  // ../core/src/v2/recall/router.ts
2315
+ function indexItems(pool) {
2316
+ const sorted = [...pool].sort(byId);
2317
+ const item = (s, kind) => `<item id="${attr(s.id)}" kind="${kind}" title="${attr(s.skill?.name ?? s.title)}">
2318
+ WHEN: ${whenOf(s)}
2319
+ </item>`;
2320
+ const names = new Map(pool.map((s) => [s.id, s.skill?.name ?? s.title]));
2321
+ const atomKind = (s) => s.kind === "card" ? `card${s.partOf && names.has(s.partOf) ? ` of ${attr(names.get(s.partOf))}` : ""}` : s.kind === "fact" ? "fact" : "lesson";
2322
+ return { docs: sorted.filter((s) => !isLesson(s)).map((s) => item(s, s.skill ? "skill" : s.kind)), atoms: sorted.filter(isLesson).map((s) => item(s, atomKind(s))) };
2323
+ }
2324
+ function withRecent(system, recent) {
2325
+ if (!recent.length) return system;
2326
+ const { docs, atoms } = indexItems(recent);
2327
+ const at = system.lastIndexOf(ATOMS_HEADER);
2328
+ const docsAt = system.lastIndexOf(DOCS_HEADER);
2329
+ if (at < 0 || docsAt < 0 || docsAt > at) return system;
2330
+ const listed = (block2, extra) => [block2.trim() === "(none)" ? "" : block2.trim(), ...extra].filter(Boolean).join("\n\n") || "(none)";
2331
+ const head = system.slice(0, docsAt);
2332
+ const docBlock = system.slice(docsAt + DOCS_HEADER.length, at);
2333
+ const atomBlock = system.slice(at + ATOMS_HEADER.length);
2334
+ return `${head}${DOCS_HEADER}
2335
+
2336
+ ${listed(docBlock, docs)}
2337
+
2338
+ ${ATOMS_HEADER}
2339
+
2340
+ ${listed(atomBlock, atoms)}`;
2341
+ }
2315
2342
  function routerMessage(prompt, ctx, inContext2) {
2316
2343
  const lines = ["Session context:"];
2317
2344
  lines.push(ctx.first ? `- First prompt of this session: ${ctx.first.slice(0, 600)}` : "- This is the first prompt of the session.");
@@ -2350,19 +2377,21 @@ function parseRouterAnswer(text2, items, skip = []) {
2350
2377
  return null;
2351
2378
  }
2352
2379
  const skipped = new Set(skip);
2353
- const byId = new Map(items.filter((i) => !skipped.has(i.id)).map((i) => [i.id, i]));
2354
- const ids = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "string" && byId.has(x)) : [];
2355
- const serve = typeof o.serve === "string" && byId.has(o.serve) ? o.serve : void 0;
2356
- const rules = [...new Set(ids(o.rules).filter((id) => byId.get(id).lesson && id !== serve))].slice(0, MAX_RULES);
2380
+ const byId2 = new Map(items.filter((i) => !skipped.has(i.id)).map((i) => [i.id, i]));
2381
+ const ids = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "string" && byId2.has(x)) : [];
2382
+ const serve = typeof o.serve === "string" && byId2.has(o.serve) ? o.serve : void 0;
2383
+ const rules = [...new Set(ids(o.rules).filter((id) => byId2.get(id).lesson && id !== serve))].slice(0, MAX_RULES);
2357
2384
  const hint = ids(o.hints).filter((id) => id !== serve && !rules.includes(id)).slice(0, 2);
2358
2385
  return { ...serve ? { serve } : {}, rules, hint };
2359
2386
  }
2360
- var MAX_RULES, RULES;
2387
+ var MAX_RULES, WHEN_CHARS, isLesson, RULES, oneLine, whenOf, attr, routerItems, DOCS_HEADER, ATOMS_HEADER, byId;
2361
2388
  var init_router = __esm({
2362
2389
  "../core/src/v2/recall/router.ts"() {
2363
2390
  "use strict";
2364
2391
  init_atoms();
2365
2392
  MAX_RULES = 3;
2393
+ WHEN_CHARS = 400;
2394
+ isLesson = (s) => isAtom(s);
2366
2395
  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).
2367
2396
 
2368
2397
  - "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.
@@ -2370,6 +2399,13 @@ var init_router = __esm({
2370
2399
  - "hints": up to 2 other possibly relevant document ids, shown as titles only.
2371
2400
 
2372
2401
  Only use ids from the library. Output exactly one line of JSON and nothing else: {"serve": "<id or null>", "rules": ["<atom id>", ...], "hints": ["<id>", ...]}`;
2402
+ oneLine = (t) => t.replace(/\s+/g, " ").trim();
2403
+ whenOf = (s) => oneLine(s.skill ? s.skill.description : s.when || s.title).slice(0, WHEN_CHARS);
2404
+ attr = (t) => oneLine(t).replace(/"/g, "'");
2405
+ routerItems = (pool) => pool.map((s) => ({ id: s.id, lesson: isLesson(s) }));
2406
+ DOCS_HEADER = "LIBRARY: SKILLS AND DOCUMENTS";
2407
+ ATOMS_HEADER = "LIBRARY: ATOMS (LESSONS, FACTS, CARDS)";
2408
+ byId = (a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
2373
2409
  }
2374
2410
  });
2375
2411
 
@@ -3858,7 +3894,7 @@ function matchingRecallLessons(task, rules) {
3858
3894
  }
3859
3895
  function prepareRecall(inputs, request, profile, rules = [], opts = {}) {
3860
3896
  const recallLessons = matchingRecallLessons(request.task, rules);
3861
- const byId = /* @__PURE__ */ new Map();
3897
+ const byId2 = /* @__PURE__ */ new Map();
3862
3898
  for (const { lesson, relevance } of inputs) {
3863
3899
  if (!canSee(lesson, profile) || !["active", "stale", "conflicted"].includes(lesson.status) || opts.excludeIds?.has(lesson.id)) continue;
3864
3900
  const lexical = lexicalRelevance(lesson, request.task);
@@ -3875,10 +3911,10 @@ function prepareRecall(inputs, request, profile, rules = [], opts = {}) {
3875
3911
  if (Math.max(taskRelevance, expanded) <= 0) continue;
3876
3912
  const result = score(lesson, request, profile, Math.max(taskRelevance, expanded), opts);
3877
3913
  const candidate = { lessonId: lesson.id, lesson, score: result.score, reasons: [...result.reasons, ...reasons], taskRelevance };
3878
- const previous = byId.get(lesson.id);
3879
- if (!previous || previous.lesson.version < lesson.version || previous.lesson.version === lesson.version && previous.score < candidate.score) byId.set(lesson.id, candidate);
3914
+ const previous = byId2.get(lesson.id);
3915
+ if (!previous || previous.lesson.version < lesson.version || previous.lesson.version === lesson.version && previous.score < candidate.score) byId2.set(lesson.id, candidate);
3880
3916
  }
3881
- const candidates = [...byId.values()].sort((a, b) => b.score - a.score || a.lessonId.localeCompare(b.lessonId)).slice(0, opts.poolSize ?? 30);
3917
+ const candidates = [...byId2.values()].sort((a, b) => b.score - a.score || a.lessonId.localeCompare(b.lessonId)).slice(0, opts.poolSize ?? 30);
3882
3918
  return { candidates, recallLessons };
3883
3919
  }
3884
3920
  function fallbackRecall(candidates, limit) {
@@ -6064,8 +6100,8 @@ function localView(v2, config, cwd, opts = {}) {
6064
6100
  source = void 0;
6065
6101
  }
6066
6102
  const reader = readerFor(ctx, void 0, { ...source ? { source } : {}, ...bundle?.scopes ? { tree: bundle.scopes } : {} });
6067
- const byId = /* @__PURE__ */ new Map();
6068
- for (const s of bundle?.sections ?? []) byId.set(s.id, s);
6103
+ const byId2 = /* @__PURE__ */ new Map();
6104
+ for (const s of bundle?.sections ?? []) byId2.set(s.id, s);
6069
6105
  let root = cwd;
6070
6106
  let repo = "";
6071
6107
  if (opts.index !== false) {
@@ -6074,8 +6110,8 @@ function localView(v2, config, cwd, opts = {}) {
6074
6110
  root = idx.root;
6075
6111
  repo = idx.index.repo;
6076
6112
  for (const s of idx.sections) {
6077
- const upstream = byId.get(s.id);
6078
- byId.set(s.id, upstream ? { ...upstream, ...s, stats: upstream.stats, situations: upstream.situations, experience: upstream.experience } : s);
6113
+ const upstream = byId2.get(s.id);
6114
+ byId2.set(s.id, upstream ? { ...upstream, ...s, stats: upstream.stats, situations: upstream.situations, experience: upstream.experience } : s);
6079
6115
  }
6080
6116
  } catch {
6081
6117
  }
@@ -6083,10 +6119,10 @@ function localView(v2, config, cwd, opts = {}) {
6083
6119
  const overlays = v2.readOverlays();
6084
6120
  if (bundle?.pending?.length) {
6085
6121
  const local = /* @__PURE__ */ new Set([...overlays.map((o) => o.suggestionId), ...v2.listSuggestions().map((s) => s.id)]);
6086
- applyPending(byId, bundle.pending, local);
6122
+ applyPending(byId2, bundle.pending, local);
6087
6123
  }
6088
- applyOverlays(byId, overlays, ctx);
6089
- return { ctx, reader, ...source ? { source } : {}, layers: reader.layers, bundle, sections: [...byId.values()], byId, root, repo };
6124
+ applyOverlays(byId2, overlays, ctx);
6125
+ return { ctx, reader, ...source ? { source } : {}, layers: reader.layers, bundle, sections: [...byId2.values()], byId: byId2, root, repo };
6090
6126
  }
6091
6127
  var ACTIVE_OVERLAY;
6092
6128
  var init_view = __esm({
@@ -7376,6 +7412,7 @@ __export(route_exports, {
7376
7412
  readAnswer: () => readAnswer,
7377
7413
  readJob: () => readJob,
7378
7414
  readStats: () => readStats,
7415
+ recentSections: () => recentSections,
7379
7416
  routeJob: () => routeJob,
7380
7417
  sweepRouter: () => sweepRouter,
7381
7418
  writeJob: () => writeJob
@@ -7526,8 +7563,12 @@ async function askRouter(store, v2, sessionId, model, kind) {
7526
7563
  const index = await routerIndex(store, v2, session.source ?? "");
7527
7564
  if (!/^[\w-]{1,64}$/.test(index.hash)) return { picks: { error: "the router index came back with a malformed hash" } };
7528
7565
  indexHash = index.hash;
7529
- const systemFile = path13.join(dir(v2), `system-${index.hash}.txt`);
7530
- if (!fs17.existsSync(systemFile)) fs17.writeFileSync(systemFile, index.system);
7566
+ const recent = recentSections(v2, store.config(), session, index.items);
7567
+ const system = withRecent(index.system, recent);
7568
+ const items = recent.length ? [...index.items, ...routerItems(recent)] : index.items;
7569
+ const name = recent.length ? `${index.hash}-${createHash5("sha256").update(system).digest("hex").slice(0, 12)}` : index.hash;
7570
+ const systemFile = path13.join(dir(v2), `system-${name}.txt`);
7571
+ if (!fs17.existsSync(systemFile)) fs17.writeFileSync(systemFile, system);
7531
7572
  const cwd = path13.join(dir(v2), "cwd");
7532
7573
  fs17.mkdirSync(cwd, { recursive: true });
7533
7574
  const inContext2 = session.inContext ?? [...session.loaded, ...session.pushed];
@@ -7539,13 +7580,22 @@ async function askRouter(store, v2, sessionId, model, kind) {
7539
7580
  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 } : {} };
7540
7581
  const meta = { ...res.duration_ms ? { modelMs: res.duration_ms } : {}, usage, ...typeof res.total_cost_usd === "number" ? { costUsd: res.total_cost_usd } : {} };
7541
7582
  if (res.is_error) return { picks: { ...meta, error: `claude: ${(res.result ?? "error").slice(0, 300)}` }, indexHash };
7542
- const picks = parseRouterAnswer(res.result ?? "", index.items, inContext2);
7583
+ const picks = parseRouterAnswer(res.result ?? "", items, inContext2);
7543
7584
  if (!picks) return { picks: { ...meta, error: `not JSON: ${(res.result ?? "").slice(0, 120)}` }, indexHash };
7544
7585
  return { picks: { ...picks, ...meta }, indexHash };
7545
7586
  } catch (err) {
7546
7587
  return { picks: { error: (err instanceof Error ? err.message : String(err)).slice(0, 300) }, ...indexHash ? { indexHash } : {} };
7547
7588
  }
7548
7589
  }
7590
+ function recentSections(v2, config, session, known) {
7591
+ try {
7592
+ const have = new Set(known.map((i) => i.id));
7593
+ const view = localView(v2, config, session.cwd, { index: false, ...session.source !== void 0 ? { source: session.source } : {} });
7594
+ return recallable(view.sections, view.reader).filter((s) => !have.has(s.id) && (s.localTrial?.length ?? 0) > 0);
7595
+ } catch {
7596
+ return [];
7597
+ }
7598
+ }
7549
7599
  async function recordStats(v2, sessionId, a, model, indexHash) {
7550
7600
  let release = null;
7551
7601
  for (let i = 0; i < 40 && !(release = v2.tryLock("router-stats", 3e4)); i++) await new Promise((r) => setTimeout(r, 50));
@@ -7594,6 +7644,7 @@ var init_route = __esm({
7594
7644
  init_util();
7595
7645
  init_api();
7596
7646
  init_store2();
7647
+ init_view();
7597
7648
  ROUTER_MODEL = "claude-haiku-5-5";
7598
7649
  INDEX_TTL_MS = 10 * 6e4;
7599
7650
  CLAUDE_TIMEOUT_MS = 6e4;
@@ -10682,7 +10733,7 @@ async function runRecall(store, opts) {
10682
10733
  };
10683
10734
  const connected = canSync(config) && config.recall.useMothership;
10684
10735
  const local = store.listLessons().filter((l) => !connected || l.provenance.userId === config.userId && l.provenance.orgId === config.orgId);
10685
- const byId = new Map(local.map((l) => [l.id, l]));
10736
+ const byId2 = new Map(local.map((l) => [l.id, l]));
10686
10737
  const rules = new Map(store.listRecallLessons().map((r) => [r.id, r]));
10687
10738
  let degraded;
10688
10739
  if (connected && !opts.offline) {
@@ -10705,12 +10756,12 @@ async function runRecall(store, opts) {
10705
10756
  const lookupOK = lookup && sameIdentity(lookup.profile);
10706
10757
  if (remoteOK || lookupOK) {
10707
10758
  profile = (remoteOK ? remote.profile : void 0) ?? (lookupOK ? lookup.profile : void 0) ?? profile;
10708
- byId.clear();
10759
+ byId2.clear();
10709
10760
  const refreshed = /* @__PURE__ */ new Map();
10710
10761
  if (lookupOK) {
10711
10762
  const unavailable = new Set(lookup.unavailableIds);
10712
10763
  for (const lesson of cached) {
10713
- if (unavailable.has(lesson.id) && lesson.version === 1 && (!config.lastSyncAt || lesson.provenance.createdAt > config.lastSyncAt)) byId.set(lesson.id, lesson);
10764
+ if (unavailable.has(lesson.id) && lesson.version === 1 && (!config.lastSyncAt || lesson.provenance.createdAt > config.lastSyncAt)) byId2.set(lesson.id, lesson);
10714
10765
  }
10715
10766
  for (const lesson of lookup.lessons) {
10716
10767
  if (cachedIds.has(lesson.id) && lesson.provenance.orgId === profile.orgId) refreshed.set(lesson.id, lesson);
@@ -10724,7 +10775,7 @@ async function runRecall(store, opts) {
10724
10775
  if (!checked || lesson.version > checked.version) refreshed.set(lesson.id, lesson);
10725
10776
  }
10726
10777
  for (const lesson of refreshed.values()) {
10727
- byId.set(lesson.id, lesson);
10778
+ byId2.set(lesson.id, lesson);
10728
10779
  if (!opts.dryRun) store.saveLesson(lesson, { reindex: false });
10729
10780
  }
10730
10781
  for (const rule of remoteOK ? remote.recallLessons : []) rules.set(rule.id, rule);
@@ -10739,7 +10790,7 @@ async function runRecall(store, opts) {
10739
10790
  }
10740
10791
  const fresh = new Set(Object.entries(state.servedAt).filter(([, turn]) => state.turn - turn < FRESH_TURNS).map(([id]) => id));
10741
10792
  const request = { task, userId: profile.userId, role: profile.role, orgUnit: profile.orgUnit, recentContext: history };
10742
- const prepared = prepareRecall([...byId.values()].map((lesson) => ({ lesson })), request, profile, [...rules.values()], { excludeIds: fresh });
10793
+ const prepared = prepareRecall([...byId2.values()].map((lesson) => ({ lesson })), request, profile, [...rules.values()], { excludeIds: fresh });
10743
10794
  const { candidates, recallLessons } = prepared;
10744
10795
  let selection;
10745
10796
  let selectedIds = fallbackRecall(candidates, config.recall.maxLessons);
@@ -10769,7 +10820,7 @@ async function runRecall(store, opts) {
10769
10820
  degraded = [degraded, response.error].filter(Boolean).join("; ");
10770
10821
  }
10771
10822
  }
10772
- const served = selectedIds.map((id) => byId.get(id));
10823
+ const served = selectedIds.map((id) => byId2.get(id));
10773
10824
  const trace = {
10774
10825
  id: newId("t"),
10775
10826
  sessionId: opts.sessionId,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bunshin-cc/bunshin",
3
- "version": "0.13.0",
3
+ "version": "0.13.1",
4
4
  "description": "Shared memory for company AI agents. Connect Codex, Claude Code, or Pi to Bunshin.",
5
5
  "type": "module",
6
6
  "bin": {