opencode-self-improvement 0.23.1 → 0.24.1
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 +44 -4
- package/package.json +1 -1
- package/src/capture/runtime.ts +41 -12
- package/src/events.ts +8 -7
- package/src/identity/host-events.ts +82 -0
- package/src/index.ts +2 -0
- package/src/inject/epochs.ts +19 -1
- package/src/recall/relevant.ts +91 -3
- package/src/status/metrics.ts +68 -0
- package/src/status/payload.ts +28 -3
- package/src/status/report.ts +23 -0
- package/src/tools/status-tool.ts +4 -0
package/README.md
CHANGED
|
@@ -144,15 +144,40 @@ Injection, recall, the frontier block, compaction, `memory_forget` and decay onl
|
|
|
144
144
|
|
|
145
145
|
Gate-authored evidence and its init/capture lifecycle records capture attribution at operation entry: if a session moves repositories while the operation runs, its audit lines remain in the starting repository's partition and can be read with `memory_evidence` from a session bound there. Init start/complete/skip, capture outcomes/refusals, and capture lag share that captured owner. A captured named session with no resolved repository keeps a session-private `sid` label even on lifecycle records that suppress call metadata; otherwise an unstamped line would appear global. Viewer audit attribution and cancellation of in-flight capture are separate boundaries.
|
|
146
146
|
|
|
147
|
+
## What memory is worth, measured
|
|
148
|
+
|
|
149
|
+
Two results. Only two are quoted, each with its `n` and the seat it ran on, because the direction of an early finding flipped when the metric was corrected — see [#385](https://github.com/abogartz/opencode-self-improvement/issues/385) and [#392](https://github.com/abogartz/opencode-self-improvement/issues/392).
|
|
150
|
+
|
|
151
|
+
**The metric.** `work = session generation + capture generation`, with cache read and cache write reported separately and never folded into a total. Capture is a separate model call made after the turn, so it appears in no session's usage: a meter that reads session numbers alone reports this plugin's own cost as exactly zero. On the seat below `input` is only the **uncached remainder** — one run reported 13,393 of 187,856 tokens that actually moved, 7%.
|
|
152
|
+
|
|
153
|
+
| Result | n | Seat | What was measured |
|
|
154
|
+
| --- | --- | --- | --- |
|
|
155
|
+
| **Transport.** A fact learned in one session reaches a later session that provably cannot obtain it any other way | 5 per arm, with the empty-store floor verified first | `evo/Qwen3.8-Flash-Next-UD-Q4_K_XL`, local seat behind a recording proxy | empty store **0/5** (every failure: the artifact was never written), the same store seeded **5/5**. The fixture is leak-checked: no form of the answer is in any file the agent sees, including its own documentation |
|
|
156
|
+
| **Reuse.** A memory reduces the work on a task the agent already passes | 6 pairs | same seat | median of the six per-pair L2/L0 work ratios — sorted 0.54, 0.79, 0.84, 0.98, 1.06, 1.23, middle two averaged — **0.91×**, higher in 2 of 6, inside the pre-registered 0.80–1.25 band: **no measurable effect at 20% resolution**. A memory about an unrelated task: **0.99×**, same estimator, higher in 3 of 6 |
|
|
157
|
+
|
|
158
|
+
**What is not claimed here.** No token saving. No dollar figure. The seat above is a local box with no cache price; on a hosted provider a cache miss costs roughly 0.1× read and 1.25× write, which is a different claim and cannot be quoted from these numbers.
|
|
159
|
+
|
|
160
|
+
**Rules for any cost claim in this repository** — enforced by `test/claims.test.ts`, which runs in CI:
|
|
161
|
+
|
|
162
|
+
- No cost claim below **n=6 pairs per arm**. A ratio at `6 ≤ n < 21` is labelled **"20% resolution"**.
|
|
163
|
+
- A **seat** and a **metric** are named on the same line as the number.
|
|
164
|
+
- The word "cheaper" does not appear without those.
|
|
165
|
+
- An issue or PR body making a cost claim owes the same n, seat and metric. CI reads only this file, so that half is enforced by review.
|
|
166
|
+
- Nothing reproduces at n=1: the same arm on the same fixture, both runs passing, differed by more than 2× in tokens.
|
|
167
|
+
- Cache state is reported, never assumed. Two runs that start from different cache states are not a saving.
|
|
168
|
+
|
|
147
169
|
## Token cost and caching
|
|
148
170
|
|
|
149
171
|
- **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.
|
|
150
172
|
- **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.
|
|
151
173
|
- **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.
|
|
174
|
+
- **User-stated guidance rides ahead of relevance.** A row auto-capture tagged `user-guided` — something you said outright, like "the correct sales tax rate is 8.25%" — rides the block ahead of the lexical picks: newest-first, at most three, and `injectBudget` still bounds the whole block (`test/hint-channel.test.ts`). The channel exists because ranking cannot bridge vocabulary: a prompt about "the injected bug" shares no word with a row stating a tax rate, and the shipped matcher scored it zero ([#334](https://github.com/abogartz/opencode-self-improvement/issues/334)). `memory_recall` and the contextual pull stay query-driven — the channel changes only what rides the prompt. Because always-riding priority is a poisoning amplifier, the tag is minted by auto-capture alone: `memory_remember`, `memory_update` replacements and JSONL imports strip it, along with the contradiction fields ([#342](https://github.com/abogartz/opencode-self-improvement/issues/342), `test/guidance-provenance.test.ts`).
|
|
175
|
+
- **The block re-scores at every user turn.** An epoch is not frozen at the first request: a later prompt re-scores, and the epoch MOVES only when the rendered bytes move — a prompt change that selects the same rows in the same order costs no cache bust ([#340](https://github.com/abogartz/opencode-self-improvement/issues/340), `test/epoch.test.ts`). Order is part of those bytes on this build: the lexical picks render in score order, so a prompt that keeps the same rows and re-ranks them moves the bytes and pays the bust. Canonical render order, which removes that churn, is still open ([#388](https://github.com/abogartz/opencode-self-improvement/issues/388), [#396](https://github.com/abogartz/opencode-self-improvement/pull/396)).
|
|
152
176
|
- **Hard budgets.** Relevance block and each pull are capped at `injectBudget` characters, the frontier at `frontierBudget`, trimmed at whole-memory boundaries.
|
|
153
177
|
- **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
178
|
- **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.
|
|
179
|
+
- **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.
|
|
180
|
+
- **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
181
|
|
|
157
182
|
**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
183
|
|
|
@@ -163,13 +188,13 @@ Gate-authored evidence and its init/capture lifecycle records capture attributio
|
|
|
163
188
|
| C — section frozen on rendered bytes | 4 | 3 | 55258 | 2762.9 | 2856 |
|
|
164
189
|
| D — C + riding bytes (shipped) | 1 | 0 | 53500 | 2675.0 | 2675 |
|
|
165
190
|
|
|
166
|
-
The byte-
|
|
191
|
+
The invalidation counter counts **byte-moving recomputes**: epochs whose memory-section bytes differ from the previous epoch. It is not a provider cache-miss or re-prefill count, and no status surface claims it is. 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`. The workload re-scores only when the store fingerprint moves, so its 20 prompts never re-rank one shared set — D's `0` is not evidence about the same-set re-ranking above. D also injects 12.3% fewer **characters** than the naive policy, measured over the whole section — bytes on a deterministic workload, not tokens and not a provider bill. Reproduce this deterministic byte workload:
|
|
167
192
|
|
|
168
193
|
```sh
|
|
169
194
|
bun run bench
|
|
170
195
|
```
|
|
171
196
|
|
|
172
|
-
**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.
|
|
197
|
+
**Author-reported provider audit**, not a new measurement here, and **input tokens only** (on that provider `input` is the uncached remainder, so this is not a total and not a saving): [#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.
|
|
173
198
|
|
|
174
199
|
## Recall quality
|
|
175
200
|
|
|
@@ -363,10 +388,25 @@ bun run sweep:test
|
|
|
363
388
|
|
|
364
389
|
The output is a canonical mutation score — killed over total, with equivalent mutants and load errors excluded from the denominator — plus the survivors, the unpinned invariants. Survivors are the audit's output, not a scandal: some mutants are expected to survive and become entries on the unpinned list rather than red CI.
|
|
365
390
|
|
|
366
|
-
Run it when you want to know whether the suite still has teeth — after changing tests or coverage, or as a pre-release gate with `bun scripts/test-sweep.ts --fail-on-survivors`, which exits 4 when anything survives. Two
|
|
391
|
+
Run it when you want to know whether the suite still has teeth — after changing tests or coverage, or as a pre-release gate with `bun scripts/test-sweep.ts --fail-on-survivors`, which exits 4 when anything survives. Two lighter checks come first: `bun scripts/test-sweep.ts --validate` confirms every mutation pattern still lands on exactly one source site without running the suite, and `bun scripts/test-sweep.ts --selftest` plants a mutation in a trivially-tested pure function and fails unless the suite kills it — proof the instrument itself can go red.
|
|
367
392
|
|
|
368
393
|
**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
394
|
|
|
395
|
+
### Bench artifacts stay out of git
|
|
396
|
+
|
|
397
|
+
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.
|
|
398
|
+
|
|
399
|
+
| Artifact | How to get it back |
|
|
400
|
+
| --- | --- |
|
|
401
|
+
| `bench/append-publication-198/` | The pinned recipe below. |
|
|
402
|
+
| A mutation sweep log | `bun scripts/test-sweep.ts --log=<path>`. |
|
|
403
|
+
|
|
404
|
+
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`.
|
|
405
|
+
|
|
406
|
+
A script that needs a missing artifact names the file and the command that produces it instead of throwing a stack trace.
|
|
407
|
+
|
|
408
|
+
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.
|
|
409
|
+
|
|
370
410
|
## Troubleshooting
|
|
371
411
|
|
|
372
412
|
| Problem | Fix |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-self-improvement",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.24.1",
|
|
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/capture/runtime.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
|
266
|
+
const { sessionID } = usage;
|
|
266
267
|
sessions.touch(sessionID);
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
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;
|
package/src/inject/epochs.ts
CHANGED
|
@@ -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` ->
|
|
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 } : {}),
|
package/src/recall/relevant.ts
CHANGED
|
@@ -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
|
|
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
|
|
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:
|
|
231
|
+
block: [
|
|
232
|
+
baseHeader + caveatFor(shown),
|
|
233
|
+
...shown.map((i) => lines[i] ?? ""),
|
|
234
|
+
].join("\n"),
|
|
147
235
|
selected: merged,
|
|
148
236
|
rendered,
|
|
149
237
|
};
|
package/src/status/metrics.ts
CHANGED
|
@@ -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
|
package/src/status/payload.ts
CHANGED
|
@@ -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 {
|
|
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,
|
|
80
|
-
* honest receipt for "are we busting cache", never billed as our
|
|
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 {
|
package/src/status/report.ts
CHANGED
|
@@ -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(
|
package/src/tools/status-tool.ts
CHANGED
|
@@ -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,
|