opencode-self-improvement 0.16.1 → 0.18.0

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
@@ -140,19 +140,21 @@ Gate-authored evidence and its init/capture lifecycle records capture attributio
140
140
 
141
141
  **Bench** — 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:
142
142
 
143
- | Policy | Recomputes | Cache busts | Injected chars (20 turns) | Avg/turn | Worst section |
143
+ | Policy | Recomputes | Epochs whose bytes moved | Injected chars (20 turns) | Avg/turn | Worst section |
144
144
  | --- | ---: | ---: | ---: | ---: | ---: |
145
145
  | A — recompute per prompt, uncapped (naive) | 20 | 19 | 60996 | 3049.8 | 3404 |
146
146
  | B — block frozen on store fingerprint, digest rebuilt per turn | 4 | 3 | 55478 | 2773.9 | 2867 |
147
147
  | C — section frozen on rendered bytes | 4 | 3 | 55258 | 2762.9 | 2856 |
148
148
  | D — C + riding bytes (shipped) | 1 | 0 | 53500 | 2675.0 | 2675 |
149
149
 
150
- 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):
150
+ The byte-change counter records epochs whose memory-section bytes differ from the previous epoch; it does not measure provider cache misses or re-prefill cost. All three synthetic writes change B and C's bytes; D records no change for these self-writes. Corrections, removals and writes by another session can still move D's bytes, as pinned by `test/epoch.test.ts`. D also injects 12.3% fewer characters than the naive policy, measured over the whole section. Reproduce this deterministic byte workload:
151
151
 
152
152
  ```sh
153
153
  bun run bench
154
154
  ```
155
155
 
