@bunshin-cc/bunshin 0.12.1 → 0.12.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 +75 -15
  2. package/package.json +1 -1
package/dist/bin.js CHANGED
@@ -2406,7 +2406,7 @@ anchor "${GUIDELINES_ANCHOR}", one general rule in the imperative, with the reas
2406
2406
 
2407
2407
  ${rules}${route}`;
2408
2408
  }
2409
- var GUIDELINES_ANCHOR, generality;
2409
+ var GUIDELINES_ID, GUIDELINES_ANCHOR, generality;
2410
2410
  var init_guidelines = __esm({
2411
2411
  "../core/src/v2/guidelines.ts"() {
2412
2412
  "use strict";
@@ -2414,6 +2414,7 @@ var init_guidelines = __esm({
2414
2414
  init_layers();
2415
2415
  init_engine();
2416
2416
  init_scopes();
2417
+ GUIDELINES_ID = "reflection:guidelines";
2417
2418
  GUIDELINES_ANCHOR = "rules";
2418
2419
  generality = (l) => ({ org: 0, group: 1, source: 2, robot: 3, user: 3 })[layerKind(l)] ?? 4;
2419
2420
  }
@@ -3146,6 +3147,30 @@ learned about the code or the company), at most 6, most important first: name ea
3146
3147
  say whether it became a lesson or was skipped, and why in one sentence. People read this to see
3147
3148
  what reflection noticed and to steer it; list them even when nothing is new.`;
3148
3149
  }
3150
+ function runSection(r) {
3151
+ const list2 = (xs) => xs.length ? xs.map((x) => `- ${x}`).join("\n") : "- (none)";
3152
+ return `
3153
+ The feedback is about one earlier reflection run on this session (${r.at}${r.turns ? `, turns ${r.turns.from + 1}\u2013${r.turns.to}` : ""}). This is what it did:
3154
+
3155
+ What it considered:
3156
+ ${list2(r.considered.map((c) => `${c.decision === "lesson" ? "took as a lesson" : "skipped"}: ${c.moment} (${c.why})`))}
3157
+
3158
+ What it kept:
3159
+ ${list2(r.kept)}
3160
+ ${r.dropped.length ? `
3161
+ What it proposed that was refused:
3162
+ ${list2(r.dropped.map((d) => `${d.summary} (${d.reason})`))}
3163
+ ` : ""}${r.nothingNew ? "\nIt answered that the turns taught nothing new.\n" : ""}
3164
+ That run did not take what the person expected. Before proposing anything, work out from the
3165
+ above why it missed it: it never noticed the moment (not in what it considered), it noticed and
3166
+ skipped it (on what reasoning), or it took a weaker or wrong lesson. Then propose:
3167
+ 1. the lesson it should have taken, written as the guidelines ask; and
3168
+ 2. a rule for the reflection guidelines (op "append" to ${GUIDELINES_ID}, anchor "rules") that would
3169
+ make a future reflection take that kind of lesson: general, about how to reflect, never about
3170
+ this session's topic, and not a repeat of a rule already there.
3171
+ In "considered", say why that run missed it, in one sentence.
3172
+ `;
3173
+ }
3149
3174
  function feedbackSection(f) {
3150
3175
  return `
3151
3176
  ## Feedback from the person (human steering)
@@ -3162,6 +3187,7 @@ The lesson it is about:
3162
3187
  ${f.lesson.trim()}
3163
3188
  </lesson>
3164
3189
  ` : ""}
3190
+ ${f.run ? runSection(f.run) : ""}
3165
3191
  Treat it as a correction from a person (signal "steering"): the strongest evidence there is. Act on it:
3166
3192
  - If it says the session taught something that was missed, capture that lesson in the right
3167
3193
  document, written as the guidelines below ask. ${f.transcript ? "Find it in the session below." : "The session's trace is no longer available: work from the feedback itself (the person's own account), the lessons already taken and the documents."}
@@ -6841,20 +6867,27 @@ function sessionModel(transcriptPath) {
6841
6867
  }
6842
6868
  return void 0;
6843
6869
  }
