opencode-self-improvement 0.23.0 → 0.24.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.
@@ -72,6 +72,15 @@ export interface SelectOptions {
72
72
  * no check: rows render plainly, exactly as before the feature.
73
73
  */
74
74
  repoDir?: string;
75
+ /**
76
+ * Character budget for the block (#388). Applied to the PRIORITY order —
77
+ * guided lane first, then score — so pressure drops the least RELEVANT row.
78
+ * Capping the rendered string instead would let recency decide who rides,
79
+ * because the rendered order is canonical and not score-derived. Absent
80
+ * means unbounded, which is what the callers that cap the string themselves
81
+ * have always had.
82
+ */
83
+ budget?: number;
75
84
  }
76
85
 
77
86
  /** Row carries the hint-channel tag (written by capture for user-stated facts). */
@@ -139,11 +148,90 @@ export async function selectRelevant(
139
148
  }
140
149
  const text = message.trim();
141
150
  const top = text ? scoreMemories(text, mems, limit, use) : [];
142
- const merged = [...guided, ...top.filter((m) => !guided.includes(m))];
151
+ const rest = top.filter((m) => !guided.includes(m));
152
+ const merged = [...guided, ...rest];
143
153
  if (!merged.length) return { block: "", selected: [], rendered };
144
- const hasConflict = rendered.size > 0;
154
+ const lines = merged.map((m) => formatMemory(rendered.get(m) ?? m));
155
+ // The caveat must describe the rows that ACTUALLY ride, so it cannot be fixed
156
+ // before the budget runs (it used to be, and a budget that dropped the only
157
+ // CONFLICT row still rendered "CONFLICT rows were code-checked … follow their
158
+ // Action" over a block with none). The caveat also decides the header width
159
+ // the budget is measured against, so the FIT uses the widest header this
160
+ // selection can still produce and the RENDERED header is chosen afterwards
161
+ // from the survivors. Re-fitting on the narrower header instead oscillates:
162
+ // dropping the CONFLICT row shortens the header, which lets it fit again.
163
+ const baseHeader = `## Relevant durable memory${FRAME}`;
164
+ const widestCaveat = rendered.size
165
+ ? CONFLICT_CAVEAT
166
+ : guided.length
167
+ ? GUIDED_CAVEAT
168
+ : "";
169
+ const fitHeader = baseHeader + widestCaveat;
170
+ const caveatFor = (survivors: number[]): string => {
171
+ let guidedRides = false;
172
+ let conflictRides = false;
173
+ for (const i of survivors) {
174
+ const m = merged[i];
175
+ if (!m) continue;
176
+ if (guided.includes(m)) guidedRides = true;
177
+ if (rendered.has(m)) conflictRides = true;
178
+ }
179
+ return !guidedRides ? "" : conflictRides ? CONFLICT_CAVEAT : GUIDED_CAVEAT;
180
+ };
181
+ // PRIORITY decides who rides; CANONICAL order decides how they are shown.
182
+ // The rendered bytes are the prompt-cache key (src/inject/epochs.ts joins
183
+ // them onto the system parts), and score order is a function of the live
184
+ // prompt — so two turns that selected the same rows in a different rank
185
+ // order re-billed the whole prefix to tell the model what it already knew.
186
+ // `selected` keeps score order: the use ledger and attribution credit the
187
+ // ranking, and a miss has to stay diagnosable.
188
+ let shown = merged.map((_, i) => i);
189
+ const budget = opts?.budget;
190
+ if (budget !== undefined) {
191
+ // Same whole-line discipline capToBudget uses (skip an over-long line,
192
+ // keep scanning), applied BEFORE the re-order so relevance still decides.
193
+ // A block left with nothing but its header renders as nothing — a dangling
194
+ // "## Relevant durable memory" over zero memories is noise, not memory. A
195
+ // header too wide for the budget needs no separate guard: `used` starts at
196
+ // the header width, so no line can clear the test below and the empty
197
+ // `shown` returns exactly what an explicit header check would.
198
+ let used = fitHeader.length;
199
+ shown = [];
200
+ for (let i = 0; i < lines.length; i++) {
201
+ const line = lines[i] ?? "";
202
+ if (used + 1 + line.length > budget) continue;
203
+ shown.push(i);
204
+ used += 1 + line.length;
205
+ }
206
+ // `selected` keeps the PRE-budget selection even here: the evidence field
207
+ // `guided=` answers "did the selector pick it", `guidedRode=` answers "did
208
+ // it survive". Returning [] would make a total trim read as "never picked".
209
+ if (!shown.length) return { block: "", selected: merged, rendered };
210
+ }
211
+ shown.sort((a, b) => {
212
+ const ma = merged[a];
213
+ const mb = merged[b];
214
+ if (!ma || !mb) return 0;
215
+ const lane = (m: Memory) => (guided.includes(m) ? 0 : 1);
216
+ if (lane(ma) !== lane(mb)) return lane(ma) - lane(mb);
217
+ const recency = cmpTs(mb.ts, ma.ts);
218
+ if (recency !== 0) return recency;
219
+ // TOTAL order, not merely newest-first. Two rows can share an instant: a
220
+ // same-millisecond pair, or a legacy second-precision stamp beside a
221
+ // millisecond stamp for the same instant (`ISO_TS_RE` makes `.000`
222
+ // optional, so both load). cmpTs returns 0 there and a stable sort falls
223
+ // back to score order — the prompt-derived order this PR exists to remove,
224
+ // one row pair away. Content, then the literal ts string, are both
225
+ // prompt-independent, so the bytes depend on the SET of rows and nothing
226
+ // else.
227
+ if (ma.content !== mb.content) return ma.content < mb.content ? -1 : 1;
228
+ return ma.ts < mb.ts ? -1 : ma.ts > mb.ts ? 1 : 0;
229
+ });
145
230
  return {
146
- block: `## Relevant durable memory${FRAME}${guided.length ? (hasConflict ? CONFLICT_CAVEAT : GUIDED_CAVEAT) : ""}\n${merged.map((m) => formatMemory(rendered.get(m) ?? m)).join("\n")}`,
231
+ block: [
232
+ baseHeader + caveatFor(shown),
233
+ ...shown.map((i) => lines[i] ?? ""),
234
+ ].join("\n"),
147
235
  selected: merged,
148
236
  rendered,
149
237
  };
