opencode-self-improvement 0.14.16 → 0.14.17

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,22 +99,24 @@ Injection, recall, the frontier block, compaction, `memory_forget` and decay onl
99
99
 
100
100
  ## Token cost and caching
101
101
 
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.
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 actually needs changes. The epoch's authority is the **rendered bytes**, not the store fingerprint: a promoted row that changes nothing visible costs no cache bust.
103
+ - **A session never pays for bytes it is not riding.** A memory *you* saved in this session is a fact you already produced — it is in your own transcript — so it never busts your cache. The test is not "did the store change" but "would the frozen bytes still have been produced from the same inputs, minus the rows this session authored since": a correction, blocklisting, redaction or supersession of a row you are riding, and anything another session, the viewer or an import wrote, all still land on your next request.
103
104
  - **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
105
  - **Hard budgets.** Relevance block and each pull are capped at `injectBudget` characters, the frontier at `frontierBudget`, trimmed at whole-memory boundaries.
105
106
  - **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.
106
107
  - **Evidence is never injected**, and the standing system digest is two lines.
107
108
  - **Measured, not claimed.** The plugin reads each turn's `tokens.cache` accounting and displays the actual hit rate next to the badge.
108
109
 
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:
110
+ Deterministic workload (50 memories, 20 prompts, 3 mid-session store writes made *by the measured session*) 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:
110
111
 
111
112
  | Policy | Recomputes | Cache busts | Injected chars (20 turns) | Avg/turn | Worst section |
112
113
  | --- | ---: | ---: | ---: | ---: | ---: |
113
114
  | A — recompute per prompt, uncapped (naive) | 20 | 19 | 60996 | 3049.8 | 3404 |
114
115
  | 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 |
116
+ | C — section frozen on rendered bytes | 4 | 3 | 55258 | 2762.9 | 2856 |
117
+ | D — C + riding bytes (shipped) | 1 | 0 | 53500 | 2675.0 | 2675 |
116
118
 
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):
119
+ 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. All three synthetic writes change what the session is shown, so B and C each pay for them; D pays nothing, because the session wrote them itself. What D still pays for is a riding row being corrected, blocklisted or redacted, or another session writing a row — that half of the contract is pinned by `test/epoch.test.ts` rather than by this table, since a benchmark that only writes never exercises it. D also injects 12.3% 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):
118
120
 