6844
- function lastLineWith(file2, needle, tail = 4 * 1024 * 1024) {
6870
+ function lastLineWith(file2, needle, chunk = 1024 * 1024) {
6871
+ let fd;
6845
6872
  try {
6846
- const fd = fs16.openSync(file2, "r");
6847
- try {
6848
- const size = fs16.fstatSync(fd).size;
6849
- const len = Math.min(size, tail);
6873
+ fd = fs16.openSync(file2, "r");
6874
+ let pos = fs16.fstatSync(fd).size;
6875
+ let carry = "";
6876
+ while (pos > 0) {
6877
+ const len = Math.min(chunk, pos);
6878
+ pos -= len;
6850
6879
  const buf = Buffer.alloc(len);
6851
- fs16.readSync(fd, buf, 0, len, size - len);
6852
- return buf.toString("utf8").split("\n").reverse().find((l) => l.includes(needle));
6853
- } finally {
6854
- fs16.closeSync(fd);
6880
+ fs16.readSync(fd, buf, 0, len, pos);
6881
+ const text2 = buf.toString("utf8") + carry;
6882
+ const lines = text2.split("\n");
6883
+ carry = pos > 0 ? lines.shift() ?? "" : "";
6884
+ for (let i = lines.length - 1; i >= 0; i--) if (lines[i].includes(needle)) return lines[i];
6855
6885
  }
6886
+ return void 0;
6856
6887
  } catch {
6857
6888
  return void 0;
6889
+ } finally {
6890
+ if (fd !== void 0) fs16.closeSync(fd);
6858
6891
  }
6859
6892
  }
6860
6893
  function sessionCostSoFar(transcriptPath) {
@@ -6868,6 +6901,14 @@ function sessionCostSoFar(transcriptPath) {
6868
6901
  return void 0;
6869
6902
  }
6870
6903
  }
6904
+ function transcriptIdleMs(transcriptPath, now = Date.now()) {
6905
+ if (!transcriptPath) return void 0;
6906
+ try {
6907
+ return Math.max(0, now - fs16.statSync(transcriptPath).mtimeMs);
6908
+ } catch {
6909
+ return void 0;
6910
+ }
6911
+ }
6871
6912
  function forkOwnCost(reported, before) {
6872
6913
  if (reported === void 0) return void 0;
6873
6914
  return before === void 0 ? reported : Math.max(0, reported - before);
@@ -6895,7 +6936,7 @@ function forkDecision(records, o) {
6895
6936
  if (o.learn) return { fork: true, reason: "asked for (/learn)" };
6896
6937
  if (o.tokens <= o.limit) return { fork: true, reason: "short session" };
6897
6938
  const now = o.now ?? Date.now();
6898
- const latest = [...records].reverse().find((r) => r.mode === "faithful" && r.tokens > o.limit && now - Date.parse(r.at) < MISS_HOLD_MS);
6939
+ const latest = [...records].reverse().find((r) => r.mode === "faithful" && !r.cold && r.tokens > o.limit && now - Date.parse(r.at) < MISS_HOLD_MS);
6899
6940
  if (latest && latest.hitRate < CACHE_MISS) return { fork: false, reason: `the last fork here missed the session's cache (${Math.round(latest.hitRate * 100)}% read from cache): digest of the new turns` };
6900
6941
  return { fork: true, reason: latest ? `forks here read ${Math.round(latest.hitRate * 100)}% from the session's cache` : "first fork of a large session here" };
6901
6942
  }
@@ -6912,7 +6953,7 @@ function reflectionSummary(v2, days = 7, now = Date.now()) {
6912
6953
  read += t.usage.cacheRead ?? 0;
6913
6954
  paid += (t.usage.cacheWrite ?? 0) + (t.usage.input ?? 0);
6914
6955
  const rate = t.cache?.hitRate;
6915
- if (rate !== void 0 && rate < CACHE_MISS) misses++;
6956
+ if (rate !== void 0 && rate < CACHE_MISS && !t.cache?.cold) misses++;
6916
6957
  }
6917
6958
  const latest = [...readForkCache(v2)].reverse()[0];
6918
6959
  return { runs: traces.length, costUsd: traces.reduce((a, t) => a + (t.costUsd ?? 0), 0), forks, hitRate: read + paid > 0 ? read / (read + paid) : null, misses, mode: latest?.mode ?? null };
@@ -7050,6 +7091,18 @@ async function runReflectionV2(store, opts) {
7050
7091
  ...reflectionIndex(view, [...session.loaded, ...session.pushed, ...session.served], session.task, opts.focus, humanTurnsOf(session.transcriptPath)).filter((s) => s.id !== profile?.id)
7051
7092
  ];
7052
7093
  const harness = session.harness ?? config.harness;
7094
+ if (session.serverReflectedTurns === void 0 && canCall(config)) {
7095
+ try {
7096
+ const cur = await v2api(config, "GET", `/episodes/${encodeURIComponent(episodeId)}/cursor`, void 0, { timeoutMs: 5e3 });
7097
+ v2.updateSession(opts.sessionId, session.cwd, (s) => {
7098
+ s.serverReflectedTurns = Math.max(s.serverReflectedTurns ?? 0, typeof cur.reflectedTurns === "number" ? cur.reflectedTurns : 0);
7099
+ if (Array.isArray(cur.lessons)) s.serverLessons = cur.lessons.filter((l) => typeof l === "string").slice(0, 40);
7100
+ });
7101
+ } catch (err) {
7102
+ if (err instanceof ApiError && err.status === 404) v2.updateSession(opts.sessionId, session.cwd, (s) => void (s.serverReflectedTurns ??= 0));
7103
+ }
7104
+ Object.assign(session, v2.readSession(opts.sessionId) ?? {});
7105
+ }
7053
7106
  const facts = readFacts(session.transcriptPath);
7054
7107
  const turns = facts?.turns.length ?? 0;
7055
7108
  const from = reflectCursor(session, turns);
@@ -7071,14 +7124,21 @@ async function runReflectionV2(store, opts) {
7071
7124
  if (mode === "isolated") call2.cacheNote = guard ? "reflect.forkMode is isolated in this machine's config" : "hooks are turned off on this machine (disableAllHooks or allowManagedHooksOnly), so the guard that stops a fork acting cannot run";
7072
7125
  const model = mode === "faithful" ? sessionModel(session.transcriptPath) ?? config.model : config.model;
7073
7126
  const before = sessionCostSoFar(session.transcriptPath);
7127
+ const idleMs = transcriptIdleMs(session.transcriptPath);
7128
+ const cold = idleMs !== void 0 && idleMs > Math.max(config.reflect.cacheTtlMs, 5 * 6e4);
7074
7129
  const fork = await runClaudeFork(opts.sessionId, prompt, { cwd: session.cwd, model, mode });
7075
7130
  fork.costUsd = forkOwnCost(fork.costUsd, before);
7076
7131
  const hitRate = cacheHitRate(fork.usage);
7077
7132
  call2.cacheMode = mode;
7078
7133
  if (hitRate !== void 0) {
7079
7134
  call2.hitRate = hitRate;
7080
- recordForkCache(v2, { at: (/* @__PURE__ */ new Date()).toISOString(), sessionId: opts.sessionId, mode, tokens: sessionTokens, hitRate, ...fork.costUsd !== void 0 ? { costUsd: fork.costUsd } : {} });
7081
- if (mode === "faithful" && hitRate < CACHE_MISS && sessionTokens > limit) {
7135
+ const coldMiss = cold && hitRate < CACHE_MISS;
7136
+ if (coldMiss) {
7137
+ call2.cacheCold = true;
7138
+ call2.cacheNote = `the session's prompt cache had expired (idle ${Math.round(idleMs / 6e4)} min before this fork): not counted as a miss`;
7139
+ }
7140
+ recordForkCache(v2, { at: (/* @__PURE__ */ new Date()).toISOString(), sessionId: opts.sessionId, mode, tokens: sessionTokens, hitRate, ...fork.costUsd !== void 0 ? { costUsd: fork.costUsd } : {}, ...coldMiss ? { cold: true } : {} });
7141
+ if (mode === "faithful" && hitRate < CACHE_MISS && sessionTokens > limit && !coldMiss) {
7082
7142
  const cost = fork.costUsd !== void 0 ? ` ($${fork.costUsd.toFixed(2)})` : "";
7083
7143
  v2.log("v2-reflect-cache-miss", { session: opts.sessionId, hitRate, tokens: sessionTokens, costUsd: fork.costUsd ?? null });
7084
7144
  updateFeed(v2, opts.sessionId, (f) => addEvent(f, "warning", `reflection did not reuse this session's prompt cache${cost}: large sessions here reflect from a digest of their new turns for now`));
@@ -7208,7 +7268,7 @@ async function runReflectionV2(store, opts) {
7208
7268
  nothingNew: result.nothingNew,
7209
7269
  ...call2.usage ? { usage: call2.usage } : {},
7210
7270
  ...call2.costUsd !== void 0 ? { costUsd: call2.costUsd } : {},
7211
- ...call2.cacheNote || call2.hitRate !== void 0 ? { cache: { ...call2.cacheMode ? { mode: call2.cacheMode } : {}, ...call2.hitRate !== void 0 ? { hitRate: Math.round(call2.hitRate * 1e3) / 1e3 } : {}, ...call2.cacheNote ? { note: call2.cacheNote } : {} } } : {},
7271
+ ...call2.cacheNote || call2.hitRate !== void 0 ? { cache: { ...call2.cacheMode ? { mode: call2.cacheMode } : {}, ...call2.hitRate !== void 0 ? { hitRate: Math.round(call2.hitRate * 1e3) / 1e3 } : {}, ...call2.cacheNote ? { note: call2.cacheNote } : {}, ...call2.cacheCold ? { cold: true } : {} } } : {},
7212
7272
  durationMs: Date.now() - Date.parse(startedAt),
7213
7273
  ...result.error ? { error: result.error } : {},
7214
7274
  startedAt,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bunshin-cc/bunshin",
3
- "version": "0.12.1",
3
+ "version": "0.12.2",
4
4
  "description": "Shared memory for company AI agents. Connect Codex, Claude Code, or Pi to Bunshin.",
5
5
  "type": "module",
6
6
  "bin": {