opencode-self-improvement 0.14.15 → 0.14.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -99,20 +99,22 @@ Injection, recall, the frontier block, compaction, `memory_forget` and decay onl
99
99
 
100
100
  ## Token cost and caching
101
101
 
102
- - **Epoch-frozen injection.** The relevance block is computed once per epoch — first prompt of a session, a change to the store, or a compaction — and stays byte-identical in between, so the provider's prompt cache survives ordinary turns.
102
+ - **Section-frozen injection.** The whole memory section — standing digest, open-thread frontier, relevance block — is computed once per epoch and delivered byte-identically until something the model is actually shown changes. The epoch's authority is the **rendered bytes**, not the store fingerprint: a promoted row that changes nothing visible costs no cache bust, while a write that does change what you see costs exactly one.
103
103
  - **Two-concept threshold.** A free-text prompt must share at least two distinct concepts with a memory for it to be injected; keyword-length queries (one or two words) need only one. Silence on single-word coincidences is deliberate; `memory_recall` still reaches them on the pull path.
104
104
  - **Hard budgets.** Relevance block and each pull are capped at `injectBudget` characters, the frontier at `frontierBudget`, trimmed at whole-memory boundaries.
105
+ - **Nothing volatile on the cached prefix.** The standing digest carries no row count and no latest timestamp. Both used to ride the very front of the system prompt, so every saved memory rewrote the prefix and made the next request re-bill the whole conversation; the exact numbers now live where they are free — the footer badge, `/memory`, `memory_status`, the viewer.
105
106
  - **Evidence is never injected**, and the standing system digest is two lines.
106
107
  - **Measured, not claimed.** The plugin reads each turn's `tokens.cache` accounting and displays the actual hit rate next to the badge.
107
108
 
108
- Deterministic workload (50 memories, 20 prompts, 3 mid-session store writes) through the plugin's real injection code:
109
+ Deterministic workload (50 memories, 20 prompts, 3 mid-session store writes) through the plugin's real injection code. Every column is measured on the full memory section — the bytes a request actually sends — because prompt caching is a property of those bytes:
109
110
 
110
- | Policy | Recomputes | Injected chars (20 turns) | Avg/turn | Worst block |
111
- | --- | ---: | ---: | ---: | ---: |
112
- | A — recompute per prompt, uncapped | 20 | 25742 | 1287.1 | 1838 |
113
- | B — epoch freeze + 1200-char cap (shipped) | 4 | 19990 | 999.5 | 1139 |
111
+ | Policy | Recomputes | Cache busts | Injected chars (20 turns) | Avg/turn | Worst section |
112
+ | --- | ---: | ---: | ---: | ---: | ---: |
113
+ | A — recompute per prompt, uncapped (naive) | 20 | 19 | 60996 | 3049.8 | 3404 |
114
+ | B — block frozen on store fingerprint, digest rebuilt per turn | 4 | 3 | 55478 | 2773.9 | 2867 |
115
+ | C — section frozen on rendered bytes (shipped) | 4 | 3 | 55258 | 2762.9 | 2856 |
114
116
 
115
- Policy B injects 22.3% fewer characters, and its block is byte-identical between store changes so the prompt cache stays warm. Reproduce (byte-identical output):
117
+ A "cache bust" is a turn whose memory-section bytes differ from the turn before — each one re-bills the entire conversation as fresh input. On this workload all three writes happen to be visible, so B and C agree; a write the session *cannot* see costs C nothing and cost B a full re-prefill (pinned by `test/epoch.test.ts`, which fails against B). C also injects 9.4% fewer characters than the naive policy — the denominator here is the whole section, not the relevance block alone, so it is not comparable with the block-only figure this README quoted before. Reproduce (byte-identical output):
116
118
 