@@ -80,6 +80,74 @@ export async function captureLagLines(days = 30): Promise<string[]> {
80
80
  return out;
81
81
  }
82
82
 
83
+ /**
84
+ * What the plugin's own model calls cost (#387).
85
+ *
86
+ * Capture is a separate `generate.text` call made after the turn, so it appears
87
+ * in NO session's usage: read from the session event stream the plugin's cost
88
+ * is exactly zero, which is how it was billed for its whole history. The host
89
+ * exposes no receipt either — `ctx.generate` has one member, `text`, and it
90
+ * resolves to `{ text }` with no `usage` and no `tokens` (probed against the
91
+ * running host, 2026-11-11). So this is an ESTIMATE, labelled as one on every
92
+ * line, and the honest alternative to it is silence rather than a rounder number.
93
+ *
94
+ * Estimate is chars/4 both ways, the same convention `estTok` uses for the
95
+ * injected block. It cannot see reasoning tokens, which on a local seat are the
96
+ * bulk of a capture completion (measured 94%), so it UNDERSTATES. Say so where
97
+ * it is rendered.
98
+ */
99
+ export interface CaptureCost {
100
+ /** Capture model calls that completed in the window. */
101
+ calls: number;
102
+ /** Distinct sessions those calls belong to. */
103
+ sessions: number;
104
+ promptChars: number;
105
+ textChars: number;
106
+ /** chars/4, both directions summed. An estimate, never a receipt. */
107
+ estTokens: number;
108
+ /** Always "estimate": no provider receipt exists for these calls. */
109
+ source: "estimate";
110
+ }
111
+
112
+ export function captureCost(
113
+ lines: string[],
114
+ days = 30,
115
+ now = Date.now(),
116
+ ): CaptureCost {
117
+ const cutoff = new Date(now - days * 86_400_000).toISOString();
118
+ const out: CaptureCost = {
119
+ calls: 0,
120
+ sessions: 0,
121
+ promptChars: 0,
122
+ textChars: 0,
123
+ estTokens: 0,
124
+ source: "estimate",
125
+ };
126
+ const seen = new Set<string>();
127
+ for (const line of lines) {
128
+ const f = parseLine(line);
129
+ if (!f || f.ev !== "capture_cost") continue;
130
+ if (typeof f.ts === "string" && f.ts < cutoff) continue;
131
+ // A blank or non-numeric count is skipped, NOT read as zero: `Number("")`
132
+ // is 0, so a line whose count failed to render would be billed as a free
133
+ // capture — the exact error this whole ticket exists to remove.
134
+ const raw = f.prompt_chars;
135
+ const chars =
136
+ typeof raw === "string" && raw.trim() !== "" ? Number(raw) : Number.NaN;
137
+ if (!Number.isFinite(chars) || chars < 0) continue;
138
+ out.calls++;
139
+ out.promptChars += chars;
140
+ out.textChars += Number(f.text_chars) || 0;
141
+ out.estTokens +=
142
+ Number(f.est_tokens) ||
143
+ Math.ceil((chars + (Number(f.text_chars) || 0)) / 4);
144
+ const sid = typeof f.session === "string" ? f.session : "";
145
+ if (sid) seen.add(sid);
146
+ }
147
+ out.sessions = seen.size;
148
+ return out;
149
+ }
150
+
83
151
  /**
84
152
  * Capture health (#138): the answer to "is auto-capture off, misconfigured,
85
153
  * armed-but-inert, or alive?" read from the evidence file ALONE — the
@@ -16,7 +16,12 @@
16
16
  import { preparePrivateFile } from "../core/permissions.ts";
17
17
  import { readFile } from "node:fs/promises";
18
18
  import type { Attribution } from "../inject/attribution.ts";
19
- import { captureLag, ledgerIsYoung, rowsPerDay } from "./metrics.ts";
19
+ import {
20
+ captureLag,
21
+ type CaptureCost,
22
+ ledgerIsYoung,
23
+ rowsPerDay,
24
+ } from "./metrics.ts";
20
25
 
21
26
  export interface StoreCounts {
22
27
  active: number;
@@ -44,6 +49,12 @@ export interface StoreCounts {
44
49
  rowsPerDay?: number;
45
50
  /** Capture latency in ms, p50/p95, from `capture_lag` evidence. */