119
121
  ```sh
120
122
  bun run bench
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.14.16",
3
+ "version": "0.14.17",
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/gates.ts CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  type SupersedeFields,
16
16
  } from "./memory.ts";
17
17
  import { chainId, contentHash, record, recordWriteBlocked } from "./evidence.ts";
18
+ import { noteAuthored } from "./state.ts";
18
19
  import { flattenMemoryText } from "./sanitize.ts";
19
20
  import { containsSecret, redactSecrets } from "./secrets.ts";
20
21
  import { readerForSession } from "./memory.ts";
@@ -662,6 +663,10 @@ export async function runWriteGate(
662
663
  // The write carries the CALLER's session, not whatever current says after
663
664
  // the gate's own awaits - capture's stamp must follow the captured session.
664
665
  const ts = await appendMemory({ ...candidate, sessionID: ctx.sessionID });
666
+ // #165: remember who made this row, so the writing session is not billed a
667
+ // prompt-cache bust to be shown its own thought. Only promoted writes are
668
+ // attributed — a blocked candidate created nothing.
669
+ noteAuthored(ctx.sessionID, ts);
665
670
  await rec("write_promoted", {
666
671
  gate: 4,
667
672
  op: "write",
package/src/index.ts CHANGED
@@ -81,7 +81,7 @@ import {
81
81
  markTurn,
82
82
  onCompacting,
83
83
  } from "./triggers.ts";
84
- import { getCurrent, setCurrent } from "./state.ts";
84
+ import { authoredFor, getCurrent, setCurrent } from "./state.ts";
85
85
  import { resolveRepo, setRepoScope, rememberSessionDir, sessionDir, sessionDirFirm, bindSessionProvisional, writeTarget } from "./repokey.ts";
86
86
  import { parseLine, readLines } from "./logfmt.ts";
87
87
  import { buildCapturePrompt, flattenTranscript, lagSince, parseCandidates, parseModelRef } from "./capture.ts";
@@ -1072,8 +1072,10 @@ const impl = {
1072
1072
  // change, or after a compaction (see the prompt/context/compaction hooks).
1073
1073
  // The RENDERED BYTES, not the fingerprint, decide whether the epoch moved
1074
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
+ // cost the next request a full re-prefill. And a pure addition the session
1076
+ // wrote itself does not move them either (#165) — see refreshEpoch. The
1077
+ // shared LRU below may evict the whole session state; a later prompt starts
1078
+ // it fresh.
1077
1079
  const epoch = new Map<
1078
1080
  string,
1079
1081
  {
@@ -1084,6 +1086,20 @@ const impl = {
1084
1086
  block: string;
1085
1087
  /** Comparison key: every byte of the memory section, joined. */
1086
1088
  prefix: string;
1089
+ /**
1090
+ * Rows THIS session had already authored when these bytes were rendered
1091
+ * (#165). The riding-bytes test subtracts everything authored after this
1092
+ * snapshot; if what remains renders identically, the whole difference is
1093
+ * the session's own additions and the bytes keep riding.
1094
+ */
1095
+ ownRows: Set<string>;
1096
+ /**
1097
+ * The prompt these bytes were scored against. The counterfactual below
1098
+ * has to re-score the SAME inputs, or a topic change between the freeze
1099
+ * and the next write would look like a content change — and the epoch
1100
+ * would pay for a refresh it deliberately refuses to do on a prompt.
1101
+ */
1102
+ prompt: string;
1087
1103
  at: string;
1088
1104
  reason: "first" | "store_changed";
1089
1105
  refs: MemoryRefs;
@@ -1184,6 +1200,7 @@ const impl = {
1184
1200
  const buildMemorySection = async (
1185
1201
  sid: string | undefined,
1186
1202
  mems: Memory[],
1203
+ promptOverride?: string,
1187
1204
  ): Promise<{ parts: string[]; block: string; prefix: string; rode: Memory[]; refs: MemoryRefs }> => {
1188
1205
  const parts: string[] = [];
1189
1206
  await systemDigest(
@@ -1191,7 +1208,7 @@ const impl = {
1191
1208
  { system: parts },
1192
1209
  { rows: mems, frontierBudget: openBudget },
1193
1210
  );
1194
- const prompt = sid === undefined ? "" : latestPrompt.get(sid) ?? "";
1211
+ const prompt = promptOverride ?? (sid === undefined ? "" : latestPrompt.get(sid) ?? "");
1195
1212
  // Widen the candidate pool, then cap: the budget decides what rides.
1196
1213
  const sel = await selectRelevant(prompt, 5, mems, await useSignals());
1197
1214
  const block = sel.block ? capToBudget(sel.block, budget) : "";
@@ -1220,6 +1237,30 @@ const impl = {
1220
1237
  epoch.set(sid, { ...cached, version });
1221
1238
  return;
1222
1239
  }
1240
+ // Riding bytes (#165): a pure addition this session wrote itself is
1241
+ // information it already has — the model produced it, it is in the
1242
+ // transcript. Re-render the section with every row authored SINCE these
1243
+ // bytes were frozen taken back out: if it comes back byte-identical, the
1244
+ // entire difference is attributable to the session's own additions and
1245
+ // the frozen bytes keep riding. Everything else survives into that render
1246
+ // and still busts — a riding row removed or rewritten (blocklist,
1247
+ // hand-redaction, forget, supersession, decay), another session's row, a
1248
+ // viewer edit, an import, a moved convergence line.
1249
+ if (cached) {
1250
+ const mine = authoredFor(sid);
1251
+ const extra = mems.filter((m) => mine.has(m.ts) && !cached.ownRows.has(m.ts));
1252
+ if (extra.length) {
1253
+ const back = await buildMemorySection(
1254
+ sid,
1255
+ mems.filter((m) => !extra.some((e) => e.ts === m.ts)),
1256
+ cached.prompt,
1257
+ );
1258
+ if (back.prefix === cached.prefix) {
1259
+ epoch.set(sid, { ...cached, version });
1260
+ return;
1261
+ }
1262
+ }
1263
+ }
1223
1264
  const prompt = latestPrompt.get(sid) ?? "";
1224
1265
  // Use ledger (#42): the rows that actually rode the block, credited with
1225
1266
  // the terms the prompt and those rows shared (never the prompt itself).
@@ -1233,6 +1274,8 @@ const impl = {
1233
1274
  parts: built.parts,
1234
1275
  block: built.block,
1235
1276
  prefix: built.prefix,
1277
+ ownRows: new Set(mems.filter((m) => authoredFor(sid).has(m.ts)).map((m) => m.ts)),
1278
+ prompt,
1236
1279
  at,
1237
1280
  reason,
1238
1281
  refs: built.refs,
package/src/state.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  // Per-session in-memory state shared by the hooks and the gate pipeline.
2
2
  // Deterministic: only tool results and tool invocations mutate it, never the
3
3
  // model. Reset between scenario runs with resetState().
4
+ import { SESSION_CAP, SessionLru } from "./sessions.ts";
4
5
 
5
6
  export interface ToolResult {
6
7
  call: string;
@@ -43,6 +44,39 @@ export interface SessionState {
43
44
  finalized: boolean;
44
45
  }
45
46
 
47
+ // Rows this session promoted, for the riding-bytes rule (#165): a session must
48
+ // not pay a prompt-cache bust to be shown a fact it wrote itself, because that
49
+ // fact is already in its transcript. Filled where a write is promoted (the one
50
+ // place a row is created ON behalf of a named session — the viewer's own writes
51
+ // are deliberately not attributed), read by the epoch refresh.
52
+ //
53
+ // In-process on purpose. Persisting an author field would need a store
54
+ // migration and a privacy review (it records which session wrote what) to cover
55
+ // only the server-restart edge case, and a lost entry degrades to today's
56
+ // behavior — one bust — never to a wrong freeze. Bounded by the same cap as
57
+ // every other session-keyed ledger, so a resident server cannot grow it.
58
+ const authoredRows = new Map<string, Set<string>>();
59
+ const authoredOrder = new SessionLru(SESSION_CAP, (sid) => {
60
+ authoredRows.delete(sid);
61
+ });
62
+ const NO_ROWS: ReadonlySet<string> = new Set();
63
+
64
+ export function noteAuthored(sid: string | undefined, ts: string): void {
65
+ if (!sid || sid === "?") return;
66
+ let rows = authoredRows.get(sid);
67
+ if (!rows) {
68
+ rows = new Set();
69
+ authoredRows.set(sid, rows);
70
+ }
71
+ rows.add(ts);
72
+ authoredOrder.touch(sid);
73
+ }
74
+
75
+ export function authoredFor(sid: string | undefined): ReadonlySet<string> {
76
+ if (!sid) return NO_ROWS;
77
+ return authoredRows.get(sid) ?? NO_ROWS;
78
+ }
79
+
46
80
  // Newest message-bearing session seen this process. Opening a session finalizes
47
81
  // the previous one (there is no session-end hook on the host surface).
48
82
  let lastSeenSidVar: string | null = null;
@@ -88,6 +122,7 @@ export function getCurrent(): { sid: string; call: string; tool: string } {
88
122
 
89
123
  export function resetState(): void {
90
124
  sessions.clear();
125
+ authoredRows.clear();
91
126
  current = { sid: "?", call: "?", tool: "?" };
92
127
  lastSeenSidVar = null;
93
128
  }
package/src/status.ts CHANGED
@@ -382,9 +382,10 @@ export function cacheLines(p: StatusPayload): string[] {
382
382
  ` cache busts ${st.invalidations} this session · last ${
383
383
  st.lastInvalidation ? `${st.lastInvalidation.at.slice(11, 19)} (${st.lastInvalidation.reason})` : "-"
384
384
  }`,
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",
385
+ " a memory YOU saved in this session never costs one — you",
386
+ " already said it (#165). A correction, a removal, or a row",
387
+ " another session wrote costs exactly one, and the prefix",
388
+ " re-warms on the following turn",
388
389
  ];
389
390
  const rate = cacheRate(p.measured);
390
391
  const receipts = rate