117
119
  ```sh
118
120
  bun run bench
@@ -229,7 +231,7 @@ Same data behind each one (`memory_status`; no model call).
229
231
  **Terminal (opencode CLI)** — the plugin ships a TUI half (`@opencode/plugin/tui`) that loads automatically:
230
232
 
231
233
  - **Footer badge** — `● mem 1157/1200c · cache 96%`: the injected block against its budget, plus the measured session prompt-cache hit rate. The dot is green (stable and warm), yellow (recent recompute, or 50–90% reads) or red (last turn served almost nothing from cache); `—` until the first assistant turn.
232
- - **`/memory`** — session panel: **CONTEXT** (chars and estimated tokens riding now, % of budget, requests this epoch has ridden, session totals, abstentions), **CACHE** (busts this session and the measured cache-served share of prompt tokens), **INJECTED BLOCK** (the verbatim block, or an explicit abstention), **RECENT BLOCKED WRITES** (with gate reasons), **STORE** (active / superseded / open / scopes, plus `malformed` when a row's `ts` is not a valid ISO instant — those rows are skipped by every reader). Keys: `r` refresh, `f` fullscreen.
234
+ - **`/memory`** — session panel: **CONTEXT** (chars and estimated tokens riding now, % of budget, the full memory section riding the prompt — digest + frontier + block — requests this epoch has ridden, session totals, abstentions), **CACHE** (busts this session and the measured cache-served share of prompt tokens), **INJECTED BLOCK** (the verbatim block, or an explicit abstention), **RECENT BLOCKED WRITES** (with gate reasons), **STORE** (active / superseded / open / scopes, plus `malformed` when a row's `ts` is not a valid ISO instant — those rows are skipped by every reader). Keys: `r` refresh, `f` fullscreen.
233
235
  - **Block toast** when a write is refused (`"notifyBlocked": false` to silence).
234
236
 
235
237
  **Desktop / web / IDE** — the terminal slots do not exist there, so use the self-installed **`/memory-report`** chat command: the same sections rendered in the conversation.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.14.15",
3
+ "version": "0.14.16",
4
4
  "description": "Durable memory for opencode: remember facts, decisions, and commands across sessions, plus a one-command per-repo setup (/repo-init).",
5
5
  "main": "index.ts",
6
6
  "exports": {
package/src/index.ts CHANGED
@@ -1066,15 +1066,28 @@ const impl = {
1066
1066
  }));
1067
1067
  });
1068
1068
 
1069
- // Per-session frozen injection epochs: the relevance block plus the store
1070
- // fingerprint it was computed against. Recomputed on the first prompt of a
1071
- // tracked session, when injectable rows change, or after a compaction (see
1072
- // the prompt/context/compaction hooks) — so the system prefix, and with it
1073
- // the provider prompt cache, survives ordinary requests. The shared LRU
1074
- // below may evict the whole session state; a later prompt starts it fresh.
1069
+ // Per-session frozen injection epochs: the whole memory section (digest +
1070
+ // frontier + relevance) plus the store fingerprint it was rendered from.
1071
+ // Recomputed on the first prompt of a tracked session, when injectable rows
1072
+ // change, or after a compaction (see the prompt/context/compaction hooks).
1073
+ // The RENDERED BYTES, not the fingerprint, decide whether the epoch moved
1074
+ // (issue #162): a write that changes nothing the model is shown must not
1075
+ // cost the next request a full re-prefill. The shared LRU below may evict
1076
+ // the whole session state; a later prompt starts it fresh.
1075
1077
  const epoch = new Map<
1076
1078
  string,
1077
- { version: string; block: string; at: string; reason: "first" | "store_changed"; refs: MemoryRefs }
1079
+ {
1080
+ version: string;
1081
+ /** Frozen standing digest + frontier + convergence parts, in push order. */
1082
+ parts: string[];
1083
+ /** The budgeted relevance block the surfaces report against injectBudget. */
1084
+ block: string;
1085
+ /** Comparison key: every byte of the memory section, joined. */
1086
+ prefix: string;
1087
+ at: string;
1088
+ reason: "first" | "store_changed";
1089
+ refs: MemoryRefs;
1090
+ }
1078
1091
  >();
1079
1092
  // Latest user prompt per tracked session. A changed store is re-scored
1080
1093
  // against it even when the change happened during a tool loop with no new
@@ -1121,6 +1134,7 @@ const impl = {
1121
1134
  recomputes: epochRecomputes,
1122
1135
  block: ep.block,
1123
1136
  blockChars: ep.block.length,
1137
+ sectionChars: ep.prefix.length,
1124
1138
  budget,
1125
1139
  store: {
1126
1140
  active: act.length,
@@ -1161,32 +1175,74 @@ const impl = {
1161
1175
  for (const m of rows) for (const t of sharedTerms(query, m)) if (!terms.includes(t)) terms.push(t);
1162
1176
  await recordHits(src, sid, rows, terms);
1163
1177
  };
1178
+ // Render the COMPLETE memory section for one request: the standing digest,
1179
+ // the open-thread frontier and the convergence line (all from systemDigest),
1180
+ // followed by this epoch's relevance block. The parts are exactly what gets
1181
+ // pushed onto `event.system`; their join is the byte key the epoch compares
1182
+ // against, so "did the cache-critical prefix change?" is answered by the
1183
+ // bytes the model would actually see and never by a proxy (issue #162).
1184
+ const buildMemorySection = async (
1185
+ sid: string | undefined,
1186
+ mems: Memory[],
1187
+ ): Promise<{ parts: string[]; block: string; prefix: string; rode: Memory[]; refs: MemoryRefs }> => {
1188
+ const parts: string[] = [];
1189
+ await systemDigest(
1190
+ { sessionID: sid },
1191
+ { system: parts },
1192
+ { rows: mems, frontierBudget: openBudget },
1193
+ );
1194
+ const prompt = sid === undefined ? "" : latestPrompt.get(sid) ?? "";
1195
+ // Widen the candidate pool, then cap: the budget decides what rides.
1196
+ const sel = await selectRelevant(prompt, 5, mems, await useSignals());
1197
+ const block = sel.block ? capToBudget(sel.block, budget) : "";
1198
+ // Refs the ACTUALLY-injected rows assert (paths + commands), the join key
1199
+ // for attribution. Derived from the budget-surviving rows, not the wider
1200
+ // candidate pool — crediting paths the model never saw would overclaim.
1201
+ const rode = injectedRows(block, sel.selected);
1202
+ const prefix = [...parts, block].join("\u0000");
1203
+ return { parts, block, prefix, rode, refs: deriveMemoryRefs(rode) };
1204
+ };
1164
1205
  const refreshEpoch = async (sid: string, rows?: Memory[]): Promise<void> => {
1165
1206
  if (!latestPrompt.has(sid)) return;
1166
1207
  const mems = rows ?? (await injectableRows(sid));
1167
1208
  const version = await storeVersion(mems);
1168
1209
  const cached = epoch.get(sid);
1210
+ // Cheap pre-check: no injectable row moved, so the frozen bytes still
1211
+ // stand. Skips re-scoring and the use-ledger write on ordinary turns.
1169
1212
  if (cached?.version === version) return;
1213
+ const built = await buildMemorySection(sid, mems);
1214
+ // The store moved. A write that changes nothing RENDERED — a row that is
1215
+ // not relevant to this prompt, supersession elsewhere, a scope the reader
1216
+ // never sees rendered identically — must not cost this session a prompt
1217
+ // cache. Adopt the new fingerprint, keep riding the same bytes, emit
1218
+ // nothing: an invalidation has to mean bytes actually moved.
1219
+ if (cached && cached.prefix === built.prefix) {
1220
+ epoch.set(sid, { ...cached, version });
1221
+ return;
1222
+ }
1170
1223
  const prompt = latestPrompt.get(sid) ?? "";
1171
- const sel = await selectRelevant(prompt, 5, mems, await useSignals()); // widen candidate pool
1172
- const block = sel.block ? capToBudget(sel.block, budget) : "";
1173
- // Refs the ACTUALLY-injected rows assert (paths + commands), the join key
1174
- // for attribution. Derived from the budget-surviving rows, not the wider
1175
- // candidate pool — crediting paths the model never saw would overclaim.
1176
- const rode = injectedRows(block, sel.selected);
1177
- const refs = deriveMemoryRefs(rode);
1178
1224
  // Use ledger (#42): the rows that actually rode the block, credited with
1179
1225
  // the terms the prompt and those rows shared (never the prompt itself).
1180
- await noteHits("inject", sid, rode, prompt);
1226
+ // Only once the build is ADOPTED — a discarded rebuild must not credit
1227
+ // rows that were already offered under the frozen epoch.
1228
+ await noteHits("inject", sid, built.rode, prompt);
1181
1229
  const at = new Date().toISOString();
1182
1230
  const reason: "first" | "store_changed" = cached ? "store_changed" : "first";
1183
- epoch.set(sid, { version, block, at, reason, refs });
1231
+ epoch.set(sid, {
1232
+ version,
1233
+ parts: built.parts,
1234
+ block: built.block,
1235
+ prefix: built.prefix,
1236
+ at,
1237
+ reason,
1238
+ refs: built.refs,
1239
+ });
1184
1240
  await record(
1185
1241
  "epoch_recompute",
1186
1242
  {
1187
1243
  session: sid,
1188
1244
  reason,
1189
- chars: block.length,
1245
+ chars: built.block.length,
1190
1246
  },
1191
1247
  false,
1192
1248
  );
@@ -1270,16 +1326,26 @@ const impl = {
1270
1326
  if (typeof sid === "string") bindSessionProvisional(sid, instanceDir);
1271
1327
  const mems = await injectableRows(sid);
1272
1328
  if (typeof sid === "string") await refreshEpoch(sid, mems);
1273
- const parts: string[] = [];
1274
- await systemDigest(
1275
- { sessionID: event?.sessionID },
1276
- { system: parts },
1277
- { rows: mems, frontierBudget: openBudget },
1278
- );
1279
- for (const text of parts) event?.system?.push?.({ type: "text", text });
1280
- // Deliver this epoch's relevance-ranked memory via the system channel.
1281
- // The UI never renders system parts, unlike appended prompt text.
1282
- const knowledge = typeof sid === "string" ? epoch.get(sid)?.block : undefined;
1329
+ // Deliver the FROZEN memory section. Every byte pushed onto the system
1330
+ // prompt comes from the epoch, so between busts the provider sees an
1331
+ // identical prefix and serves the conversation from cache (issue #162).
1332
+ // A session with no epoch yet (no prompt recorded, or evicted from the
1333
+ // LRU) still gets the standing digest, built fresh and uncached.
1334
+ const ep = typeof sid === "string" ? epoch.get(sid) : undefined;
1335
+ if (ep) {
1336
+ for (const text of ep.parts) event?.system?.push?.({ type: "text", text });
1337
+ } else {
1338
+ const parts: string[] = [];
1339
+ await systemDigest(
1340
+ { sessionID: event?.sessionID },
1341
+ { system: parts },
1342
+ { rows: mems, frontierBudget: openBudget },
1343
+ );
1344
+ for (const text of parts) event?.system?.push?.({ type: "text", text });
1345
+ }
1346
+ // This epoch's relevance-ranked memory, also on the system channel —
1347
+ // the UI never renders system parts, unlike appended prompt text.
1348
+ const knowledge = ep?.block;
1283
1349
  if (knowledge) event?.system?.push?.({ type: "text", text: knowledge });
1284
1350
  // Count AT THE INJECTION DECISION so badge/panel numbers match exactly
1285
1351
  // what rode this request (a later abort still rode the bytes — known
package/src/inject.ts CHANGED
@@ -291,11 +291,17 @@ export async function systemDigest(
291
291
  // after the loadAll await.
292
292
  const mems = opts.rows ?? visibleTo((await loadAll()).filter(isActive), readerFromSid(sid));
293
293
  if (!mems.length) return;
294
- const latest = flattenMemoryText(mems.map((m) => m.ts).sort().pop() ?? "?");
294
+ // CACHE-STABLE BY CONSTRUCTION (issue #162): this line carries no row count
295
+ // and no latest-ts. Both change on every promoted write, and the digest rides
296
+ // the FRONT of the system prompt, so one volatile byte invalidated the whole
297
+ // cached prefix — every memory write cost the next request a full re-prefill.
298
+ // The exact numbers belong on surfaces where they are free and never ride a
299
+ // prompt: the footer badge, /memory, memory_status, the viewer.
295
300
  output.system.push(
296
301
  "\n## Persistent memory (opencode-self-improvement)\n" +
297
- `${mems.length} durable memories; latest: ${latest}. ` +
298
- "Check memory_recall BEFORE grepping or reading, for build/test/lint commands, decisions, and conventions. Relevant memories are also auto-injected when your message matches.",
302
+ "Durable memories exist for this repository. Check memory_recall BEFORE grepping or " +
303
+ "reading, for build/test/lint commands, decisions, and conventions. Relevant memories " +
304
+ "are also auto-injected when your message matches.",
299
305
  );
300
306
 
301
307
  const open = mems
package/src/status.ts CHANGED
@@ -160,6 +160,12 @@ export interface StatusPayload {
160
160
  /** exact injected block ("" = abstained: no vocabulary overlap). */
161
161
  block: string;
162
162
  blockChars: number;
163
+ /**
164
+ * Every memory byte riding the system prompt: digest + frontier + block.
165
+ * Optional for backward-compatible reads of status files written before the
166
+ * distinction existed — the panel only prints it when present.
167
+ */
168
+ sectionChars?: number;
163
169
  budget: number;
164
170
  store: StoreCounts;
165
171
  /** optional for backward-compatible reads of pre-v2 files. */
@@ -350,6 +356,15 @@ export function contextLines(p: StatusPayload): string[] {
350
356
  const pct = p.budget > 0 ? Math.round((p.blockChars / p.budget) * 100) : 0;
351
357
  return [
352
358
  ` injected now ${p.blockChars}c ≈ ${estTok(p.blockChars)} tok · ${pct}% of ${p.budget}c budget`,
359
+ // The budget caps the RELEVANCE BLOCK; the standing digest and the frontier
360
+ // ride the system prompt too. Quoting only the budgeted slice would
361
+ // understate what the request actually carries.
362
+ ...(p.sectionChars === undefined
363
+ ? []
364
+ : [
365
+ ` memory section ${p.sectionChars}c ≈ ${estTok(p.sectionChars)} tok riding the prompt` +
366
+ ` (digest + frontier + the ${p.blockChars}c block above)`,
367
+ ]),
353
368
  ` this epoch ${p.reason} epoch since ${p.at} (${ago(p.at)}) · rode ${st.epochRequests} request(s)`,
354
369
  ` session ${st.requests} request(s) · ${fmtCount(st.cumChars)}c ≈ ${fmtCount(estTok(st.cumChars))} tok rode · abstained ${st.abstained}`,
355
370
  ];
@@ -367,8 +382,9 @@ export function cacheLines(p: StatusPayload): string[] {
367
382
  ` cache busts ${st.invalidations} this session · last ${
368
383
  st.lastInvalidation ? `${st.lastInvalidation.at.slice(11, 19)} (${st.lastInvalidation.reason})` : "-"
369
384
  }`,
370
- " each memory write between turns costs exactly one; the",
371
- " prefix re-warms on the following turn",
385
+ " each write that changes what you are shown costs exactly",
386
+ " one; a write that changes nothing rendered costs nothing,",
387
+ " and the prefix re-warms on the following turn",
372
388
  ];
373
389
  const rate = cacheRate(p.measured);
374
390
  const receipts = rate