opencode-self-improvement 0.23.1 → 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.
package/README.md CHANGED
@@ -152,7 +152,8 @@ Gate-authored evidence and its init/capture lifecycle records capture attributio
152
152
  - **Hard budgets.** Relevance block and each pull are capped at `injectBudget` characters, the frontier at `frontierBudget`, trimmed at whole-memory boundaries.
153
153
  - **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.
154
154
  - **Evidence is never injected**, and the standing system digest is two lines.
155
- - **Measured, not claimed.** The plugin reads each turn's `tokens.cache` accounting and displays the actual hit rate next to the badge.
155
+ - **Measured, not claimed.** The plugin reads each turn's `tokens.cache` accounting and displays the actual hit rate next to the badge. The same receipts now carry what the session generated — `output` and `reasoning`, shown split, because on a reasoning-heavy seat the completion side is where the cost actually goes. A host that reports neither shows nothing, never a zero.
156
+ - **Auto-capture bills separately, and it is an estimate.** Capture is its own model call made after the turn, so it appears in no session's usage: read from session numbers, the plugin's own cost is exactly zero. The host exposes no receipt for it — `ctx.generate` has one member, `text`, resolving to `{ text }` with no `usage` — so `memory_status` reports chars/4 with `receipt=none` and the words "estimate, no provider receipt" on the line. Quote that number as an estimate or not at all. A pass disposed during teardown is not billed: its store is already gone, so the count undercounts by one call there.
156
157
 
157
158
  **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:
158
159
 
@@ -367,6 +368,21 @@ Run it when you want to know whether the suite still has teeth — after changin
367
368
 
