opencode-self-improvement 0.10.0 → 0.12.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
@@ -206,6 +206,40 @@ What the benchmark bought us:
206
206
  Full methodology, all store sizes: `bench/recall-results.md`
207
207
  (regenerate with `bun bench:recall`).
208
208
 
209
+ ## The store keeps score of itself
210
+
211
+ Retrieval quality is a claim unless the store can show its receipts, so the
212
+ plugin keeps a **use ledger** (`<memory-root>/hits.logfmt`, append-only, rotated
213
+ at 512 KB, never ingested as a memory) and reports four numbers in
214
+ `memory_status` and the `/memory` panel:
215
+
216
+ ```
217
+ STORE
218
+ 41 active · 12 superseded · 4 open · 6 scopes
219
+ retrieved 33 rows in the last 30d; never retrieved 8 (20%) — reported, not acted on
220
+ 24.1 KB total · 604 B per row · 1.3 rows/day (30d) · capture lag p50 42 s / p95 6 min
221
+ ```
222
+
223
+ - **Which memories were actually used.** A row is credited when it *rode the
224
+ injected block*, when `memory_recall` returned it, or when a grep/read pull
225
+ appended it — three sources, kept distinct, because "the model asked" and "the
226
+ harness offered" are different facts. Credit needs ≥2 shared terms with the
227
+ query, the same bar as scoring, and it is throttled to one line per memory per
228
+ session per source per hour so a retry storm cannot fake frequency.
229
+ - **Nothing about you is in it.** The ledger stores a scan-truncated string from
230
+ the *memory* side, never your message. Grep it: your prompts are not there.
231
+ - **Reinforcement is a tie-break, never a verdict.** A recently used row wins a
232
+ tie; it can never outrank a real score gap (`useBoost ≤ 1.0`). Consolidation
233
+ respects the same rule — the most recently used row in a cluster is never the
234
+ merge loser.
235
+ - **Dead weight is stated, not deleted.** `never retrieved` is evidence about a
236
+ store that may need pruning, and pruning is a decision you make. Retired rows
237
+ cannot inherit reinforcement either: ledger rows are verified against the
238
+ store on read, so a resurrected identity earns nothing from its past life.
239
+ - **Capture lag** is how stale the newest message was when auto-capture fired.
240
+ Sessions idle for an hour produce an hour-old capture; now you can see it
241
+ instead of guessing.
242
+
209
243
  ## Quick start
210
244
 
211
245
  1. Add the plugin to your Opencode config (see install below) and restart Opencode.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.10.0",