46
51
  captureLag?: { p50: number; p95: number; n: number };
52
+ /**
53
+ * What the plugin's own model calls cost (#387), from `capture_cost`
54
+ * evidence. An ESTIMATE: the host gives capture no receipt. Absent until
55
+ * evidence is read — a missing number, never a zero that reads as free.
56
+ */
57
+ captureCost?: CaptureCost;
47
58
  }
48
59
 
49
60
  /**
@@ -76,14 +87,28 @@ export function emptyStats(): SessionStats {
76
87
  /**
77
88
  * Measured prompt-cache usage from the last usage event — `session.usage.updated`
78
89
  * (v2 hosts) or `message.updated` assistant info (older hosts) — carrying tokens
79
- * {input, cache.read, cache.write}. This is the SESSION-WIDE prompt cache — the
80
- * honest receipt for "are we busting cache", never billed as our block's own rate.
90
+ * {input, output, reasoning, cache.read/write}. This is the SESSION-WIDE prompt
91
+ * cache — the honest receipt for "are we busting cache", never billed as our
92
+ * block's own rate. Cumulative, not a per-message snapshot: the final streaming
93
+ * update carries the whole session (see the note in src/events.ts).
81
94
  */
82
95
  export interface Measured {
83
96
  at: string;
84
97
  input: number;
85
98
  read: number;
86
99
  write: number;
100
+ /**
101
+ * Completion tokens for the session (#387): what the model produced, split
102
+ * so a reasoning-heavy seat is visible as one. `input` alone is only the
103
+ * uncached remainder, so quoting it as "what the session cost" understates
104
+ * it by most of its size — measured 13,393 reported against 187,856 moved.
105
+ *
106
+ * Optional on PURPOSE: this object is a persisted file read by a newer TUI
107
+ * than wrote it, and a host may omit the fields too. Absent means "not
108
+ * reported", which the surfaces render as nothing — never as 0.
109
+ */
110
+ output?: number;
111
+ reasoning?: number;
87
112
  }
88
113
 
89
114
  export interface StatusPayload {
@@ -109,6 +109,17 @@ export function windowLines(p: StatusPayload): string[] {
109
109
  " of what you sent not measured yet — receipts appear after the first assistant turn",
110
110
  );
111
111
  }
112
+ // #387: the completion side. Everything above counts the prompt only, and
113
+ // `input` is the UNCACHED remainder, so neither was ever "what the session
114
+ // cost" — the tokens the model produced were not reported at all. Rendered
115
+ // only when the host reports them: an absent number stays absent rather than
116
+ // showing 0, which reads as "generated nothing".
117
+ const gen = m ? (m.output ?? 0) + (m.reasoning ?? 0) : 0;
118
+ if (gen > 0) {
119
+ out.push(
120
+ ` what it produced ${fmtCount(gen)} completion tok — ${fmtCount(m?.output ?? 0)} answer + ${fmtCount(m?.reasoning ?? 0)} reasoning (provider-reported, session-wide)`,
121
+ );
122
+ }
112
123
  const moved = p.stats?.invalidations ?? 0;