368
369
  **Pre-release ritual (decided 2026-11-04, #72):** before pushing a release commit, a human runs `--validate`, then `--selftest`, then `--fail-on-survivors`, and records the mutation score and the survivor list in `bench/RESULTS.md` beside the published evidence. Cadence is pre-release only, run by a person: the sweep is a full suite per mutant and never belongs in CI, where it would cost more than it informs. Survivors become entries on the unpinned-invariant list, not red checks.
369
370
 
371
+ ### Bench artifacts stay out of git
372
+
373
+ Raw sweep output is regenerable measurement data, and it was the largest tracked content in the repository. It is not committed (#232). A clone carries the published summaries — `bench/RESULTS.md`, `bench/recall-results.md`, `bench/test-sweep-results.md`, `bench/capture-trigger-results.md` — and the inputs those summaries are rebuilt from. History is not rewritten: the old blobs stay in earlier revisions, so this shrinks new checkouts, not the archive.
374
+
375
+ | Artifact | How to get it back |
376
+ | --- | --- |
377
+ | `bench/append-publication-198/` | The pinned recipe below. |
378
+ | A mutation sweep log | `bun scripts/test-sweep.ts --log=<path>`. |
379
+
380
+ Regenerating `bench/append-publication-198/`: the runner is `bench/runners/append-cost-198.ts`, invoked once per size, mode and platform as `bun bench/runners/append-cost-198.ts <absolute-source-checkout> <size-MiB> <baseline|candidate> <round>`. It loads `src/memory.ts`, `src/logfmt.ts` and `src/config.ts` from the source root it is given, so it must point at the two pinned checkouts of the #198 measurement — baseline `bf9f4d2` (0.15.0) and candidate `7c1dfc4` (the atomic-publication commit on that same base) — not at a current tree, where the #168 restructure moved those modules. Install locked dependencies in each checkout; use the current runner for both source roots; every invocation creates and cleans its own synthetic store and prints one JSON line. Sizes 0.1, 1, 10, 50 MiB; 3 rounds; baseline-then-candidate in rounds 1 and 3, reversed in round 2; 12 sequential appends per invocation, first 2 discarded as warmups, 30 samples pooled per mode/size/platform. Aggregation: sort `latencyMs` ascending, median = average of positions 15 and 16, p95 = nearest rank `ceil(0.95×30)` = position 29, max = position 30. Every invocation asserts the original byte prefix is unchanged and the parsed row count equals `seedRows + 12`. The full methodology — including the measurement limitations, which are part of the claim — is one command away: `git show c86379e^:bench/append-publication-198/methodology.json`.
381
+
382
+ A script that needs a missing artifact names the file and the command that produces it instead of throwing a stack trace.
383
+
384
+ The `#71` set is the deliberate exception: `bench/test-integrity-71.json`, `bench/test-integrity-71/before.jsonl`, `bench/test-integrity-71/after.jsonl` and `bench/test-integrity-71-verdicts.json` stay tracked. It looks regenerable and is not. `scripts/triage-71.ts` refuses to run unless the verdicts file carries exactly one verdict per CURRENT test file, and the test tree has grown since #71, so the documented rebuild fails on today's tree (`every current test file needs exactly one verdict`, measured on `main` at `f8f42fd`). Deleting the derived JSON would therefore destroy the only copy of a published number.
385
+
370
386
  ## Troubleshooting
371
387
 
372
388
  | Problem | Fix |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.23.1",
3
+ "version": "0.24.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": {
@@ -521,20 +521,23 @@ export function configureAutoCapture(
521
521
  lessonSet.add(normWs(f.slice(sep + 3)).toLowerCase());
522
522
  }
523
523
  }
524
+ // Hoisted so its length can be billed below.
525
+ // Redact the COMPLETE transcript, THEN apply the character budget
526
+ // (#132). Cropping first can start the window INSIDE a credential:
527
+ // a PEM body whose BEGIN marker fell off, or a token whose prefix
528
+ // fell off, matches no pattern — buildCapturePrompt's own scrub
529
+ // (kept, defense in depth) cannot recognize a fragment.
530
+ const capturePrompt = buildCapturePrompt(
531
+ redactSecrets(work).slice(-7000),
532
+ captureMax,
533
+ redactSecrets(userProse).slice(-1500),
534
+ knownRows,
535
+ attested,
536
+ );
537
+ const promptChars = capturePrompt.length;
524
538
  const out = await generateApi.text({
525
539
  model,
526
- // Redact the COMPLETE transcript, THEN apply the character budget
527
- // (#132). Cropping first can start the window INSIDE a credential:
528
- // a PEM body whose BEGIN marker fell off, or a token whose prefix
529
- // fell off, matches no pattern — buildCapturePrompt's own scrub
530
- // (kept, defense in depth) cannot recognize a fragment.
531
- prompt: buildCapturePrompt(
532
- redactSecrets(work).slice(-7000),
533
- captureMax,
534
- redactSecrets(userProse).slice(-1500),
535
- knownRows,
536
- attested,
537
- ),
540
+ prompt: capturePrompt,
538
541
  });
539
542
  const text = typeof out === "string" ? out : (out?.text ?? "");
540
543
  // #211: disposed while the model call was in flight. Stop here — the
@@ -543,6 +546,32 @@ export function configureAutoCapture(
543
546
  // is the ENOENT teardown noise this check exists to eliminate, and
544
547
  // the drain in cleanup means the pass is finished, not lost mid-air.
545
548
  if (controller.signal.aborted) return;
549
+ // #387: bill our own call. `generate.text` resolves to `{ text }` and
550
+ // nothing else — no `usage`, no `tokens` (probed against the running
551
+ // host) — and capture is not part of any session's event stream, so a
552
+ // meter reading the session reports zero for it. chars/4 is an
553
+ // estimate and the line says `receipt=none` so it can never be quoted
554
+ // as a provider number.
555
+ //
556
+ // Deliberately AFTER the teardown check above: a disposed pass has no
557
+ // store left to write to. Its tokens therefore go unbilled here, which
558
+ // undercounts by one call at teardown rather than throwing ENOENT out
559
+ // of a receipt path that must never break a session.
560
+ await record(
561
+ "capture_cost",
562
+ {
563
+ session: sid,
564
+ trigger,
565
+ prompt_chars: promptChars,
566
+ text_chars: text.length,
567
+ est_tokens: Math.ceil((promptChars + text.length) / 4),
568
+ receipt: "none",
569
+ ...(modelTag ? { model: modelTag } : {}),
570
+ },
571
+ true,
572
+ sid,
573
+ captureGate.evidenceContext,
574
+ );
546
575
  let candidates = parseCandidates(text, captureMax);
547
576
  // Deterministic guided pre-pass (POC, FINDINGS 2026-11-08 §4, option
548
577
  // `captureGuidedRules`): the user's own lines decide what is guided —
package/src/events.ts CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  import {
16
16
  sessionIdentityEvent,
17
17
  sessionUsageEvent,
18
+ foldUsage,
18
19
  } from "./identity/host-events.ts";
19
20
  import {
20
21
  afterTool,
@@ -262,14 +263,14 @@ export async function registerHooks(
262
263
  }
263
264
  const usage = sessionUsageEvent(raw);
264
265
  if (!usage) continue;
265
- const { sessionID, input, read, write } = usage;
266
+ const { sessionID } = usage;
266
267
  sessions.touch(sessionID);
267
- measuredTurns.set(sessionID, {
268
- at: new Date().toISOString(),
269
- input,
270
- read,
271
- write,
272
- });
268
+ // #394 review: fold, do not overwrite — on the compatibility path a
269
+ // receipt is per-message, and the last message is not the session.
270
+ measuredTurns.set(
271
+ sessionID,
272
+ foldUsage(usage, new Date().toISOString()),
273
+ );
273
274
  await guarded("status flush (measured)", () =>
274
275
  flushStatus(sessionID),
275
276
  );
@@ -1,5 +1,7 @@
1
1
  // Compatibility boundary for host payloads. These adapters only read data;
2
2
  // repository binding, ambient fallbacks, clocks, and I/O belong to the caller.
3
+ import type { Measured } from "../status/payload.ts";
4
+
3
5
  function fields(value: unknown): Record<string, unknown> {
4
6
  return value !== null && typeof value === "object"
5
7
  ? (value as Record<string, unknown>)
@@ -87,6 +89,27 @@ export interface SessionUsage {
87
89
  input: number;
88
90
  read: number;
89
91
  write: number;
92
+ /**
93
+ * Completion tokens the session generated (#387). Absent from the envelope
94
+ * before this, so the plugin could report what the prompt cache cost but
95
+ * never what the session itself produced — and `input` is only the UNCACHED
96
+ * remainder, so the two together understate a session by most of its size.
97
+ * Zero when the host omits the field, which is why the status surface gates
98
+ * its generation line on a nonzero rather than printing 0.
99
+ */
100
+ output: number;
101
+ reasoning: number;
102
+ /**
103
+ * The message this receipt belongs to — the `message.updated` compatibility
104
+ * path only. Streaming updates for the same message overwrite each other;
105
+ * they must not overwrite another message's receipt (#394 review).
106
+ */
107
+ messageID?: string;
108
+ /**
109
+ * True only for `session.usage.updated`: that source is cumulative, so the
110
+ * latest receipt replaces the session total instead of folding into it.
111
+ */
112
+ cumulative?: boolean;
90
113
  }
91
114
 
92
115
  /** V2 session usage, or the assistant-message usage emitted by older hosts. */
@@ -111,7 +134,66 @@ export function sessionUsageEvent(raw: unknown): SessionUsage | undefined {
111
134
  input: Number(tokens.input) || 0,
112
135
  read: Number(cache.read) || 0,
113
136
  write: Number(cache.write) || 0,
137
+ output: Number(tokens.output) || 0,
138
+ reasoning: Number(tokens.reasoning) || 0,
139
+ // The two sources mean different things, and conflating them was the
140
+ // review finding: `session.usage.updated` is cumulative, so its latest
141
+ // receipt IS the session total; `message.updated` carries ONE message's
142
+ // usage, and the total must sum across messages.
143
+ ...(event.type === "session.usage.updated" ? { cumulative: true } : {}),
144
+ ...(typeof info.id === "string" ? { messageID: info.id } : {}),
145
+ };
146
+ }
147
+
148
+ // #394 review: on the `message.updated` compatibility path each receipt is
149
+ // ONE message's usage, not the session's. Overwriting the session total with
150
+ // the last message displayed 90 completion tok where two messages produced
151
+ // 160. Streaming updates arrive repeatedly per message, so the latest receipt
152
+ // per message is kept and the session total sums across messages. A
153
+ // genuinely cumulative `session.usage.updated` keeps its replacement
154
+ // semantics. State is module-level and evicted with the session (the epoch
155
+ // controller's LRU calls forgetUsage).
156
+ const messageReceipts = new Map<string, Map<string, Measured>>();
157
+
158
+ /** Fold one usage receipt into the session's measured total. */
159
+ export function foldUsage(usage: SessionUsage, at: string): Measured {
160
+ const receipt: Measured = {
161
+ at,
162
+ input: usage.input,
163
+ read: usage.read,
164
+ write: usage.write,
165
+ output: usage.output,
166
+ reasoning: usage.reasoning,
114
167
  };
168
+ if (usage.cumulative || usage.messageID === undefined) return receipt;
169
+ let msgs = messageReceipts.get(usage.sessionID);
170
+ if (!msgs) {
171
+ msgs = new Map();
172
+ messageReceipts.set(usage.sessionID, msgs);
173
+ }
174
+ msgs.set(usage.messageID, receipt);
175
+ const total = {
176
+ at,
177
+ input: 0,
178
+ read: 0,
179
+ write: 0,
180
+ output: 0,
181
+ reasoning: 0,
182
+ };
183
+ for (const r of msgs.values()) {
184
+ total.input += r.input ?? 0;
185
+ total.read += r.read ?? 0;
186
+ total.write += r.write ?? 0;
187
+ total.output += r.output ?? 0;
188
+ total.reasoning += r.reasoning ?? 0;
189
+ if (r.at > total.at) total.at = r.at;
190
+ }
191
+ return total;
192
+ }
193
+
194
+ /** Drop a session's per-message ledger when its status entry is evicted. */
195
+ export function forgetUsage(sessionID: string): void {
196
+ messageReceipts.delete(sessionID);
115
197
  }
116
198
 
117
199
  /** Session ID envelopes accepted by capture; trigger selection stays separate. */
package/src/index.ts CHANGED
@@ -8,6 +8,7 @@
8
8
  // src/command.ts. The default export `{ id, setup(ctx) }` is checked against
9
9
  // the SDK's Plugin type using a type-only import (see the note on `plugin`).
10
10
  import { registerHooks } from "./events.ts";
11
+ import { forgetUsage } from "./identity/host-events.ts";
11
12
  import { guarded, setGuardedFailureReporter } from "./core/hooks.ts";
12
13
  import type { PluginCtx } from "./core/host.ts";
13
14
  import type { Cleanup, Plugin } from "@opencode/plugin/promise/plugin";
@@ -207,6 +208,7 @@ const impl = {
207
208
  // Code-check guided claims by default; explicit false opts out.
208
209
  contradictionSurface: ctx.options?.contradictionSurface !== false,
209
210
  measuredTurns,
211
+ forgetUsage,
210
212
  noteHits: (sid, rows, query) => noteHits("inject", sid, rows, query),
211
213
  });
212
214
  const flushStatus = sessions.flushStatus;
@@ -38,6 +38,8 @@ interface InjectionEpochOptions {
38
38
  // The host listener records usage. Eviction must still drop it with the
39
39
  // epoch and request counters, so no measurement outlives its tracked session.
40
40
  measuredTurns: Pick<Map<string, Measured>, "get" | "delete">;
41
+ /** Evict the per-message usage ledger (#394) with the session. */
42
+ forgetUsage?: (sid: string) => void;
41
43
  noteHits: (sid: string, rows: Memory[], query: string) => Promise<void>;
42
44
  }
43
45
 
@@ -46,6 +48,7 @@ export function createInjectionEpochs({
46
48
  frontierBudget: openBudget,
47
49
  contradictionSurface = true,
48
50
  measuredTurns,
51
+ forgetUsage,
49
52
  noteHits,
50
53
  }: InjectionEpochOptions) {
51
54
  // Per-session frozen injection epochs: the whole memory section (digest +
@@ -106,6 +109,7 @@ export function createInjectionEpochs({
106
109
  latestPrompt.delete(sid);
107
110
  sessionStats.delete(sid);
108
111
  measuredTurns.delete(sid);
112
+ forgetUsage?.(sid);
109
113
  });
110
114
  const statsFor = (sid: string): SessionStats => {
111
115
  let st = sessionStats.get(sid);
@@ -203,6 +207,11 @@ export function createInjectionEpochs({
203
207
  undefined,
204
208
  {
205
209
  guidedCap: 3,
210
+ // #388: budget the RIDING set by priority here, before the block is
211
+ // rendered in canonical order. Capping the rendered string (the old
212
+ // path) made recency decide who got dropped, because the newest row is
213
+ // now always first.
214
+ budget,
206
215
  ...(contradictionSurface
207
216
  ? {
208
217
  conflictCheck: true,
@@ -211,6 +220,14 @@ export function createInjectionEpochs({
211
220
  : {}),
212
221
  },
213
222
  );
223
+ // UNREACHABLE today, not a guard: `selectRelevant` was handed the same
224
+ // `budget` and builds the block as header + Σ(1 + line) over lines it
225
+ // accepted while that running sum stayed ≤ budget, and every line length is
226
+ // non-negative. So a non-empty `sel.block` is already ≤ budget, capToBudget
227
+ // keeps every line, and this call returns its argument unchanged. No test
228
+ // can reach a different result; it stays only as a byte bound on the text
229
+ // that rides the prompt if a future caller stops budgeting inside the
230
+ // selector.
214
231
  const block = sel.block ? capToBudget(sel.block, budget) : "";
215
232
  // Refs the ACTUALLY-injected rows assert (paths + commands), the join key
216
233
  // for attribution. Derived from the budget-surviving rows, not the wider
@@ -328,7 +345,8 @@ export function createInjectionEpochs({
328
345
  // Hint-channel attribution (mystery 2): a wire miss is one grep away.
329
346
  // guidedSeen=0 -> capture never wrote the row. guidedSeen>0 with the
330
347
  // id absent from `guided` -> the cap (newest-first, 3) dropped it.
331
- // In `guided` but absent from `guidedRode` -> capToBudget dropped it.
348
+ // In `guided` but absent from `guidedRode` -> the budget inside
349
+ // selectRelevant dropped it (#388 moved the cap there from capToBudget).
332
350
  // In `guidedRode` yet absent from the wire -> render/transport, or a
333
351
  // paraphrased needle (now impossible for rows carrying `orig=true`).
334
352
  ...(built.guidedSeen ? { guidedSeen: built.guidedSeen } : {}),
@@ -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(
@@ -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,