3
+ "version": "0.12.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": {
package/src/capture.ts CHANGED
@@ -168,6 +168,22 @@ export function parseModelRef(ref: unknown): { providerID: string; id: string }
168
168
  // only); capped at 40 user turns. Never throws.
169
169
  const TRANSCRIPT_USER_TURN_CAP = 40;
170
170
 
171
+ /**
172
+ * Age of the newest message in a session context, in ms, or null when no
173
+ * message carries a timestamp. Capture uses this to say how stale a transcript
174
+ * was at the moment the model was asked for candidates (#44).
175
+ */
176
+ export function lagSince(messages: unknown, now = Date.now()): number | null {
177
+ let newest = 0;
178
+ for (const raw of Array.isArray(messages) ? messages : []) {
179
+ const m = raw as Record<string, any>;
180
+ const at = m?.time?.updated ?? m?.createdAt ?? m?.created ?? m?.timestamp;
181
+ const ms = typeof at === "number" ? at : typeof at === "string" ? Date.parse(at) : Number.NaN;
182
+ if (Number.isFinite(ms) && ms > newest) newest = ms;
183
+ }
184
+ return newest ? now - newest : null;
185
+ }
186
+
171
187
  export function flattenTranscript(msgs: unknown): string {
172
188
  try {
173
189
  if (!Array.isArray(msgs)) return "";
package/src/config.ts CHANGED
@@ -33,6 +33,10 @@ export function canonicalFile(): string {
33
33
  return join(memoryRoot(), "canonical.logfmt");
34
34
  }
35
35
 
36
+ // The use ledger (src/hits.ts). Lives in the store root beside the day files
37
+ // but is NOT a memory file: memory.ts's RESERVED set keeps it out of loadAll().
38
+ export const HITS_FILENAME = "hits.logfmt";
39
+
36
40
  export function deletionsFile(): string {
37
41
  return join(memoryRoot(), "deletions.logfmt");
38
42
  }
package/src/evidence.ts CHANGED
@@ -35,6 +35,29 @@ export function chainId(): string {
35
35
  .slice(0, 8);
36
36
  }
37
37
 
38
+ /**
39
+ * One capture decision, in both directions. `lagMs` is the wall-clock distance
40
+ * from the last message of the transcript to the moment the capture model was
41
+ * asked — the number #44 asks for ("how stale is a capture?"). Negative and
42
+ * missing values are dropped rather than guessed: a capture with no observed
43
+ * message time has no lag, and inventing 0 would pull p50 toward "instant".
44
+ */
45
+ export async function recordCaptureLag(
46
+ session: string,
47
+ lagMs: number | null,
48
+ outcome: string,
49
+ ): Promise<void> {
50
+ await record(
51
+ "capture_lag",
52
+ {
53
+ session,
54
+ ...(lagMs !== null && Number.isFinite(lagMs) && lagMs >= 0 ? { lag: Math.round(lagMs) } : {}),
55
+ outcome,
56
+ },
57
+ false,
58
+ );
59
+ }
60
+
38
61
  export async function recordWriteBlocked(
39
62
  gate: number,
40
63
  reason: string,
package/src/hits.ts ADDED
@@ -0,0 +1,213 @@
1
+ // The use ledger (#42). Decay, consolidation and the status surfaces all act
2
+ // on memories today with no idea whether anybody ever reads them — the store
3
+ // knows what was written and nothing about what was used. This module closes
4
+ // that loop with one append-only logfmt file.
5
+ //
6
+ // What a "use" is, deliberately narrow:
7
+ // inject — the rows that actually survived into an epoch block (offered to
8
+ // the model on every request of that epoch);
9
+ // pull — rows appended to a grep/glob/read result by the contextual pull;
10
+ // recall — rows returned by a memory_recall call.
11
+ //
12
+ // What it is NOT: evidence is a different file and a different contract. This
13
+ // ledger is DATA, never injected (I3 holds), never a memory row (hits.logfmt
14
+ // is in memory.ts's RESERVED set so loadAll() cannot ingest it), and it logs no
15
+ // prompt text — only the tokens a row and the query shared, each of which
16
+ // already exists inside that row.
17
+ import { join } from "node:path";
18
+ import { memoryRoot, HITS_FILENAME } from "./config.ts";
19
+ import { appendLog, bracketList, formatLine, parseLine, readLines, writeAtomic } from "./logfmt.ts";
20
+ import type { UseSignals } from "./inject.ts";
21
+ import { withStoreLock, LOCK_WRITE } from "./lock.ts";
22
+ import type { Memory } from "./memory.ts";
23
+
24
+ export type HitSource = "inject" | "pull" | "recall";
25
+
26
+ export { HITS_FILENAME };
27
+
28
+ // The ledger is a bounded ring, not a growing file: one line per (source,
29
+ // session, row-set) per THROTTLE_MS, and at MAX_HITS_BYTES the older half is
30
+ // dropped whole-line. Use data older than the window is not interesting — a
31
+ // memory unused since before the window is the finding, not the record. The
32
+ // size is sized for the hour throttle (worst case ~200 B/line × 24 h × dozens
33
+ // of row-sets covering the 30-day dead-weight window for ordinary traffic);
34
+ // when it is shorter than the window, the surfaces say so with the ledger's
35
+ // own first line rather than inflating "never" (status.ledgerSince).
36
+ const MAX_HITS_BYTES = 2_000_000;
37
+ export const THROTTLE_MS = 3_600_000;
38
+ const MAX_LOGGED_TERMS = 8;
39
+
40
+ export function hitsFile(): string {
41
+ return join(memoryRoot(), HITS_FILENAME);
42
+ }
43
+
44
+ export interface HitEntry {
45
+ ts: string;
46
+ src: HitSource;
47
+ sid: string;
48
+ mems: string[];
49
+ terms: string[];
50
+ }
51
+
52
+ // --- writing --------------------------------------------------------------------
53
+
54
+ // key -> ms of the last line actually written. The epoch block rides EVERY
55
+ // request of an epoch, so without this one "offer" would be counted dozens of
56
+ // times and the dead-weight number would be fiction.
57
+ const lastWrite = new Map<string, number>();
58
+
59
+ /** Clear the throttle window (tests; also what a process restart does). */
60
+ export function resetHitThrottle(): void {
61
+ lastWrite.clear();
62
+ }
63
+
64
+ async function rotateIfNeeded(): Promise<void> {
65
+ const file = Bun.file(hitsFile());
66
+ const size = await file.size;
67
+ if (size <= MAX_HITS_BYTES) return;
68
+ const lines = (await file.text()).split("\n").filter((l) => l.trim());
69
+ await writeAtomic(hitsFile(), lines.slice(Math.floor(lines.length / 2)).join("\n") + "\n");
70
+ }
71
+
72
+ /**
73
+ * Record one use of a set of rows. Throttled per (source, session, row-set),
74
+ * fail-soft: the ledger is telemetry, so a write failure must never break the
75
+ * read path that noticed it.
76
+ *
77
+ * `terms` are the tokens the query and these rows shared (never the query
78
+ * itself), capped and pre-sanitised by sharedTerms() in src/inject.ts. They
79
+ * exist so #45 can ask "if we merge these rows, do the same reads still
80
+ * land?" — a question no use log without them can answer.
81
+ */
82
+ export async function recordHits(
83
+ source: HitSource,
84
+ sid: string,
85
+ rows: Memory[],
86
+ terms: string[] = [],
87
+ now = Date.now(),
88
+ ): Promise<boolean> {
89
+ if (!rows.length) return false;
90
+ const ids = rows.map((m) => m.ts);
91
+ const key = `${source}|${sid}|${ids.join(",")}`;
92
+ const prev = lastWrite.get(key);
93
+ if (prev !== undefined && now - prev < THROTTLE_MS) return false;
94
+ lastWrite.set(key, now);
95
+ // Bound the throttle map: sessions churn, and a long-lived server must not
96
+ // grow one entry per row-set forever. Oldest-inserted entries go first.
97
+ if (lastWrite.size > 2000) {
98
+ for (const k of [...lastWrite.keys()].slice(0, 1000)) lastWrite.delete(k);
99
+ }
100
+ const line = formatLine({
101
+ ev: "memory_used",
102
+ ts: new Date(now).toISOString(),
103
+ src: source,
104
+ sid,
105
+ mem: bracketList(ids),
106
+ ...(terms.length ? { terms: bracketList(terms.slice(0, MAX_LOGGED_TERMS)) } : {}),
107
+ });
108
+ try {
109
+ await withStoreLock(
110
+ hitsFile(),
111
+ async () => {
112
+ await rotateIfNeeded();
113
+ await appendLog(hitsFile(), line);
114
+ },
115
+ LOCK_WRITE,
116
+ );
117
+ return true;
118
+ } catch {
119
+ return false; // telemetry never breaks retrieval
120
+ }
121
+ }
122
+
123
+ // --- reading --------------------------------------------------------------------
124
+
125
+ export interface UseSignal {
126
+ count: number;
127
+ last: string; // newest hit ts
128
+ terms: string[];
129
+ }
130
+
131
+ export interface UseLedger {
132
+ /** row ts -> what the ledger knows about it. */
133
+ byRow: Map<string, UseSignal>;
134
+ /** oldest line in the ledger — "never retrieved" is only true since this. */
135
+ since: string | null;
136
+ lines: number;
137
+ }
138
+
139
+ /** Read the whole ledger. Cheap by construction: it is a bounded ring. */
140
+ export async function readLedger(): Promise<UseLedger> {
141
+ const byRow = new Map<string, UseSignal>();
142
+ let since: string | null = null;
143
+ let lines = 0;
144
+ for (const line of await readLines(hitsFile())) {
145
+ const f = parseLine(line);
146
+ if (!f || f.ev !== "memory_used") continue;
147
+ lines++;
148
+ const ts = typeof f.ts === "string" ? f.ts : "";
149
+ if (ts && (!since || ts < since)) since = ts;
150
+ const mem = typeof f.mem === "string" ? parseList(f.mem) : [];
151
+ const terms = typeof f.terms === "string" ? parseList(f.terms) : [];
152
+ for (const row of mem) {
153
+ const cur = byRow.get(row);
154
+ if (!cur) byRow.set(row, { count: 1, last: ts, terms: [...terms] });
155
+ else {
156
+ cur.count++;
157
+ if (ts > cur.last) cur.last = ts;
158
+ for (const t of terms) if (!cur.terms.includes(t)) cur.terms.push(t);
159
+ }
160
+ }
161
+ }
162
+ return { byRow, since, lines };
163
+ }
164
+
165
+ function parseList(value: string): string[] {
166
+ return value
167
+ .replace(/^\[|\]$/g, "")
168
+ .split(",")
169
+ .map((s) => s.trim())
170
+ .filter(Boolean);
171
+ }
172
+
173
+ /** Rows the ledger has NEVER seen used, plus the honest since-qualifier. */
174
+ export function neverRetrieved(rows: Memory[], ledger: UseLedger, days = 30): Memory[] {
175
+ const cutoff = new Date(Date.now() - days * 86_400_000).toISOString();
176
+ return rows.filter((m) => {
177
+ const u = ledger.byRow.get(m.ts);
178
+ return !u || u.last < cutoff;
179
+ });
180
+ }
181
+
182
+ /** Active rows used at least once inside the window. */
183
+ export function usedRecently(rows: Memory[], ledger: UseLedger, days = 30): number {
184
+ const cutoff = new Date(Date.now() - days * 86_400_000).toISOString();
185
+ return rows.filter((m) => {
186
+ const u = ledger.byRow.get(m.ts);
187
+ return !!u && u.last >= cutoff;
188
+ }).length;
189
+ }
190
+
191
+ // --- cached view for the read path -------------------------------------------------
192
+ // A contextual pull runs on every grep/glob/read, so the ledger is read at most
193
+ // once per LEDGER_TTL_MS. Ranking may therefore lag a write by one TTL — the
194
+ // epoch only re-scores when the store changes anyway, so this never costs a
195
+ // prompt-cache bust, and reinforcement is a tie-break, not a guarantee.
196
+
197
+ const LEDGER_TTL_MS = 60_000;
198
+ let ledgerCache: { at: number; ledger: UseLedger } | null = null;
199
+
200
+ export async function useSignals(ttlMs = LEDGER_TTL_MS, now = Date.now()): Promise<UseSignals> {
201
+ if (!ledgerCache || now - ledgerCache.at > ttlMs) {
202
+ ledgerCache = { at: now, ledger: await readLedger() };
203
+ }
204
+ return ledgerCache.ledger.byRow;
205
+ }
206
+
207
+ /** Drop the cached ledger (tests). There is no write hook: between resets the
208
+ * cache simply expires after `ttlMs`, so ranking can lag a new hit by up to
209
+ * one TTL — fine for a tie-break, and it keeps a pull from re-reading the
210
+ * ring on every grep/glob/read. */
211
+ export function resetLedgerCache(): void {
212
+ ledgerCache = null;
213
+ }
package/src/index.ts CHANGED
@@ -30,18 +30,21 @@ import { pruneMemory } from "./prune.ts";
30
30
  import { exportMemories, findStaleOpen, importMemories } from "./portable.ts";
31
31
  import { listSnapshots, restoreSnapshot } from "./undo.ts";
32
32
  import { SESSION_CAP, SessionLru } from "./sessions.ts";
33
- import { record } from "./evidence.ts";
33
+ import { record, recordCaptureLag } from "./evidence.ts";
34
34
  import {
35
35
  capToBudget,
36
36
  compactionAnchor,
37
37
  contextualPull,
38
38
  formatMemory,
39
39
  injectedRows,
40
+ pullQuery,
40
41
  selectRelevant,
42
+ sharedTerms,
41
43
  storeVersion,
42
44
  systemDigest,
43
45
  } from "./inject.ts";
44
46
  import { attributeSession, deriveMemoryRefs, type MemoryRefs } from "./attribution.ts";
47
+ import { readLedger, neverRetrieved, recordHits, useSignals, type HitSource } from "./hits.ts";
45
48
  import { formatInit, runInit } from "./init.ts";
46
49
  import { ensureInitCommand, ensureMemoryReportCommand } from "./command.ts";
47
50
  import {
@@ -51,7 +54,11 @@ import {
51
54
  writeStatus,
52
55
  type Measured,
53
56
  type SessionStats,
57
+ captureLag,
58
+ captureLagLines,
59
+ rowsPerDay,
54
60
  type StatusPayload,
61
+ type StoreCounts,
55
62
  } from "./status.ts";
56
63
  import {
57
64
  afterTool,
@@ -68,7 +75,7 @@ import {
68
75
  import { getCurrent, setCurrent } from "./state.ts";
69
76
  import { resolveRepo, setRepoScope, rememberSessionDir, sessionDir } from "./repokey.ts";
70
77
  import { readLines } from "./logfmt.ts";
71
- import { buildCapturePrompt, flattenTranscript, parseCandidates, parseModelRef } from "./capture.ts";
78
+ import { buildCapturePrompt, flattenTranscript, lagSince, parseCandidates, parseModelRef } from "./capture.ts";
72
79
  import { redactSecrets } from "./secrets.ts";
73
80
  import { flattenMemoryText } from "./sanitize.ts";
74
81
  import { bunFloorWarning } from "./runtime.ts";
@@ -368,6 +375,7 @@ const impl = {
368
375
  turn: firstFrontierTap(cur.sid)?.turn,
369
376
  });
370
377
  }
378
+ if (args.query) await noteHits("recall", getCurrent().sid, limited, args.query);
371
379
  return { content: `Found ${results.length} (${total} total)\n\n${limited.map(formatMemory).join("\n")}` };
372
380
  },
373
381
  }));
@@ -648,13 +656,25 @@ const impl = {
648
656
  const status = sid === "?" ? null : await buildPayload(sid);
649
657
  const all = await loadAll();
650
658
  const act = all.filter(isActive);
651
- const store = {
659
+ const store: StoreCounts = {
652
660
  active: act.length,
653
661
  superseded: all.length - act.length,
654
662
  open: act.filter((m) => m.status === "open").length,
655
663
  scopes: new Set(act.map((m) => m.scope)).size,
656
664
  malformed: malformedCount(),
657
665
  };
666
+ // Use ledger (#42): how much of the store has never been surfaced.
667
+ // Reported, never acted on — retirement is a decision, not a metric.
668
+ const ledger = await readLedger();
669
+ store.neverRetrieved = neverRetrieved(act, ledger).length;
670
+ store.ledgerSince = ledger.since;
671
+ // Self-metrics (#44): what the store costs, how fast it grows, and how
672
+ // stale a capture is when it fires. Same rule as above — the numbers
673
+ // are the point, not a verdict on them.
674
+ store.bytes = act.reduce((n, m) => n + new TextEncoder().encode(formatMemory(m)).length, 0);
675
+ store.bytesPerRow = act.length ? Math.round(store.bytes / act.length) : 0;
676
+ store.rowsPerDay = rowsPerDay(act) ?? undefined;
677
+ store.captureLag = captureLag(await captureLagLines());
658
678
  return {
659
679
  content: renderMemoryReport({ status, store, blocked: await blockedRecent(6) }),
660
680
  };
@@ -709,6 +729,7 @@ const impl = {
709
729
  if (!ep) return null;
710
730
  const all = await loadAll();
711
731
  const act = all.filter(isActive);
732
+ const led = await readLedger();
712
733
  return {
713
734
  at: ep.at,
714
735
  sessionID: sid,
@@ -723,6 +744,8 @@ const impl = {
723
744
  open: act.filter((m) => m.status === "open").length,
724
745
  scopes: new Set(act.map((m) => m.scope)).size,
725
746
  malformed: malformedCount(),
747
+ neverRetrieved: neverRetrieved(act, led).length,
748
+ ledgerSince: led.since,
726
749
  },
727
750
  stats: statsFor(sid),
728
751
  measured: measuredTurns.get(sid) ?? null,
@@ -738,18 +761,33 @@ const impl = {
738
761
  // loop cannot ride one more request waiting for another user prompt.
739
762
  const injectableRows = async (): Promise<Memory[]> =>
740
763
  (await loadAll()).filter((m) => isActive(m) && isVisibleHere(m));
764
+ // Use ledger (#42). `query` is what retrieval was asked with; what gets
765
+ // stored is the vocabulary the answer SHARES with the query, taken from the
766
+ // memory side, so the ledger can never become a copy of user prompts.
767
+ // Fail-soft inside recordHits: telemetry must not break a read path.
768
+ const noteHits = async (src: HitSource, sid: string, rows: Memory[], query: string): Promise<void> => {
769
+ if (!rows.length || !query.trim()) return;
770
+ const terms: string[] = [];
771
+ for (const m of rows) for (const t of sharedTerms(query, m)) if (!terms.includes(t)) terms.push(t);
772
+ await recordHits(src, sid, rows, terms);
773
+ };
741
774
  const refreshEpoch = async (sid: string, rows?: Memory[]): Promise<void> => {
742
775
  if (!latestPrompt.has(sid)) return;
743
776
  const mems = rows ?? await injectableRows();
744
777
  const version = await storeVersion(mems);
745
778
  const cached = epoch.get(sid);
746
779
  if (cached?.version === version) return;
747
- const sel = await selectRelevant(latestPrompt.get(sid) ?? "", 5, mems); // widen candidate pool
780
+ const prompt = latestPrompt.get(sid) ?? "";
781
+ const sel = await selectRelevant(prompt, 5, mems, await useSignals()); // widen candidate pool
748
782
  const block = sel.block ? capToBudget(sel.block, budget) : "";
749
783
  // Refs the ACTUALLY-injected rows assert (paths + commands), the join key
750
784
  // for attribution. Derived from the budget-surviving rows, not the wider
751
785
  // candidate pool — crediting paths the model never saw would overclaim.
752
- const refs = deriveMemoryRefs(injectedRows(block, sel.selected));
786
+ const rode = injectedRows(block, sel.selected);
787
+ const refs = deriveMemoryRefs(rode);
788
+ // Use ledger (#42): the rows that actually rode the block, credited with
789
+ // the terms the prompt and those rows shared (never the prompt itself).
790
+ await noteHits("inject", sid, rode, prompt);
753
791
  const at = new Date().toISOString();
754
792
  const reason: "first" | "store_changed" = cached ? "store_changed" : "first";
755
793
  epoch.set(sid, { version, block, at, reason, refs });
@@ -800,7 +838,8 @@ const impl = {
800
838
  setCurrent(input);
801
839
  const out = { output: resultText(event?.result), metadata: resultMeta(event?.result) };
802
840
  await afterTool(input, out);
803
- await contextualPull(input, out as { output?: unknown }, budget);
841
+ const pulled = await contextualPull(input, out as { output?: unknown }, budget, await useSignals());
842
+ if (pulled.length) await noteHits("pull", String(event?.sessionID ?? ""), pulled, pullQuery(input.args));
804
843
  // Write a contextual-pull append back when the tool result is text we own.
805
844
  if (event?.result && typeof event.result === "object" && typeof event.result.content === "string") {
806
845
  const text = resultText(event.result);
@@ -1008,12 +1047,17 @@ const impl = {
1008
1047
  const msgs = await contextFn({ sessionID: sid });
1009
1048
  const transcript = flattenTranscript(msgs);
1010
1049
  if (transcript.length < 200) continue; // too thin to mine reliably
1050
+ // #44: how stale is a capture? Distance from the last message of
1051
+ // the transcript to this instant. Sessions idle for an hour
1052
+ // produce an hour-old capture, and the surfaces now say so.
1053
+ const lagMs = lagSince(msgs);
1011
1054
  const out = await generateApi.text({
1012
1055
  model: modelRef,
1013
1056
  prompt: buildCapturePrompt(transcript.slice(-8000), captureMax),
1014
1057
  });
1015
1058
  const text = typeof out === "string" ? out : out?.text ?? "";
1016
- for (const c of parseCandidates(text, captureMax)) {
1059
+ const candidates = parseCandidates(text, captureMax);
1060
+ for (const c of candidates) {
1017
1061
  const outcome = await runWriteGate(
1018
1062
  { ...c, tags: ["auto-capture"] },
1019
1063
  gateContext(),
@@ -1025,6 +1069,7 @@ const impl = {
1025
1069
  false,
1026
1070
  );
1027
1071
  }
1072
+ await recordCaptureLag(sid, lagMs, candidates.length ? "candidates" : "empty");
1028
1073
  } catch {
1029
1074
  // fail-closed: a broken capture attempt is invisible to the session
1030
1075
  }
package/src/inject.ts CHANGED
@@ -104,9 +104,10 @@ const LONG_QUERY_TOKENS = 3;
104
104
  // piles of common ones — the same idf form the bench's BM25 row uses).
105
105
  // Ties break deliberately, in this order: open threads first (a pinned frontier
106
106
  // row beats an equal-scoring settled one — that is what the frontier is for),
107
- // then the newer row (#40 item 2: between two equally relevant facts, the one
108
- // stating what is true NOW is the better guess; epoch-freeze-safe because ts
109
- // never changes for a given row).
107
+ // then rows the use ledger has actually retrieved, most-recently-used first
108
+ // (#42 reinforcement), then the newer row (#40 item 2: between two equally
109
+ // relevant facts, the one stating what is true NOW is the better guess;
110
+ // epoch-freeze-safe because ts never changes for a given row).
110
111
  // The haystack is `scope + type + content + kw`, where `kw` are the
111
112
  // author-supplied aliases indexed at write time (#40 item 3, the vocabulary
112
113
  // bridge for the bench's strict-paraphrase wall). Keywords are indexed, never
@@ -119,7 +120,12 @@ const LONG_QUERY_TOKENS = 3;
119
120
  // loadAll() result must not be the one place a retired memory leaks back into
120
121
  // an injected block (#43 item 1: forbidden hits). The drop also keeps a
121
122
  // retired row from diluting the document frequencies the ranking depends on.
122
- export function scoreMemories(term: string, mems: Memory[], limit: number): Memory[] {
123
+ export function scoreMemories(
124
+ term: string,
125
+ mems: Memory[],
126
+ limit: number,
127
+ use?: UseSignals,
128
+ ): Memory[] {
123
129
  const live = mems.filter((m) => !m.superseded_by);
124
130
  const query = new Set(words(term).filter((t) => !QUERY_STOPWORDS.has(t)));
125
131
  if (!query.size) return [];
@@ -141,7 +147,14 @@ export function scoreMemories(term: string, mems: Memory[], limit: number): Memo
141
147
  return { m, shared, score };
142
148
  })
143
149
  .filter((s) => s.shared >= needShared)
144
- .sort((a, b) => b.score - a.score || openRank(b.m) - openRank(a.m) || cmpTs(b.m.ts, a.m.ts))
150
+ .sort(
151
+ (a, b) =>
152
+ b.score - a.score ||
153
+ openRank(b.m) - openRank(a.m) ||
154
+ useBoost(b.m, use) - useBoost(a.m, use) ||
155
+ cmpTs(use?.get(b.m.ts)?.last ?? "", use?.get(a.m.ts)?.last ?? "") ||
156
+ cmpTs(b.m.ts, a.m.ts),
157
+ )
145
158
  .slice(0, limit)
146
159
  .map((s) => s.m);
147
160
  }
@@ -152,6 +165,44 @@ export function haystack(m: Memory): string {
152
165
  return `${m.scope} ${m.type} ${m.content}${m.kw?.length ? ` ${m.kw.join(" ")}` : ""}`;
153
166
  }
154
167
 
168
+ /**
169
+ * The content concepts a query and a row actually share (stopwords dropped,
170
+ * capped, `ts` never included). This is what the use ledger records (#42):
171
+ * every term in it already exists inside the row, so a hit line reveals
172
+ * nothing about the prompt beyond the memory it points at — and it is enough
173
+ * for #45 to replay a merge and prove the same reads would still land.
174
+ */
175
+ /** The text a contextual pull actually searched with, for hit bookkeeping. */
176
+ export function pullQuery(args: unknown): string {
177
+ return argText(args);
178
+ }
179
+
180
+ export function sharedTerms(query: string, m: Memory, cap = 8): string[] {
181
+ const q = new Set(words(query).filter((t) => !QUERY_STOPWORDS.has(t)));
182
+ if (!q.size) return [];
183
+ const hay = new Set(words(haystack(m)));
184
+ const out: string[] = [];
185
+ for (const t of q) {
186
+ if (hay.has(t) && !out.includes(t)) out.push(t);
187
+ if (out.length === cap) break;
188
+ }
189
+ return out;
190
+ }
191
+
192
+ // Reinforcement (#42): a row the ledger has seen used breaks a tie over a row
193
+ // nobody ever read, and the more recently used one breaks it first. A TIE-BREAK
194
+ // only — the two-concept gate and IDF score still decide relevance, because
195
+ // popularity is not truth: reinforcement without evidence just amplifies
196
+ // whatever was retrieved first.
197
+ export interface UseSignals {
198
+ get(ts: string): { count: number; last: string } | undefined;
199
+ }
200
+
201
+ function useBoost(a: Memory | undefined, use?: UseSignals): number {
202
+ if (!use || !a) return 0;
203
+ return use.get(a.ts) ? 1 : 0;
204
+ }
205
+
155
206
  // Numeric compare, with the string compare kept as fallback for non-dates
156
207
  // (the ledger hands "" when a row was never used). ISO strings agree with
157
208
  // Date.parse only while the FORMAT agrees: a legacy second-precision stamp
@@ -281,12 +332,13 @@ export async function selectRelevant(
281
332
  message: string,
282
333
  limit = 3,
283
334
  rows?: Memory[],
335
+ use?: UseSignals,
284
336
  ): Promise<{ block: string; selected: Memory[] }> {
285
337
  const text = message.trim();
286
338
  if (!text) return { block: "", selected: [] };
287
339
  // Repo-scoped: model-facing reads see this repo + global rows.
288
340
  const mems = rows ?? visibleHere((await loadAll()).filter(isActive));
289
- const top = scoreMemories(text, mems, limit);
341
+ const top = scoreMemories(text, mems, limit, use);
290
342
  if (!top.length) return { block: "", selected: [] };
291
343
  return {
292
344
  block: `## Relevant durable memory${FRAME}\n${top.map(formatMemory).join("\n")}`,
@@ -384,18 +436,23 @@ export async function contextualPull(
384
436
  input: PullInput,
385
437
  output: PullOutput,
386
438
  budget = injectBudget(),
387
- ): Promise<void> {
439
+ use?: UseSignals,
440
+ ): Promise<Memory[]> {
388
441
  const tool = typeof input.tool === "string" ? input.tool : "";
389
- if (!["grep", "glob", "read"].includes(tool)) return;
442
+ if (!["grep", "glob", "read"].includes(tool)) return [];
390
443
  const term = argText(input.args);
391
- if (!term) return;
444
+ if (!term) return [];
392
445
  // Repo-scoped: model-facing reads see this repo + global rows.
393
446
  const mems = visibleHere((await loadAll()).filter(isActive));
394
- const top = scoreMemories(term, mems, 3);
395
- if (!top.length) return;
447
+ const top = scoreMemories(term, mems, 3, use);
448
+ if (!top.length) return [];
396
449
  // Held to the injection budget too: three long rows were ~12 KB per call.
397
450
  const block = capToBudget(`## Related durable memory (pull)${FRAME}\n${top.map(formatMemory).join("\n")}`, budget);
398
451
  if (block && typeof output.output === "string") {
399
452
  output.output += `\n${block}`;
453
+ // What the ledger counts is what actually rode the result — the budget can
454
+ // drop rows, and crediting a memory the model never saw would inflate it.
455
+ return injectedRows(block, top);
400
456
  }
457
+ return [];
401
458
  }
package/src/memory.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  import { existsSync } from "node:fs";
6
6
  import { open } from "node:fs/promises";
7
7
  import { join, basename } from "node:path";
8
- import { dateStr, memoryRoot, deletionsFile, snapshotDir } from "./config.ts";
8
+ import { dateStr, memoryRoot, deletionsFile, snapshotDir, HITS_FILENAME } from "./config.ts";
9
9
  import { repoScopeFor } from "./repokey.ts";
10
10
  import { getCurrent } from "./state.ts";
11
11
  import { appendLog, ensureDir, formatLine, parseLine, readLines, writeAtomic, type Fields } from "./logfmt.ts";
@@ -87,6 +87,9 @@ const RESERVED = new Set([
87
87
  "deleted.logfmt",
88
88
  "canonical.logfmt",
89
89
  "blocklist.logfmt",
90
+ // The use ledger (src/hits.ts): telemetry, not memory. A hit line must never
91
+ // be able to become a row — or to be superseded, exported, or injected.
92
+ HITS_FILENAME,
90
93
  ]);
91
94
 
92
95
  // Row identity is `ts`: supersede chains, the blocklist, undo matching, and
package/src/status.ts CHANGED
@@ -25,6 +25,89 @@ export interface StoreCounts {
25
25
  scopes: number;
26
26
  /** Rows skipped as malformed by the most recent store read. */
27
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 };
28
111
  }
29
112
 
30
113
  /**
@@ -200,6 +283,17 @@ export async function blockedRecent(limit = 6): Promise<BlockedRow[]> {
200
283
  return rows.slice(-limit).reverse();
201
284
  }
202
285
 
286
+ /** `capture_lag` lines for the trailing window, newest evidence files first. */
287
+ export async function captureLagLines(days = 30): Promise<string[]> {
288
+ const dir = evidenceDir();
289
+ const out: string[] = [];
290
+ for (let d = 0; d < days; d++) {
291
+ const day = new Date(Date.now() - d * 86_400_000).toISOString().split("T")[0]!;
292
+ out.push(...(await readLines(join(dir, `${day}.logfmt`))));
293
+ }
294
+ return out;
295
+ }
296
+
203
297
  function ago(iso: string): string {
204
298
  const ms = Date.now() - new Date(iso).getTime();
205
299
  if (!Number.isFinite(ms) || ms < 0) return "now";
@@ -391,6 +485,29 @@ export function renderMemoryReport(input: {
391
485
  ` ${store.active} active · ${store.superseded} superseded · ${store.open} open · ${store.scopes} scopes` +
392
486
  (store.malformed ? ` · ${store.malformed} malformed (skipped; fix the ts= field or undo)` : ""),
393
487
  );
488
+ if (store.neverRetrieved !== undefined) {
489
+ const used = store.active - store.neverRetrieved;
490
+ const share = store.active ? Math.round((store.neverRetrieved / store.active) * 100) : 0;
491
+ // A ledger younger than the window cannot honestly call anything "never"
492
+ // — it has not been watching long enough. Say what it covers instead of
493
+ // letting day-one readers see 100% dead weight.
494
+ const young = ledgerIsYoung(store.ledgerSince);
495
+ const basis = young
496
+ ? `, ledger only covers since ${store.ledgerSince ? store.ledgerSince.slice(0, 10) : "no lines yet"}`
497
+ : "";
498
+ out.push(
499
+ ` retrieved ${used} rows in the last 30d; never retrieved ${store.neverRetrieved} (${share}%)${basis} — reported, not acted on`,
500
+ );
501
+ }
502
+ const sizing: string[] = [];
503
+ if (store.bytes !== undefined) {
504
+ sizing.push(`${fmtBytes(store.bytes)} total · ${fmtBytes(store.bytesPerRow ?? 0)} per row`);
505
+ }
506
+ if (store.rowsPerDay !== undefined) sizing.push(`${store.rowsPerDay} rows/day (30d)`);
507
+ if (store.captureLag && store.captureLag.n) {
508
+ sizing.push(`capture lag p50 ${fmtMs(store.captureLag.p50)} / p95 ${fmtMs(store.captureLag.p95)}`);
509
+ }
510
+ if (sizing.length) out.push(` ${sizing.join(" · ")}`);
394
511
  out.push("", "Terminal (CLI/TUI) users: /memory opens this as a live panel; the footer shows a one-line badge.");
395
512
  return out.join("\n");
396
513
  }
package/src/tui.tsx CHANGED
@@ -13,6 +13,7 @@ import { For, Show, createSignal } from "solid-js";
13
13
  import { Plugin, usePlugin } from "@opencode/plugin/tui";
14
14
  import type { PanelInput } from "@opencode/plugin/tui/context";
15
15
  import { memoryRoot, evidenceDir } from "./config.ts";
16
+ import { fmtBytes, fmtMs } from "./status.ts";
16
17
  import {
17
18
  attributionLines,
18
19
  blockedRecent,
@@ -20,6 +21,7 @@ import {
20
21
  cacheRate,
21
22
  cacheLines,
22
23
  contextLines,
24
+ ledgerIsYoung,
23
25
  readStatus,
24
26
  statusDir,
25
27
  windowLines,
@@ -299,7 +301,20 @@ function MemoryPanel(props: {
299
301
  <text fg={context.theme.text.base}>
300
302
  {" " + (s()?.store.active ?? 0) + " active · " + (s()?.store.superseded ?? 0) + " superseded · " +
301
303
  (s()?.store.open ?? 0) + " open · " + (s()?.store.scopes ?? 0) + " scopes" +
302
- ((s()?.store.malformed ?? 0) > 0 ? " · " + s()!.store.malformed + " malformed (skipped)" : "")}
304
+ ((s()?.store.malformed ?? 0) > 0 ? " · " + s()!.store.malformed + " malformed (skipped)" : "") +
305
+ ((s()?.store.neverRetrieved ?? 0) > 0
306
+ ? " · " +
307
+ s()!.store.neverRetrieved +
308
+ (ledgerIsYoung(s()!.store.ledgerSince)
309
+ ? " never retrieved (ledger since " + (s()!.store.ledgerSince?.slice(0, 10) ?? "no lines") + ")"
310
+ : " never retrieved (30d)")
311
+ : "") +
312
+ ((s()?.store.bytes ?? 0) > 0
313
+ ? " · " + fmtBytes(s()!.store.bytes!) + " · " + s()!.store.bytesPerRow + " B/row"
314
+ : "") +
315
+ ((s()?.store.captureLag?.n ?? 0) > 0
316
+ ? " · capture p50 " + fmtMs(s()!.store.captureLag!.p50)
317
+ : "")}
303
318
  </text>
304
319
  </Show>
305
320