opencode-self-improvement 0.15.4 → 0.15.6

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.
Files changed (100) hide show
  1. package/README.md +2 -0
  2. package/package.json +2 -2
  3. package/src/capture/candidates.ts +110 -0
  4. package/src/capture/lag.ts +18 -0
  5. package/src/capture/prompt.ts +50 -0
  6. package/src/capture/transcript.ts +59 -0
  7. package/src/{triggers.ts → capture/triggers.ts} +6 -5
  8. package/src/{command.ts → command/ensure.ts} +2 -2
  9. package/src/{consolidate.ts → consolidate/propose.ts} +7 -30
  10. package/src/consolidate/render.ts +30 -0
  11. package/src/core/cmp-ts.ts +16 -0
  12. package/src/core/config/budgets.ts +28 -0
  13. package/src/{config.ts → core/config/paths.ts} +6 -31
  14. package/src/core/logfmt/format.ts +82 -0
  15. package/src/{logfmt.ts → core/logfmt/publish.ts} +20 -96
  16. package/src/core/logfmt/read.ts +15 -0
  17. package/src/core/permissions.ts +47 -0
  18. package/src/{state.ts → core/state.ts} +1 -1
  19. package/src/core/time.ts +6 -0
  20. package/src/{evidence.ts → evidence/record.ts} +7 -5
  21. package/src/{gates.ts → gate/gate.ts} +19 -21
  22. package/src/{resolver.ts → gate/resolver.ts} +1 -1
  23. package/src/{hits.ts → hits/ledger.ts} +8 -6
  24. package/src/index.ts +64 -943
  25. package/src/init/detect.ts +144 -0
  26. package/src/init/format.ts +25 -0
  27. package/src/init/run.ts +188 -0
  28. package/src/inject/anchor.ts +43 -0
  29. package/src/{attribution.ts → inject/attribution.ts} +2 -2
  30. package/src/inject/budget.ts +78 -0
  31. package/src/inject/digest.ts +89 -0
  32. package/src/{injection-epochs.ts → inject/epochs.ts} +15 -14
  33. package/src/inject/format.ts +32 -0
  34. package/src/inject/pull.ts +52 -0
  35. package/src/inject/version.ts +31 -0
  36. package/src/portable/decay.ts +20 -0
  37. package/src/portable/export.ts +194 -0
  38. package/src/portable/import.ts +173 -0
  39. package/src/recall/relevant.ts +72 -0
  40. package/src/recall/score.ts +106 -0
  41. package/src/recall/shared-terms.ts +15 -0
  42. package/src/status/format.ts +58 -0
  43. package/src/status/metrics.ts +65 -0
  44. package/src/status/payload.ts +145 -0
  45. package/src/status/report.ts +202 -0
  46. package/src/status/write.ts +114 -0
  47. package/src/{blocklist.ts → store/blocklist.ts} +4 -2
  48. package/src/store/files/append.ts +176 -0
  49. package/src/store/files/deletions.ts +31 -0
  50. package/src/store/files/load.ts +106 -0
  51. package/src/store/files/prune.ts +81 -0
  52. package/src/store/files/snapshots.ts +88 -0
  53. package/src/store/files/supersede.ts +123 -0
  54. package/src/store/files/target.ts +36 -0
  55. package/src/{lock.ts → store/lock.ts} +5 -4
  56. package/src/store/model/memory.ts +91 -0
  57. package/src/store/model/predicates.ts +12 -0
  58. package/src/store/model/visibility.ts +140 -0
  59. package/src/{prune.ts → store/prune.ts} +4 -3
  60. package/src/store/quarantine/release.ts +24 -0
  61. package/src/store/tombstones/rejection.ts +93 -0
  62. package/src/{tombstones.ts → store/tombstones/tombstone.ts} +12 -97
  63. package/src/{undo.ts → store/undo.ts} +6 -3
  64. package/src/tools/consolidate.ts +42 -0
  65. package/src/tools/decay.ts +83 -0
  66. package/src/tools/deps.ts +27 -0
  67. package/src/tools/evidence.ts +48 -0
  68. package/src/tools/export.ts +27 -0
  69. package/src/tools/forget.ts +23 -0
  70. package/src/tools/import.ts +57 -0
  71. package/src/tools/init.ts +30 -0
  72. package/src/tools/list.ts +36 -0
  73. package/src/tools/merge-review.ts +138 -0
  74. package/src/tools/recall.ts +72 -0
  75. package/src/tools/registry.ts +40 -0
  76. package/src/tools/remember.ts +49 -0
  77. package/src/{schema.ts → tools/schema.ts} +3 -3
  78. package/src/tools/status-tool.ts +59 -0
  79. package/src/tools/undo.ts +57 -0
  80. package/src/tools/update.ts +342 -0
  81. package/src/{tui.tsx → tui/panel.tsx} +7 -17
  82. package/src/viewer/mutate.ts +15 -15
  83. package/src/viewer/server.ts +10 -8
  84. package/tui.ts +1 -1
  85. package/src/capture.ts +0 -222
  86. package/src/init.ts +0 -333
  87. package/src/inject.ts +0 -471
  88. package/src/memory.ts +0 -851
  89. package/src/portable.ts +0 -379
  90. package/src/status.ts +0 -536
  91. /package/src/{sessions.ts → core/lru.ts} +0 -0
  92. /package/src/{runtime.ts → core/runtime.ts} +0 -0
  93. /package/src/{tokenize.ts → core/tokenize.ts} +0 -0
  94. /package/src/{types.ts → core/types.ts} +0 -0
  95. /package/src/{host.ts → identity/host-events.ts} +0 -0
  96. /package/src/{repokey.ts → identity/repokey.ts} +0 -0
  97. /package/src/{containment.ts → store/containment.ts} +0 -0
  98. /package/src/{quarantine.ts → store/quarantine/quarantine.ts} +0 -0
  99. /package/src/{sanitize.ts → store/sanitize.ts} +0 -0
  100. /package/src/{secrets.ts → store/secrets.ts} +0 -0