113
124
  out.push(
114
125
  ` epochs whose bytes moved ${moved} this session${moved ? "" : " — memory-section bytes have not moved"}`,
@@ -284,6 +295,18 @@ export function renderMemoryReport(input: {
284
295
  `capture lag p50 ${fmtMs(store.captureLag.p50)} / p95 ${fmtMs(store.captureLag.p95)}`,
285
296
  );
286
297
  }
298
+ // #387: capture is a separate model call outside every session's usage, so
299
+ // anything that reads session numbers reports it as free. Render it even at
300
+ // zero, with the reason, because "0" and "never ran" are different facts and
301
+ // the plugin billed it as the first for its whole history.
302
+ if (store.captureCost) {
303
+ const c = store.captureCost;
304
+ sizing.push(
305
+ c.calls
306
+ ? `capture ~${fmtCount(c.estTokens)} tok est. over ${c.calls} call${c.calls === 1 ? "" : "s"} (${fmtCount(c.promptChars)} in / ${fmtCount(c.textChars)} out, ${c.sessions} session${c.sessions === 1 ? "" : "s"}) — estimate, no provider receipt`
307
+ : "capture 0 tok — no capture call in the window",
308
+ );
309
+ }
287
310
  if (sizing.length) out.push(` ${sizing.join(" · ")}`);
288
311
  if (input.capture) {
289
312
  out.push(
@@ -1,4 +1,5 @@
1
1
  // predicates — split from src/memory.ts (#168 domain restructure). Declaration bodies are unchanged.
2
+ import { INIT_STAMP_TAG } from "../../core/tags.ts";
2
3
  import { isQuarantined } from "../quarantine/quarantine.ts";
3
4
  import type { Memory } from "./memory.ts";
4
5
 
@@ -7,6 +8,17 @@ export function isActive(m: Memory): boolean {
7
8
  }
8
9
 
9
10
  // Quarantine remains durable and reviewable; only model-facing reads withhold it.
11
+ // The legacy `init-stamp` tag joins it (#376 review). A pre-#374 stamp row is
12
+ // plugin bookkeeping, and migration only retires a row whose `init_complete`
13
+ // audit line survives; in a store where that line is gone the row stays active
14
+ // forever, so the tag itself has to keep it off the prompt. This is the one
15
+ // predicate every model-facing read uses, so injection, recall, list, digest and
16
+ // the capture context all withhold it together. Store reads that are NOT
17
+ // model-facing — the viewer, memory_forget, memory_undo, export — still see it.
10
18
  export function isInjectable(m: Memory): boolean {
11
- return isActive(m) && !isQuarantined(m);
19
+ return (
20
+ isActive(m) &&
21
+ !isQuarantined(m) &&
22
+ m.tags?.includes(INIT_STAMP_TAG) !== true
23
+ );
12
24
  }
package/src/tools/init.ts CHANGED
@@ -19,7 +19,7 @@ export const register: ToolRegister = (editor, deps) => {
19
19
  validated(InitArgs, {
20
20
  name: "memory_init",
21
21
  description:
22
- "Initialize repository memory: re-derives build/lint/test/typecheck command memories through the write gate and stores an init stamp keyed on git HEAD. Idempotent: a no-op when the stamp matches HEAD, unless force=true (refresh after a refactor).",
22
+ "Initialize repository memory: re-derives build/lint/test/typecheck command memories through the write gate and records an init stamp keyed on git HEAD. The stamp is plugin bookkeeping under <memory-root>/init-stamps/, not a memory row, so no session can forge it (#374). Idempotent: a no-op when the stamp matches HEAD, unless force=true (refresh after a refactor).",
23
23
  options: direct,
24
24
  async execute(args, context): Promise<{ content: string }> {
25
25
  const { sid } = toolIds(context);
@@ -12,6 +12,7 @@ import {
12
12
  import { EmptyArgs, validated } from "./schema.ts";
13
13
  import {
14
14
  captureHealth,
15
+ captureCost,
15
16
  captureLag,
16
17
  captureLagLines,
17
18
  rowsPerDay,
@@ -57,6 +58,9 @@ export const register: ToolRegister = (editor, deps) => {
57
58
  store.rowsPerDay = rowsPerDay(act) ?? undefined;
58
59
  const evidenceLines = await captureLagLines();
59
60
  store.captureLag = captureLag(evidenceLines);
61
+ // #387: the plugin's own model calls, billed. Same evidence read, so
62
+ // the number cannot disagree with the lag line above it.
63
+ store.captureCost = captureCost(evidenceLines);
60
64
  return {
61
65
  content: renderMemoryReport({
62
66
  status,