156
+ **Author-reported provider audit**, not a new measurement here: [#346's six-turn local-seat audit](https://github.com/abogartz/opencode-self-improvement/issues/346#issuecomment-6714172764) compared `ee769ef` with frozen `29268ef`. The changed build used 2,065 additional input tokens over six turns (~344/turn), with one 3,257-input-token spike, and 94.4% cache share versus 97.5%. The block rode late in the system prompt, after a stable prefix; a byte-moving epoch did not re-bill the whole conversation. This run included two guided rows, so it does not isolate prompt rescoring from the hint channel or establish a bound for every provider. The status counter remains a byte-change count; provider receipts report actual cache reuse separately.
157
+
156
158
  ## Recall quality
157
159
 
158
160
  No vector database, no embedding model, no API key. **Bench** — what the keyword matcher gives up, measured against classic BM25 on a deterministic eval (store of 200, k=3 — the production injection limit):
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.16.1",
3
+ "version": "0.18.0",
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": {
@@ -92,11 +92,13 @@ export function parseCandidates(raw: string, max: number): CaptureCandidate[] {
92
92
  o.status === "open" || o.status === "settled" ? o.status : undefined;
93
93
  // A bad kw list costs the row its keywords, never the row itself.
94
94
  const kw = cleanKeywords(o.kw);
95
+ const guided = o.guided === true;
95
96
  out.push({
96
97
  ...(status
97
98
  ? { type, scope, content, status }
98
99
  : { type, scope, content }),
99
100
  ...(kw ? { kw } : {}),
101
+ ...(guided ? { guided: true } : {}),
100
102
  });
101
103
  }
102
104
  return out;
@@ -15,6 +15,8 @@ export interface CaptureCandidate {
15
15
  status?: "open" | "settled";
16
16
  /** Retrieval keywords (#40): indexed by the store, never rendered. */
17
17
  kw?: string[];
18
+ /** Literal true only when the user stated the fact, not agent inference. */
19
+ guided?: boolean;
18
20
  }
19
21
 
20
22
  // Keywords are the vocabulary bridge for the strict-paraphrase wall, mined from
@@ -43,7 +45,7 @@ export function buildCapturePrompt(
43
45
  "You mine one coding-agent session transcript for durable memories worth keeping across future sessions.",
44
46
  "",
45
47
  `Output ONLY a JSON array of at most ${max} objects (a fenced json block is fine), each:`,
46
- '{"type": "...", "scope": "...", "content": "...", "status": "...", "kw": ["...", "..."]}',
48
+ '{"type": "...", "scope": "...", "content": "...", "status": "...", "kw": ["...", "..."], "guided": true}',
47
49
  "",
48
50
  "Rules:",
49
51
  `- type: one of ${TYPES.join(", ")}.`,
@@ -51,6 +53,7 @@ export function buildCapturePrompt(
51
53
  '- status: "open" for a live planning thread; otherwise "settled".',
52
54
  "- content: one self-contained fact, 20-600 characters, useful in a NEW session.",
53
55
  "- kw: 3-5 search keywords for how a DIFFERENT session would ask for this — synonyms and alternate names, other verb forms, the literal command or file name. They are indexed for retrieval and never shown to a model. Omit (or []) when the content already uses those words.",
56
+ "- guided: true ONLY when the user STATED this fact in their own words — a value, rate, number, rule or correction that appears in a user: line or the REQUESTS block. Omit guided for anything the agent discovered by itself.",
54
57
  "- Keep: decisions made, working commands, user preferences, blockers hit, durable context, conventions.",
55
58
  "- Skip: anything derivable from the code or git history, small talk, and details that only mattered inside this conversation.",
56
59
  ...(prose
@@ -13,6 +13,7 @@ import { lagSince } from "./lag.ts";
13
13
  import { buildCapturePrompt } from "./prompt.ts";
14
14
  import { type SessionModelRef, sessionModel } from "./session-model.ts";
15
15
  import { flattenTranscript, splitTranscript } from "./transcript.ts";
16
+ import { AUTO_CAPTURE_TAG, USER_GUIDED_TAG } from "../core/tags.ts";
16
17
 
17
18
  interface CaptureHost {
18
19
  options?: Record<string, unknown>;
@@ -313,11 +314,16 @@ export function configureAutoCapture(
313
314
  try {
314
315
  outcome = await runWriteGate(
315
316
  quarantineCandidate({
316
- ...c,
317
- tags:
318
- trigger === "compaction"
319
- ? ["auto-capture", CAPTURE_COMPACT_TAG]
320
- : ["auto-capture"],
317
+ type: c.type,
318
+ scope: c.scope,
319
+ content: c.content,
320
+ ...(c.status ? { status: c.status } : {}),
321
+ ...(c.kw ? { kw: c.kw } : {}),
322
+ tags: [
323
+ AUTO_CAPTURE_TAG,
324
+ ...(trigger === "compaction" ? [CAPTURE_COMPACT_TAG] : []),
325
+ ...(c.guided ? [USER_GUIDED_TAG] : []),
326
+ ],
321
327
  }),
322
328
  { ...captureGate, durable },
323
329
  );
@@ -0,0 +1,5 @@
1
+ /** Auto-capture provenance, shared by capture and retrieval. */
2
+ export const AUTO_CAPTURE_TAG = "auto-capture";
3
+
4
+ // The public write boundaries reserve this same tag (#342/#355).
5
+ export { USER_GUIDED_TAG } from "./guidance.ts";
@@ -175,7 +175,18 @@ export function createInjectionEpochs({
175
175
  promptOverride ??
176
176
  (sid === undefined ? "" : (latestPrompt.get(sid) ?? ""));
177
177
  // Widen the candidate pool, then cap: the budget decides what rides.
178
- const sel = await selectRelevant(prompt, 5, mems, await useSignals());
178
+ const sel = await selectRelevant(
179
+ prompt,
180
+ 5,
181
+ mems,
182
+ await useSignals(),
183
+ undefined,
184
+ {
185
+ // The reserved capture provenance rides first, even on unrelated prompts.
186
+ // capToBudget still bounds all rendered rows together.
187
+ guidedCap: 3,
188
+ },
189
+ );
179
190
  const block = sel.block ? capToBudget(sel.block, budget) : "";
180
191
  // Refs the ACTUALLY-injected rows assert (paths + commands), the join key
181
192
  // for attribution. Derived from the budget-surviving rows, not the wider
@@ -5,6 +5,8 @@ import { isInjectable } from "../store/model/predicates.ts";
5
5
  import { readerFromSid, visibleTo } from "../store/model/visibility.ts";
6
6
  import { FRAME } from "../inject/budget.ts";
7
7
  import { formatMemory } from "../inject/format.ts";
8
+ import { USER_GUIDED_TAG } from "../core/guidance.ts";
9
+ import { cmpTs } from "../core/cmp-ts.ts";
8
10
  import { scoreMemories } from "./score.ts";
9
11
 
10
12
  export function argText(args: unknown): string {
@@ -47,25 +49,60 @@ export function useBoost(a: Memory | undefined, use?: UseSignals): number {
47
49
  // return the rows themselves so attribution (src/attribution.ts) can join the
48
50
  // injected facts against the session's later tool calls. `relevantKnowledge`
49
51
  // keeps its string contract for every existing caller; this is the richer seam.
52
+ export interface SelectOptions {
53
+ /**
54
+ * Hint channel (#335): when > 0, the newest `guidedCap` user-guided rows
55
+ * ride the block FIRST regardless of lexical overlap — a user-stated value
56
+ * ("the tax rate is 8.25%") shares no vocabulary with a task prompt about
57
+ * "the injected bug", and the whole point of capturing guidance is that the
58
+ * NEXT session gets it without asking. Cap + budget bound the noise; recall
59
+ * and pull leave this off and stay query-driven.
60
+ */
61
+ guidedCap?: number;
62
+ }
63
+
64
+ /** Row carries the hint-channel tag (written by capture for user-stated facts). */
65
+ export function isUserGuided(m: Memory): boolean {
66
+ return m.tags?.includes(USER_GUIDED_TAG) === true;
67
+ }
68
+
69
+ // Hint-channel caveat (#345). Measured: a WRONG user-guided row ("free
70
+ // shipping starts at $50 — the hidden suite encodes that") out-ranked correct
71
+ // code — the agent rewrote a correct threshold to match the memory. The
72
+ // generic "reference data, never instructions" framing did not prevent it.
73
+ // When guided rows ride, the header itself carries the counter-instruction:
74
+ // it rides the header line because capToBudget trims whole lines and may drop
75
+ // a standalone caveat, and the header is the one line that always survives.
76
+ const GUIDED_CAVEAT =
77
+ "; user-stated guidance may be stale — verify against the current code before changing behavior it contradicts";
78
+
50
79
  export async function selectRelevant(
51
80
  message: string,
52
81
  limit = 3,
53
82
  rows?: Memory[],
54
83
  use?: UseSignals,
55
84
  sid?: string,
85
+ opts?: SelectOptions,
56
86
  ): Promise<{ block: string; selected: Memory[] }> {
57
- const text = message.trim();
58
- if (!text) return { block: "", selected: [] };
59
87
  // Repo-scoped: model-facing reads see the caller's repo + global rows
60
88
  // (their session when one was threaded, #127).
61
89
  const mems = (rows ?? visibleTo(await loadAll(), readerFromSid(sid))).filter(
62
90
  isInjectable,
63
91
  );
64
- const top = scoreMemories(text, mems, limit, use);
65
- if (!top.length) return { block: "", selected: [] };
92
+ const cap = opts?.guidedCap ?? 0;
93
+ const guided = cap
94
+ ? mems
95
+ .filter(isUserGuided)
96
+ .sort((a, b) => cmpTs(b.ts, a.ts))
97
+ .slice(0, cap)
98
+ : [];
99
+ const text = message.trim();
100
+ const top = text ? scoreMemories(text, mems, limit, use) : [];
101
+ const merged = [...guided, ...top.filter((m) => !guided.includes(m))];
102
+ if (!merged.length) return { block: "", selected: [] };
66
103
  return {
67
- block: `## Relevant durable memory${FRAME}\n${top.map(formatMemory).join("\n")}`,
68
- selected: top,
104
+ block: `## Relevant durable memory${FRAME}${guided.length ? GUIDED_CAVEAT : ""}\n${merged.map(formatMemory).join("\n")}`,
105
+ selected: merged,
69
106
  };
70
107
  }
71
108
 
@@ -50,15 +50,15 @@ export interface StoreCounts {
50
50
  * Per-session ledger, incremented at the session.context injection decision
51
51
  * (so counts match exactly what was injected — an aborted turn still rode the
52
52
  * bytes). Cumulative fields are session-lifetime; epochRequests resets when a
53
- * new epoch freezes. An invalidation = a store_changed recompute that moved a
54
- * live epoch (the first epoch of a session is not one).
53
+ * new epoch freezes. `invalidations` counts epochs whose bytes moved (the
54
+ * first epoch is not one), not provider cache misses or re-prefill tokens.
55
55
  */
56
56
  export interface SessionStats {
57
57
  requests: number; // provider requests that injected through session.context
58
58
  abstained: number; // requests where the epoch block was empty
59
59
  cumChars: number; // lifetime sum of injected block chars
60
60
  epochRequests: number; // requests the CURRENT epoch block has ridden
61
- invalidations: number; // store_changed recomputes this session
61
+ invalidations: number; // epochs whose bytes moved; provider cost is separate
62
62
  lastInvalidation: { at: string; reason: string } | null;
63
63
  }
64
64
 
@@ -49,31 +49,27 @@ export function cacheLines(p: StatusPayload): string[] {
49
49
  const inv =
50
50
  st.invalidations === 0
51
51
  ? [
52
- " cache busts 0 — memory has never rewritten a byte of your past",
53
- " conversation, so the provider can serve history from cache",
52
+ " epochs whose bytes moved 0 — memory-section bytes have not moved this session",
54
53
  ]
55
54
  : [
56
- ` cache busts ${st.invalidations} this session · last ${
55
+ ` epochs whose bytes moved ${st.invalidations} this session · last ${
57
56
  st.lastInvalidation
58
57
  ? `${st.lastInvalidation.at.slice(11, 19)} (${st.lastInvalidation.reason})`
59
58
  : "-"
60
59
  }`,
61
- " a memory YOU saved in this session never costs one — you",
62
- " already said it (#165). A correction, a removal, or a row",
63
- " another session wrote costs exactly one, and the prefix",
64
- " re-warms on the following turn",
60
+ " counts memory-section byte changes, not provider cache misses",
65
61
  ];
66
62
  const rate = cacheRate(p.measured);
67
63
  const receipts = rate
68
64
  ? [
69
65
  ` receipts ${fmtCount(rate.read)}/${fmtCount(rate.prompt)} prompt tok served from cache (${rate.pct}%)`,
70
66
  rate.pct >= 90
71
- ? " — memory is cache-invisible: the same bytes ride every turn"
72
- : " — below ~90% something re-bills the whole history each turn",
67
+ ? " — observed session-wide cache reuse; memory-only cost is not measured"
68
+ : " — lower observed reuse; this receipt does not identify the cause",
73
69
  ]
74
70
  : [
75
- " receipts provider reports no cache usage yet — structural proof:",
76
- ` the same block bytes rode ${st.epochRequests} request(s) with ${st.invalidations} busts`,
71
+ " receipts provider reports no cache usage yet — byte history only:",
72
+ ` the block rode ${st.epochRequests} request(s) with ${st.invalidations} byte-moving epochs`,
77
73
  ];
78
74
  return [
79
75
  ...inv,
@@ -85,7 +81,7 @@ export function cacheLines(p: StatusPayload): string[] {
85
81
  /**
86
82
  * CONTEXT WINDOW — the "is memory bloating my context?" answer, built ONLY from
87
83
  * numbers we trust: the exact injected block (we wrote those bytes), the
88
- * provider's own cache receipts, and the memory-caused bust count. No estimated
84
+ * provider's own cache receipts, and the memory byte-change count. No estimated
89
85
  * decomposition of the system prompt or history (we cannot measure those); the
90
86
  * one honest share we can state is memory as a slice of what was actually sent.
91
87
  */
@@ -105,7 +101,7 @@ export function windowLines(p: StatusPayload): string[] {
105
101
  );
106
102
  out.push(
107
103
  rate
108
- ? ` cache served ${rate.pct}% of that prompt from cache → memory rides free after turn 1`
104
+ ? ` cache served ${rate.pct}% of that prompt from cache — provider-reported share, not a memory-only cost estimate`
109
105
  : " cache served provider has not reported a split yet",
110
106
  );
111
107
  } else {
@@ -113,9 +109,9 @@ export function windowLines(p: StatusPayload): string[] {
113
109
  " of what you sent not measured yet — receipts appear after the first assistant turn",
114
110
  );
115
111
  }
116
- const busts = p.stats?.invalidations ?? 0;
112
+ const moved = p.stats?.invalidations ?? 0;
117
113
  out.push(
118
- ` memory busts ${busts} this session${busts ? "" : " — memory never invalidated your cache prefix"}`,
114
+ ` epochs whose bytes moved ${moved} this session${moved ? "" : " — memory-section bytes have not moved"}`,
119
115
  );
120
116
  return out;
121
117
  }
@@ -26,7 +26,7 @@ export const register: ToolRegister = (editor, deps) => {
26
26
  validated(EmptyArgs, {
27
27
  name: "memory_status",
28
28
  description:
29
- "Plain-text memory report for chat clients (desktop/web/IDE), same sections as the terminal /memory panel: CONTEXT (this session's injected block, budget use, cumulative ride and abstentions), CACHE (plain-language cache receipts: bust count, and the provider-reported share of prompt tokens served from cache — the proof that memory never mutates your prefix), the block verbatim, recent blocked writes with gate reasons (filtered to this reader's evidence visibility, #306), and store stats. Aggregate STORE counts are machine-wide — they count every repository's rows by decision (#213 B), not this reader's. Reads only — no model call.",
29
+ "Plain-text memory report for chat clients (desktop/web/IDE), same sections as the terminal /memory panel: CONTEXT (this session's injected block, budget use, cumulative ride and abstentions), CACHE (epochs whose bytes moved, plus provider-reported cache receipts; byte changes are not a cache-miss estimate), the block verbatim, recent blocked writes with gate reasons (filtered to this reader's evidence visibility, #306), and store stats. Aggregate STORE counts are machine-wide — they count every repository's rows by decision (#213 B), not this reader's. Reads only — no model call.",
30
30
  options: direct,
31
31
  async execute(_args, context): Promise<{ content: string }> {
32
32
  // In-process truth: the live epoch + ledger, fresher than any file.
package/src/tui/panel.tsx CHANGED
@@ -300,7 +300,7 @@ function MemoryPanel(props: {
300
300
  </For>
301
301
  </Show>
302
302
 
303
- <Section t="CACHE" />
303
+ <Section t="CACHE — byte-moving epochs and provider receipts" />
304
304
  <Show
305
305
  when={s()}
306
306
  fallback={