package/src/status.ts DELETED
@@ -1,536 +0,0 @@
1
- // The status hand-off between the two surface halves. The server plugin writes
2
- // one status file per session on every epoch recompute AND every measured
3
- // assistant turn (src/index.ts); the terminal plugin (src/tui.tsx) and the
4
- // memory_status tool consume them. Status files are deliberately NOT .logfmt
5
- // memory files — loadAll() must never ingest them.
6
- //
7
- // Why per-session: the epoch freeze is per-session, so a single global
8
- // last-writer-wins file let one session's badge show another session's epoch.
9
- // `status/<sessionID>.json` is the primary read; the global `status.json`
10
- // survives as a "latest" fallback for argument-free reads. Both are pruned /
11
- // written best-effort: a status failure degrades surfaces, never injection.
12
- //
13
- // Scope of v2: same-machine reads. Against a REMOTE server the terminal panel
14
- // sees no status files (it says so) — the RPC surface is the planned follow-up.
15
- import { readFile, readdir, rm, stat } from "node:fs/promises";
16
- import { join } from "node:path";
17
- import { dateStr, evidenceDir, memoryRoot } from "./config.ts";
18
- import { parseLine, readLines } from "./logfmt.ts";
19
- import type { Attribution } from "./attribution.ts";
20
-
21
- export interface StoreCounts {
22
- active: number;
23
- superseded: number;
24
- open: number;
25
- scopes: number;
26
- /** Rows skipped as malformed by the most recent store read. */
27
- malformed: number;
28
- /**
29
- * Active rows the use ledger has never credited (or not inside the window).
30
- * Undefined until #42's ledger is read — an absent number, never a zero.
31
- */
32
- neverRetrieved?: number;
33
- /**
34
- * Oldest line in the use ledger, or null when it holds none. The 30-day
35
- * dead-weight number is only honest inside the ledger's coverage; a young
36
- * ledger says so instead of inflating "never" (see `ledgerIsYoung`).
37
- */
38
- ledgerSince?: string | null;
39
- /** Bytes of store the active rows occupy (canonical logfmt rendering). */
40
- bytes?: number;
41
- /** Per-row average of the same, the "what does a row cost" number. */
42
- bytesPerRow?: number;
43
- /** Rows created per day over the trailing window. */
44
- rowsPerDay?: number;
45
- /** Capture latency in ms, p50/p95, from `capture_lag` evidence. */
46
- captureLag?: { p50: number; p95: number; n: number };
47
- }
48
-
49
- /**
50
- * True when the ledger cannot honestly cover the 30-day window: its first
51
- * line is younger than the window, or there is no ledger at all. Every "never
52
- * retrieved" surface must carry this qualifier when it returns true.
53
- */
54
- export function ledgerIsYoung(ledgerSince: string | null | undefined, now = Date.now()): boolean {
55
- if (!ledgerSince) return true;
56
- return ledgerSince > new Date(now - 30 * 86_400_000).toISOString();
57
- }
58
-
59
- /** Human byte count, base 1024, one decimal above a kilobyte. */
60
- export function fmtBytes(n: number): string {
61
- if (n < 1024) return `${n} B`;
62
- if (n < 1024 * 1024) return `${Math.round(n / 102.4) / 10} KB`;
63
- return `${Math.round(n / (1024 * 102.4)) / 10} MB`;
64
- }
65
-
66
- /** Duration in the unit a reader actually parses: s / min / h. */
67
- export function fmtMs(ms: number): string {
68
- if (ms < 1000) return `${ms} ms`;
69
- if (ms < 60_000) return `${Math.round(ms / 100) / 10} s`;
70
- if (ms < 3_600_000) return `${Math.round(ms / 60_000)} min`;
71
- return `${Math.round(ms / 360_000) / 10} h`;
72
- }
73
-
74
- /** Percentile of an unsorted list, nearest-rank. Empty input has no answer. */
75
- export function percentile(values: number[], q: number): number | null {
76
- if (!values.length) return null;
77
- const sorted = [...values].sort((a, b) => a - b);
78
- const idx = Math.min(sorted.length - 1, Math.max(0, Math.ceil(q * sorted.length) - 1));
79
- return sorted[idx];
80
- }
81
-
82
- /** Rows created per day across `days`, counting only days the store saw activity. */
83
- export function rowsPerDay(rows: { ts: string }[], days = 30, now = Date.now()): number | null {
84
- if (!rows.length) return null;
85
- const cutoff = new Date(now - days * 86_400_000).toISOString().slice(0, 10);
86
- const inWindow = rows.filter((m) => m.ts.slice(0, 10) >= cutoff);
87
- if (!inWindow.length) return null;
88
- const dates = new Set(inWindow.map((m) => m.ts.slice(0, 10)));
89
- return Math.round((inWindow.length / dates.size) * 10) / 10;
90
- }
91
-
92
- /**
93
- * Capture latency from `capture_lag` evidence lines: how stale the newest
94
- * message was when the capture model was asked. Lag-less lines (a session with
95
- * no timestamped message) are counted in `n` only through their outcome, never
96
- * as a zero lag.
97
- */
98
- export function captureLag(lines: string[], days = 30, now = Date.now()): { p50: number; p95: number; n: number } {
99
- const cutoff = new Date(now - days * 86_400_000).toISOString();
100
- const lags: number[] = [];
101
- for (const line of lines) {
102
- const f = parseLine(line);
103
- if (!f || f.ev !== "capture_lag") continue;
104
- if (typeof f.ts === "string" && f.ts < cutoff) continue;
105
- const lag = Number(f.lag);
106
- if (Number.isFinite(lag) && lag >= 0) lags.push(lag);
107
- }
108
- const p50 = percentile(lags, 0.5);
109
- const p95 = percentile(lags, 0.95);
110
- return { p50: p50 ?? 0, p95: p95 ?? 0, n: lags.length };
111
- }
112
-
113
- /**
114
- * Per-session ledger, incremented at the session.context injection decision
115
- * (so counts match exactly what was injected — an aborted turn still rode the
116
- * bytes). Cumulative fields are session-lifetime; epochRequests resets when a
117
- * new epoch freezes. An invalidation = a store_changed recompute that moved a
118
- * live epoch (the first epoch of a session is not one).
119
- */
120
- export interface SessionStats {
121
- requests: number; // provider requests that injected through session.context
122
- abstained: number; // requests where the epoch block was empty
123
- cumChars: number; // lifetime sum of injected block chars
124
- epochRequests: number; // requests the CURRENT epoch block has ridden
125
- invalidations: number; // store_changed recomputes this session
126
- lastInvalidation: { at: string; reason: string } | null;
127
- }
128
-
129
- export function emptyStats(): SessionStats {
130
- return {
131
- requests: 0,
132
- abstained: 0,
133
- cumChars: 0,
134
- epochRequests: 0,
135
- invalidations: 0,
136
- lastInvalidation: null,
137
- };
138
- }
139
-
140
- /**
141
- * Measured prompt-cache usage from the last usage event — `session.usage.updated`
142
- * (v2 hosts) or `message.updated` assistant info (older hosts) — carrying tokens
143
- * {input, cache.read, cache.write}. This is the SESSION-WIDE prompt cache — the
144
- * honest receipt for "are we busting cache", never billed as our block's own rate.
145
- */
146
- export interface Measured {
147
- at: string;
148
- input: number;
149
- read: number;
150
- write: number;
151
- }
152
-
153
- export interface StatusPayload {
154
- /** ISO instant of the epoch recompute that produced this snapshot. */
155
- at: string;
156
- sessionID: string;
157
- reason: "first" | "store_changed";
158
- /** epoch recomputes since the server process started, ALL sessions. */
159
- recomputes: number;
160
- /** exact injected block ("" = abstained: no vocabulary overlap). */
161
- block: string;
162
- blockChars: number;
163
- /**
164
- * Every memory byte riding the system prompt: digest + frontier + block.
165
- * Optional for backward-compatible reads of status files written before the
166
- * distinction existed — the panel only prints it when present.
167
- */
168
- sectionChars?: number;
169
- budget: number;
170
- store: StoreCounts;
171
- /** optional for backward-compatible reads of pre-v2 files. */
172
- stats?: SessionStats;
173
- measured?: Measured | null;
174
- /** memory-vs-files attribution for the session; null/undefined = not computed. */
175
- attribution?: Attribution | null;
176
- }
177
-
178
- export interface BlockedRow {
179
- ts: string;
180
- sid: string;
181
- reason: string;
182
- }
183
-
184
- export function statusFile(): string {
185
- return join(memoryRoot(), "status.json");
186
- }
187
-
188
- export function statusDir(): string {
189
- return join(memoryRoot(), "status");
190
- }
191
-
192
- // Session ids are host-generated (ses_…), but sanitize anyway: this string
193
- // becomes a file name.
194
- function safeName(sessionID: string): string {
195
- return sessionID.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 80);
196
- }
197
-
198
- export function sessionStatusFile(sessionID: string): string {
199
- return join(statusDir(), `${safeName(sessionID)}.json`);
200
- }
201
-
202
- // LRU cap on per-session files: the badge only ever reads the active session,
203
- // so old ones are kept for post-hoc inspection up to this count, then pruned
204
- // by mtime (newest survive; a re-written session refreshes its mtime).
205
- const SESSION_FILE_CAP = 32;
206
-
207
- async function pruneStatusDir(): Promise<void> {
208
- try {
209
- const names = (await readdir(statusDir())).filter((n) => n.endsWith(".json"));
210
- if (names.length <= SESSION_FILE_CAP) return;
211
- const withMtime = await Promise.all(
212
- names.map(async (n) => {
213
- try {
214
- return { n, m: (await stat(join(statusDir(), n))).mtimeMs };
215
- } catch {
216
- return { n, m: 0 }; // vanished mid-prune or unstatable: prune first
217
- }
218
- }),
219
- );
220
- withMtime.sort((a, b) => b.m - a.m);
221
- for (const f of withMtime.slice(SESSION_FILE_CAP)) {
222
- await rm(join(statusDir(), f.n), { force: true });
223
- }
224
- } catch {
225
- // pruning is housekeeping; the surfaces tolerate a growing dir
226
- }
227
- }
228
-
229
- async function writeJson(path: string, p: StatusPayload): Promise<boolean> {
230
- try {
231
- await Bun.write(path, JSON.stringify(p, null, 2) + "\n");
232
- return true;
233
- } catch {
234
- return false; // swallow — surfaces degrade to "no data", the session does not
235
- }
236
- }
237
-
238
- // Best-effort by design: a status write must never break injection. Writes the
239
- // per-session file (primary) AND the global latest file (fallback).
240
- export async function writeStatus(p: StatusPayload): Promise<void> {
241
- await writeJson(statusFile(), p);
242
- if (typeof p.sessionID === "string" && p.sessionID) {
243
- await writeJson(sessionStatusFile(p.sessionID), p);
244
- await pruneStatusDir();
245
- }
246
- }
247
-
248
- async function readJson(path: string): Promise<StatusPayload | null> {
249
- try {
250
- const v: unknown = JSON.parse((await readFile(path, "utf8")).replace(/^\uFEFF/, ""));
251
- if (!v || typeof v !== "object") return null;
252
- const p = v as Partial<StatusPayload>;
253
- if (typeof p.at !== "string" || typeof p.block !== "string") return null;
254
- return p as StatusPayload;
255
- } catch {
256
- return null;
257
- }
258
- }
259
-
260
- /**
261
- * Read the status for a session. With a sessionID: ONLY that session's file —
262
- * a missing file returns null ("mem -") rather than another session's epoch.
263
- * Without one: the global latest file.
264
- */
265
- export async function readStatus(sessionID?: string): Promise<StatusPayload | null> {
266
- if (sessionID) return readJson(sessionStatusFile(sessionID));
267
- return readJson(statusFile());
268
- }
269
-
270
- // Newest-first last `limit` write_blocked evidence rows, scanning today and
271
- // yesterday so a block just before midnight stays visible.
272
- export async function blockedRecent(limit = 6): Promise<BlockedRow[]> {
273
- const today = dateStr();
274
- const yesterday = new Date(Date.now() - 86_400_000).toISOString().split("T")[0]!;
275
- const rows: BlockedRow[] = [];
276
- for (const day of [yesterday, today]) {
277
- for (const line of await readLines(join(evidenceDir(), `${day}.logfmt`))) {
278
- const f = parseLine(line);
279
- if (!f || f.ev !== "write_blocked") continue;
280
- rows.push({
281
- ts: String(f.ts ?? day),
282
- sid: String(f.sid ?? "?"),
283
- reason: String(f.reason ?? "?"),
284
- });
285
- }
286
- }
287
- return rows.slice(-limit).reverse();
288
- }
289
-
290
- /** `capture_lag` lines for the trailing window, newest evidence files first. */
291
- export async function captureLagLines(days = 30): Promise<string[]> {
292
- const dir = evidenceDir();
293
- const out: string[] = [];
294
- for (let d = 0; d < days; d++) {
295
- const day = new Date(Date.now() - d * 86_400_000).toISOString().split("T")[0]!;
296
- out.push(...(await readLines(join(dir, `${day}.logfmt`))));
297
- }
298
- return out;
299
- }
300
-
301
- function ago(iso: string): string {
302
- const ms = Date.now() - new Date(iso).getTime();
303
- if (!Number.isFinite(ms) || ms < 0) return "now";
304
- const m = Math.floor(ms / 60_000);
305
- if (m < 1) return "just now";
306
- if (m < 60) return `${m}m ago`;
307
- const h = Math.floor(m / 60);
308
- if (h < 24) return `${h}h ago`;
309
- return `${Math.floor(h / 24)}d ago`;
310
- }
311
-
312
- // --- shared formatting (the /memory panel and memory_status render 1:1) ------
313
-
314
- /** Char counts are exact; tokens are an estimate, chars/4, shown only with "≈". */
315
- export function estTok(chars: number): number {
316
- return Math.round(chars / 4);
317
- }
318
-
319
- /** 9999 -> "9999"; 10000 -> "10k"; 41234 -> "41.2k". */
320
- export function fmtCount(n: number): string {
321
- if (n < 10_000) return String(n);
322
- const k = n / 1000;
323
- return `${k >= 100 ? Math.round(k) : Math.round(k * 10) / 10}k`;
324
- }
325
-
326
- /** Session-wide prompt-cache hit rate from measured usage; null = nothing measured. */
327
- export function cacheRate(m?: Measured | null): { read: number; prompt: number; pct: number } | null {
328
- if (!m) return null;
329
- const prompt = (m.input || 0) + (m.read || 0) + (m.write || 0);
330
- if (prompt <= 0) return null;
331
- return { read: m.read || 0, prompt, pct: Math.round(((m.read || 0) / prompt) * 100) };
332
- }
333
-
334
- /**
335
- * Badge dot state: green = no invalidation since the last measured turn AND
336
- * last measured reads >= 90%; recent = the epoch moved after the last
337
- * measurement (a bust we have not yet seen re-warm); amber 50-89%; red < 50%;
338
- * unknown = nothing measured yet (NEVER show 0% for "no data").
339
- */
340
- export type CacheHealth = "green" | "recent" | "amber" | "red" | "unknown";
341
-
342
- export function cacheHealth(p: StatusPayload): CacheHealth {
343
- const inv = p.stats?.lastInvalidation?.at;
344
- if (inv && (!p.measured || inv > p.measured.at)) return "recent";
345
- const rate = cacheRate(p.measured);
346
- if (!rate) return "unknown";
347
- if (rate.pct >= 90) return "green";
348
- if (rate.pct >= 50) return "amber";
349
- return "red";
350
- }
351
-
352
- export function contextLines(p: StatusPayload): string[] {
353
- const st = p.stats ?? emptyStats();
354
- const pct = p.budget > 0 ? Math.round((p.blockChars / p.budget) * 100) : 0;
355
- return [
356
- ` injected now ${p.blockChars}c ≈ ${estTok(p.blockChars)} tok · ${pct}% of ${p.budget}c budget`,
357
- // The budget caps the RELEVANCE BLOCK; the standing digest and the frontier
358
- // ride the system prompt too. Quoting only the budgeted slice would
359
- // understate what the request actually carries.
360
- ...(p.sectionChars === undefined
361
- ? []
362
- : [
363
- ` memory section ${p.sectionChars}c ≈ ${estTok(p.sectionChars)} tok riding the prompt` +
364
- ` (digest + frontier + the ${p.blockChars}c block above)`,
365
- ]),
366
- ` this epoch ${p.reason} epoch since ${p.at} (${ago(p.at)}) · rode ${st.epochRequests} request(s)`,
367
- ` session ${st.requests} request(s) · ${fmtCount(st.cumChars)}c ≈ ${fmtCount(estTok(st.cumChars))} tok rode · abstained ${st.abstained}`,
368
- ];
369
- }
370
-
371
- export function cacheLines(p: StatusPayload): string[] {
372
- const st = p.stats ?? emptyStats();
373
- const inv =
374
- st.invalidations === 0
375
- ? [
376
- " cache busts 0 — memory has never rewritten a byte of your past",
377
- " conversation, so the provider can serve history from cache",
378
- ]
379
- : [
380
- ` cache busts ${st.invalidations} this session · last ${
381
- st.lastInvalidation ? `${st.lastInvalidation.at.slice(11, 19)} (${st.lastInvalidation.reason})` : "-"
382
- }`,
383
- " a memory YOU saved in this session never costs one — you",
384
- " already said it (#165). A correction, a removal, or a row",
385
- " another session wrote costs exactly one, and the prefix",
386
- " re-warms on the following turn",
387
- ];
388
- const rate = cacheRate(p.measured);
389
- const receipts = rate
390
- ? [
391
- ` receipts ${fmtCount(rate.read)}/${fmtCount(rate.prompt)} prompt tok served from cache (${rate.pct}%)`,
392
- rate.pct >= 90
393
- ? " — memory is cache-invisible: the same bytes ride every turn"
394
- : " — below ~90% something re-bills the whole history each turn",
395
- ]
396
- : [
397
- " receipts provider reports no cache usage yet — structural proof:",
398
- ` the same block bytes rode ${st.epochRequests} request(s) with ${st.invalidations} busts`,
399
- ];
400
- return [
401
- ...inv,
402
- ...receipts,
403
- ` recomputes ${p.recomputes} block builds since server start (all sessions)`,
404
- ];
405
- }
406
-
407
- /**
408
- * CONTEXT WINDOW — the "is memory bloating my context?" answer, built ONLY from
409
- * numbers we trust: the exact injected block (we wrote those bytes), the
410
- * provider's own cache receipts, and the memory-caused bust count. No estimated
411
- * decomposition of the system prompt or history (we cannot measure those); the
412
- * one honest share we can state is memory as a slice of what was actually sent.
413
- */
414
- export function windowLines(p: StatusPayload): string[] {
415
- const memTok = estTok(p.blockChars);
416
- const pct = p.budget > 0 ? Math.round((p.blockChars / p.budget) * 100) : 0;
417
- const out: string[] = [
418
- ` memory slice ${p.blockChars}c ≈ ${memTok} tok · ${pct}% of the ${p.budget}c inject budget (hard-capped by design)`,
419
- ];
420
- const m = p.measured;
421
- const used = m ? (m.input || 0) + (m.read || 0) + (m.write || 0) : 0;
422
- if (used > 0) {
423
- const share = Math.round((memTok / used) * 1000) / 10;
424
- const rate = cacheRate(m);
425
- out.push(` of what you sent ≈ ${fmtCount(used)} prompt tok · memory is ${share}% of it`);
426
- out.push(
427
- rate
428
- ? ` cache served ${rate.pct}% of that prompt from cache → memory rides free after turn 1`
429
- : " cache served provider has not reported a split yet",
430
- );
431
- } else {
432
- out.push(" of what you sent not measured yet — receipts appear after the first assistant turn");
433
- }
434
- const busts = p.stats?.invalidations ?? 0;
435
- out.push(
436
- ` memory busts ${busts} this session${busts ? "" : " — memory never invalidated your cache prefix"}`,
437
- );
438
- return out;
439
- }
440
-
441
- /**
442
- * MEMORY ATTRIBUTION — which answers came from memory instead of re-reading
443
- * files. Every line is labeled [measured] (an observed tool-call fact) or
444
- * [inferred] (a coverage statement). Misses are shown alongside saves so the
445
- * panel reads as an audit, not marketing.
446
- */
447
- export function attributionLines(p: StatusPayload): string[] {
448
- const a = p.attribution;
449
- if (!a) return [" not computed — no memory was injected this session"];
450
- if (a.pathsCited === 0 && a.commandsMatched === 0 && a.readsTotal === 0) {
451
- return [" the injected memory cited no file paths or commands yet — nothing to attribute"];
452
- }
453
- return [
454
- ` Tier A · commands ${a.commandSaves} lookup(s) avoided [measured] · ran a remembered command with no prior file lookup`,
455
- ` Tier B · coverage cited ${a.pathsCited} · re-read ${a.pathsReRead} [measured] · not opened ${a.pathsSkipped} [inferred]`,
456
- ` new work ${a.readsNotCovered}/${a.readsTotal} file lookups had no memory coverage [measured]`,
457
- ];
458
- }
459
-
460
- /**
461
- * Plain-text rendering shared by the memory_status tool (and any other chat
462
- * client). Sections match the terminal /memory panel one-for-one.
463
- */
464
- export function renderMemoryReport(input: {
465
- status: StatusPayload | null;
466
- store: StoreCounts;
467
- blocked: BlockedRow[];
468
- quarantined?: { ts: string; patterns: string[] }[];
469
- }): string {
470
- const { status, store, blocked } = input;
471
- const out: string[] = ["MEMORY STATUS", ""];
472
- if (input.quarantined?.length) {
473
- out.push("QUARANTINE", ` ${input.quarantined.length} rows withheld from recall and injection; review/release in the memory viewer.`);
474
- for (const row of input.quarantined.slice(0, 20)) {
475
- out.push(` ${row.ts} ${row.patterns.join(", ") || "marked for review"}`);
476
- }
477
- out.push("");
478
- }
479
-
480
- if (!status) {
481
- out.push(
482
- "CONTEXT",
483
- " no epoch yet — memory has not injected this session (fresh server, or no prompt scored yet)",
484
- );
485
- } else {
486
- out.push("CONTEXT", ...contextLines(status));
487
- out.push("", "CACHE — the receipts on your prompt-cache cost", ...cacheLines(status));
488
- out.push("", "CONTEXT WINDOW — is memory bloating your context?", ...windowLines(status));
489
- out.push("", "INJECTED BLOCK (verbatim)");
490
- if (status.block) out.push(...status.block.split("\n").map((l) => ` ${l}`));
491
- else
492
- out.push(
493
- " abstained — your prompt shares no content vocabulary with any memory, so nothing was injected (by design, no noise).",
494
- );
495
- out.push("", "MEMORY ATTRIBUTION — answered from memory vs re-reading files", ...attributionLines(status));
496
- }
497
-
498
- out.push("", "RECENT BLOCKED WRITES");
499
- if (!blocked.length) out.push(" (none today or yesterday)");
500
- for (const b of blocked) {
501
- out.push(` ${b.ts} session ${b.sid} ${b.reason}`);
502
- }
503
- out.push(" (reasons are logged via memory_evidence; the gate never deletes — it asks for a rephrase)");
504
-
505
- out.push(
506
- "",
507
- "STORE",
508
- ` ${store.active} active · ${store.superseded} superseded · ${store.open} open · ${store.scopes} scopes` +
509
- (store.malformed ? ` · ${store.malformed} malformed (skipped; fix the ts= field or undo)` : ""),
510
- );
511
- if (store.neverRetrieved !== undefined) {
512
- const used = store.active - store.neverRetrieved;
513
- const share = store.active ? Math.round((store.neverRetrieved / store.active) * 100) : 0;
514
- // A ledger younger than the window cannot honestly call anything "never"
515
- // — it has not been watching long enough. Say what it covers instead of
516
- // letting day-one readers see 100% dead weight.
517
- const young = ledgerIsYoung(store.ledgerSince);
518
- const basis = young
519
- ? `, ledger only covers since ${store.ledgerSince ? store.ledgerSince.slice(0, 10) : "no lines yet"}`
520
- : "";
521
- out.push(
522
- ` retrieved ${used} rows in the last 30d; never retrieved ${store.neverRetrieved} (${share}%)${basis} — reported, not acted on`,
523
- );
524
- }
525
- const sizing: string[] = [];
526
- if (store.bytes !== undefined) {
527
- sizing.push(`${fmtBytes(store.bytes)} total · ${fmtBytes(store.bytesPerRow ?? 0)} per row`);
528
- }
529
- if (store.rowsPerDay !== undefined) sizing.push(`${store.rowsPerDay} rows/day (30d)`);
530
- if (store.captureLag && store.captureLag.n) {
531
- sizing.push(`capture lag p50 ${fmtMs(store.captureLag.p50)} / p95 ${fmtMs(store.captureLag.p95)}`);
532
- }
533
- if (sizing.length) out.push(` ${sizing.join(" · ")}`);
534
- out.push("", "Terminal (CLI/TUI) users: /memory opens this as a live panel; the footer shows a one-line badge.");
535
- return out.join("\n");
536
- }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes