opencode-self-improvement 0.11.0 → 0.13.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,72 @@ 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
+
243
+ ## Consolidation that has to earn its merge
244
+
245
+ Stores accumulate near-duplicates: the same fact written three times, weeks
246
+ apart, in slightly different words. `memory_consolidate` finds them and proposes
247
+ a merge — and it is built to say **no** more often than to say yes:
248
+
249
+ - **Deterministic merge.** The canonical row is the survivor's prose *verbatim*,
250
+ plus the absorbed rows' aliases as keywords. No model rewrites anything: a
251
+ rewrite cannot be diffed, audited, or proven to preserve meaning, and this
252
+ plugin ships no model.
253
+ - **Proven reads, per cluster.** Every read the use ledger recorded for that
254
+ cluster is replayed against the merged store. A merge is proposed only when
255
+ the canonical row catches at least as many of the cluster's own reads as the
256
+ best single member did alone. A cluster with no recorded reads is reported as
257
+ *unmeasured* and never merged on resemblance.
258
+ - **Proposals, not writes.** The tool writes nothing. It prints the exact
259
+ `memory_merge_review` call that resolves each proposal; resolving is
260
+ supersede-not-delete, so absorbed rows stay recoverable.
261
+ - **The most recently used member is never a loser.**
262
+
263
+ On the shipped eval dataset the pass takes 200 rows to 52 with
264
+ **R@3 52 → 53 and R@1 52 → 50**, and store-wide injected characters 25 945c →
265
+ 6 933c (two queries out of 105 get a block up to 48 characters bigger, because a
266
+ canonical row inherits aliases and wins a slot it used to lose). That trade is
267
+ asserted in CI, not assumed: `test/consolidate-bench.test.ts` bounds both the
268
+ regression and the budget swap.
269
+
270
+ The ticket carried a HOLD pending "a month of hits data", on the reasoning that
271
+ consolidation is fragile and may not earn its cost. Measurement answers that
272
+ better than a calendar does — so the harness measures it, per cluster, on every
273
+ run.
274
+
209
275
  ## Quick start
210
276
 
211
277
  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.11.0",
3
+ "version": "0.13.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 "";
@@ -0,0 +1,321 @@
1
+ // Consolidation proposals (#45): episodic rows → one canonical row, proposed and
2
+ // measured, never silently applied.
3
+ //
4
+ // The write-gate already collapses byte-identical restatements and flags >0.9
5
+ // jaccard overlaps *at write time*. What it cannot do is notice the slow drift
6
+ // that only a store develops later: three settled rows in one scope, written
7
+ // weeks apart, saying nearly the same thing in slightly different words. Every
8
+ // one of them rides the budget, and each is reachable by a different fragment
9
+ // of vocabulary.
10
+ //
11
+ // The literature is blunt that this step is where memory systems break (arXiv
12
+ // 2603.07670: "rarely automatic… fragile and hard to validate"), and NOOA's
13
+ // published numbers are the reason this file refuses to be clever: their
14
+ // reflection records were 22% of rows but ~1% of reads, and abstracting hurt
15
+ // pinpoint lookup. So the rules here are:
16
+ //
17
+ // 1. DETERMINISTIC MERGE. The canonical row is the survivor's prose, verbatim,
18
+ // plus the aliases and distinctive vocabulary of the rows it absorbs. No
19
+ // model rewrites anything — a rewrite cannot be diffed, audited, or proven
20
+ // to preserve meaning, and this plugin ships no model.
21
+ // 2. PROVEN READS, per cluster. Every read the cluster has actually served is
22
+ // taken from the use ledger and replayed against the merged store. A merge
23
+ // is proposed only when the merged row catches at least as many of those
24
+ // reads as the best single member did. "Looks redundant" is not a reason.
25
+ // 3. PROPOSALS, not writes. Nothing here mutates the store. A human resolves a
26
+ // proposal through memory_merge_review (supersede-not-delete, recoverable).
27
+ // 4. The most recently used member is never a loser (#42's rule, inherited).
28
+ import type { Memory } from "./memory.ts";
29
+ import type { UseSignal } from "./hits.ts";
30
+ import { cmpTs, formatMemory, scoreMemories, words } from "./inject.ts";
31
+
32
+ /** Default jaccard floor for "these two rows are the same statement". */
33
+ export const DEFAULT_JACCARD = 0.55;
34
+ /** Aliases are useful up to a point; a merged row that hoards 60 words is noise. */
35
+ export const MAX_MERGED_KW = 12;
36
+
37
+ export interface ReadSet {
38
+ /** The terms a real read used, exactly as the ledger recorded them. */
39
+ terms: string[];
40
+ /** Row ids that read credited. */
41
+ rows: string[];
42
+ }
43
+
44
+ export interface ClusterOptions {
45
+ jaccard?: number;
46
+ /** Smallest cluster worth proposing (2 = a pair). */
47
+ minMembers?: number;
48
+ /** Ceiling on cluster size: 6 rows merged is a rewrite, not a merge. */
49
+ maxMembers?: number;
50
+ }
51
+
52
+ function tokens(text: string): string[] {
53
+ return text.toLowerCase().split(/[^a-z0-9_.]+/).filter(Boolean);
54
+ }
55
+
56
+ function jaccard(a: Set<string>, b: Set<string>): number {
57
+ let inter = 0;
58
+ for (const t of a) if (b.has(t)) inter++;
59
+ const union = a.size + b.size - inter;
60
+ return union === 0 ? 0 : inter / union;
61
+ }
62
+
63
+ /**
64
+ * Candidate clusters of settled, same-scope, same-type rows that say the same
65
+ * thing. Grouping is transitive on the jaccard edge (union-find), so a chain of
66
+ * "almost the same" rows becomes one cluster instead of N/2 arbitrary pairs.
67
+ *
68
+ * Open rows are excluded on purpose: an open thread is a live plan, not episodic
69
+ * material to compress, and collapsing it would destroy the frontier the panel
70
+ * is showing the user.
71
+ */
72
+ export function clustersFor(rows: Memory[], opts: ClusterOptions = {}): Memory[][] {
73
+ const min = opts.jaccard ?? DEFAULT_JACCARD;
74
+ const minMembers = opts.minMembers ?? 2;
75
+ const maxMembers = opts.maxMembers ?? 6;
76
+ const pool = rows
77
+ .filter((m) => !m.superseded_by && m.status !== "open" && m.content.trim())
78
+ .sort((a, b) => cmpTs(a.ts, b.ts));
79
+
80
+ const parent = pool.map((_, i) => i);
81
+ const find = (i: number): number => {
82
+ while (parent[i] !== i) {
83
+ parent[i] = parent[parent[i]!]!;
84
+ i = parent[i]!;
85
+ }
86
+ return i;
87
+ };
88
+ const union = (a: number, b: number) => {
89
+ const ra = find(a);
90
+ const rb = find(b);
91
+ if (ra !== rb) parent[rb] = ra;
92
+ };
93
+
94
+ const toks = pool.map((m) => new Set(tokens(m.content)));
95
+ for (let i = 0; i < pool.length; i++) {
96
+ for (let j = i + 1; j < pool.length; j++) {
97
+ const a = pool[i]!;
98
+ const b = pool[j]!;
99
+ if (a.scope !== b.scope || a.type !== b.type) continue;
100
+ if (jaccard(toks[i]!, toks[j]!) >= min) union(i, j);
101
+ }
102
+ }
103
+
104
+ const groups = new Map<number, Memory[]>();
105
+ pool.forEach((m, i) => {
106
+ const root = find(i);
107
+ const g = groups.get(root) ?? [];
108
+ g.push(m);
109
+ groups.set(root, g);
110
+ });
111
+ return [...groups.values()]
112
+ .filter((g) => g.length >= minMembers && g.length <= maxMembers)
113
+ .sort((a, b) => cmpTs(a[0]!.ts, b[0]!.ts));
114
+ }
115
+
116
+ /**
117
+ * The canonical row of a cluster: the most recently used member, falling back to
118
+ * the newest row when the ledger knows nothing. Recency in the boost is not
119
+ * recency in the ledger — a row that retrieval has actually been landing on is
120
+ * the one worth keeping, and this is #42's rule applied to merges.
121
+ */
122
+ export function survivorFor(cluster: Memory[], use?: Map<string, UseSignal>): Memory {
123
+ return [...cluster].sort((a, b) => {
124
+ const la = use?.get(a.ts)?.last ?? "";
125
+ const lb = use?.get(b.ts)?.last ?? "";
126
+ if (la !== lb) return la < lb ? 1 : -1;
127
+ return cmpTs(b.ts, a.ts);
128
+ })[0]!;
129
+ }
130
+
131
+ export interface MergePlan {
132
+ id: string;
133
+ scope: string;
134
+ type: string;
135
+ survivor: Memory;
136
+ losers: Memory[];
137
+ /** What the canonical row would look like. */
138
+ merged: Memory;
139
+ /** Reads the cluster served, taken from the ledger. */
140
+ reads: ReadSet[];
141
+ readsBefore: number;
142
+ readsAfter: number;
143
+ bestMemberBefore: number;
144
+ bytesBefore: number;
145
+ bytesAfter: number;
146
+ accepted: boolean;
147
+ reasons: string[];
148
+ }
149
+
150
+ /** Distinctive vocabulary of the absorbed rows: what the survivor does not say. */
151
+ function inheritedKw(cluster: Memory[], survivor: Memory): string[] {
152
+ const have = new Set(words(`${survivor.content} ${(survivor.kw ?? []).join(" ")}`));
153
+ const out = [...(survivor.kw ?? [])];
154
+ for (const m of cluster) {
155
+ if (m.ts === survivor.ts) continue;
156
+ for (const k of m.kw ?? []) if (!out.includes(k)) out.push(k);
157
+ // Only distinctive words the absorbed row was FOUND by, in practice: its
158
+ // own vocabulary minus what the survivor already carries.
159
+ for (const w of words(m.content)) {
160
+ if (!have.has(w) && !out.includes(w)) out.push(w);
161
+ }
162
+ }
163
+ return out.slice(0, MAX_MERGED_KW);
164
+ }
165
+
166
+ function buildMerged(cluster: Memory[], survivor: Memory): Memory {
167
+ const kw = inheritedKw(cluster, survivor);
168
+ return {
169
+ ...survivor,
170
+ kw: kw.length ? kw : undefined,
171
+ tags: [...new Set(["consolidated", ...(survivor.tags ?? []), ...cluster.flatMap((m) => m.tags ?? [])])].slice(
172
+ 0,
173
+ 12,
174
+ ),
175
+ };
176
+ }
177
+
178
+ /**
179
+ * Replay the cluster's real reads against a store where the cluster has been
180
+ * replaced by the merged row. `rows` is the whole active store; the function
181
+ * returns how many of those reads still land on the cluster.
182
+ */
183
+ // Cluster bookkeeping uses OBJECT identity, not `ts`. The ledger keys on ts
184
+ // (correctly — it is the row id in the store), but nothing here may assume two
185
+ // rows cannot share one timestamp: the eval store does exactly that, and a
186
+ // ts-keyed filter would silently absorb an entire cluster into its survivor.
187
+ function replayReads(rows: Memory[], cluster: Memory[], replacement: Memory | null, reads: ReadSet[]): number {
188
+ const inCluster = new Set(cluster);
189
+ const store = replacement ? [...rows.filter((m) => !inCluster.has(m)), replacement] : rows;
190
+ let hits = 0;
191
+ for (const r of reads) {
192
+ const query = r.terms.join(" ");
193
+ if (!query.trim()) continue;
194
+ const top = scoreMemories(query, store, 3);
195
+ const landed = top.some((m) => (replacement ? m === replacement : inCluster.has(m)));
196
+ if (landed) hits++;
197
+ }
198
+ return hits;
199
+ }
200
+
201
+ /** Reads the ledger says this cluster served (any member credited). */
202
+ export function readsFor(cluster: Memory[], allReads: ReadSet[]): ReadSet[] {
203
+ const ids = new Set(cluster.map((m) => m.ts));
204
+ return allReads.filter((r) => r.rows.some((id) => ids.has(id)) && r.terms.length > 0);
205
+ }
206
+
207
+ /**
208
+ * One cluster → one measured proposal. `rows` is the full active store; `use`
209
+ * and `reads` come from the use ledger. A cluster with no recorded reads is
210
+ * reported as unmeasurable rather than merged on vibes.
211
+ */
212
+ export function proposeCluster(
213
+ rows: Memory[],
214
+ cluster: Memory[],
215
+ use: Map<string, UseSignal>,
216
+ allReads: ReadSet[],
217
+ ): MergePlan {
218
+ const survivor = survivorFor(cluster, use);
219
+ const losers = cluster.filter((m) => m !== survivor);
220
+ const merged = buildMerged(cluster, survivor);
221
+ const reads = readsFor(cluster, allReads);
222
+
223
+ // The bar the ticket sets: the merged row must catch at least as many of the
224
+ // cluster's own reads as the BEST single member did on its own.
225
+ const members = cluster.map((m) => replayReads(rows, cluster, m, reads));
226
+ const bestMemberBefore = members.length ? Math.max(...members) : 0;
227
+ const readsBefore = replayReads(rows, cluster, null, reads);
228
+ const readsAfter = replayReads(rows, cluster, merged, reads);
229
+
230
+ const bytesBefore = cluster.reduce((n, m) => n + formatMemory(m).length, 0);
231
+ const bytesAfter = formatMemory(merged).length;
232
+
233
+ const reasons: string[] = [];
234
+ if (!reads.length) reasons.push("unmeasured: the ledger has no read for any member of this cluster");
235
+ else if (readsAfter < bestMemberBefore)
236
+ reasons.push(
237
+ `reads would drop: merged row catches ${readsAfter} of ${reads.length}, the best member alone caught ${bestMemberBefore}`,
238
+ );
239
+ if (bytesAfter > bytesBefore) reasons.push("merged row is larger than the rows it absorbs");
240
+
241
+ return {
242
+ id: `cl-${cluster
243
+ .map((m) => m.ts)
244
+ .sort()[0]!
245
+ .replace(/[^0-9]/g, "")
246
+ .slice(-9)}`,
247
+ scope: survivor.scope,
248
+ type: survivor.type,
249
+ survivor,
250
+ losers,
251
+ merged,
252
+ reads,
253
+ readsBefore,
254
+ readsAfter,
255
+ bestMemberBefore,
256
+ bytesBefore,
257
+ bytesAfter,
258
+ accepted: reasons.length === 0,
259
+ reasons,
260
+ };
261
+ }
262
+
263
+ export interface ProposalReport {
264
+ plans: MergePlan[];
265
+ rowsBefore: number;
266
+ rowsAfter: number;
267
+ injectedBefore: number;
268
+ injectedAfter: number;
269
+ }
270
+
271
+ /**
272
+ * The pass: cluster, measure, keep only proposals that prove the reads survive.
273
+ * Dry by construction — the caller decides whether anything is applied.
274
+ */
275
+ export function proposeConsolidations(
276
+ rows: Memory[],
277
+ use: Map<string, UseSignal>,
278
+ reads: ReadSet[],
279
+ opts: ClusterOptions = {},
280
+ ): ProposalReport {
281
+ const plans = clustersFor(rows, opts)
282
+ .map((c) => proposeCluster(rows, c, use, reads))
283
+ .filter((p) => p.accepted);
284
+ const absorbed = new Set<Memory>(plans.flatMap((p) => p.losers));
285
+ const injected = (list: Memory[]) => list.reduce((n, m) => n + formatMemory(m).length, 0);
286
+ return {
287
+ plans,
288
+ rowsBefore: rows.length,
289
+ rowsAfter: rows.length - absorbed.size,
290
+ injectedBefore: injected(rows),
291
+ // Absorbed rows leave the budget; canonical rows keep theirs (kw never renders).
292
+ injectedAfter: injected(rows.filter((m) => !absorbed.has(m))),
293
+ };
294
+ }
295
+
296
+ /** Human-readable proposal list. Ends with the exact command to resolve one. */
297
+ export function renderProposals(report: ProposalReport): string {
298
+ const out: string[] = ["CONSOLIDATION PROPOSALS — nothing was written", ""];
299
+ if (!report.plans.length) {
300
+ out.push(" none — no cluster proved it could hold its reads.");
301
+ return out.join("\n");
302
+ }
303
+ for (const p of report.plans) {
304
+ out.push(
305
+ `${p.id} ${p.type}/${p.scope} ${p.losers.length + 1} rows → 1`,
306
+ ` keep ${p.survivor.ts}`,
307
+ ` ${p.survivor.content.slice(0, 160)}`,
308
+ ...p.losers.map((l) => ` absorb ${l.ts} ${l.content.slice(0, 120)}`),
309
+ ` reads ${p.reads.length} logged · best member alone ${p.bestMemberBefore} · merged ${p.readsAfter}`,
310
+ ` budget ${p.bytesBefore}c → ${p.bytesAfter}c for this cluster`,
311
+ ` resolve: memory_merge_review(loser="${p.losers[0]!.ts}", survivor="${p.survivor.ts}", reason="consolidate ${p.id}")`,
312
+ "",
313
+ );
314
+ }
315
+ out.push(
316
+ `STORE ${report.rowsBefore} rows → ${report.rowsAfter} if every proposal is resolved · ` +
317
+ `injected ${report.injectedBefore}c → ${report.injectedAfter}c`,
318
+ );
319
+ out.push("Resolving is supersede-not-delete: absorbed rows stay recoverable via memory_undo.");
320
+ return out.join("\n");
321
+ }
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 CHANGED
@@ -20,6 +20,7 @@ import { appendLog, bracketList, formatLine, parseLine, readLines, writeAtomic }
20
20
  import type { UseSignals } from "./inject.ts";
21
21
  import { withStoreLock, LOCK_WRITE } from "./lock.ts";
22
22
  import type { Memory } from "./memory.ts";
23
+ import type { ReadSet } from "./consolidate.ts";
23
24
 
24
25
  export type HitSource = "inject" | "pull" | "recall";
25
26
 
@@ -170,6 +171,24 @@ function parseList(value: string): string[] {
170
171
  .filter(Boolean);
171
172
  }
172
173
 
174
+ /**
175
+ * Every read the ledger recorded, in file order: the terms used and the rows it
176
+ * credited. This is the corpus consolidation (#45) replays — "would this merge
177
+ * have lost a read that actually happened?" is only answerable against real
178
+ * reads, and a per-row aggregate has already thrown the grouping away.
179
+ */
180
+ export async function readReads(): Promise<ReadSet[]> {
181
+ const out: ReadSet[] = [];
182
+ for (const line of await readLines(hitsFile())) {
183
+ const f = parseLine(line);
184
+ if (!f || f.ev !== "memory_used") continue;
185
+ const rows = typeof f.mem === "string" ? parseList(f.mem) : [];
186
+ const terms = typeof f.terms === "string" ? parseList(f.terms) : [];
187
+ if (rows.length) out.push({ terms, rows });
188
+ }
189
+ return out;
190
+ }
191
+
173
192
  /** Rows the ledger has NEVER seen used, plus the honest since-qualifier. */
174
193
  export function neverRetrieved(rows: Memory[], ledger: UseLedger, days = 30): Memory[] {
175
194
  const cutoff = new Date(Date.now() - days * 86_400_000).toISOString();
package/src/index.ts CHANGED
@@ -30,7 +30,9 @@ 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
+ import { proposeConsolidations, renderProposals } from "./consolidate.ts";
35
+ import { readReads } from "./hits.ts";
34
36
  import {
35
37
  capToBudget,
36
38
  compactionAnchor,
@@ -54,6 +56,9 @@ import {
54
56
  writeStatus,
55
57
  type Measured,
56
58
  type SessionStats,
59
+ captureLag,
60
+ captureLagLines,
61
+ rowsPerDay,
57
62
  type StatusPayload,
58
63
  type StoreCounts,
59
64
  } from "./status.ts";
@@ -72,7 +77,7 @@ import {
72
77
  import { getCurrent, setCurrent } from "./state.ts";
73
78
  import { resolveRepo, setRepoScope, rememberSessionDir, sessionDir } from "./repokey.ts";
74
79
  import { readLines } from "./logfmt.ts";
75
- import { buildCapturePrompt, flattenTranscript, parseCandidates, parseModelRef } from "./capture.ts";
80
+ import { buildCapturePrompt, flattenTranscript, lagSince, parseCandidates, parseModelRef } from "./capture.ts";
76
81
  import { redactSecrets } from "./secrets.ts";
77
82
  import { flattenMemoryText } from "./sanitize.ts";
78
83
  import { bunFloorWarning } from "./runtime.ts";
@@ -87,6 +92,7 @@ import {
87
92
  ForgetArgs,
88
93
  ImportArgs,
89
94
  InitArgs,
95
+ ConsolidateArgs,
90
96
  MergeReviewArgs,
91
97
  RecallArgs,
92
98
  RememberArgs,
@@ -329,6 +335,31 @@ const impl = {
329
335
  },
330
336
  }));
331
337
 
338
+ editor.add(validated(ConsolidateArgs, {
339
+ name: "memory_consolidate",
340
+ description:
341
+ "Propose consolidations of near-duplicate settled rows — read-only, nothing is written. Clusters same-scope same-type rows by jaccard, picks the most recently used member as canonical (#42's rule: the row retrieval keeps landing on), and proposes it ONLY when replaying the cluster's own logged reads proves the merged row catches at least as many reads as the best single member did. A cluster with no recorded reads is reported as unmeasured, never merged on resemblance. Resolve a proposal with memory_merge_review; absorbed rows stay recoverable. The merge is deterministic — the canonical row is the survivor's prose plus the absorbed rows' aliases — because this plugin ships no model and a rewritten row cannot be diffed or audited.",
342
+ options: direct,
343
+ async execute(args): Promise<{ content: string }> {
344
+ const all = (await loadAll()).filter(isActive).filter(isVisibleHere);
345
+ const rows = args.scope ? all.filter((m) => m.scope === args.scope) : all;
346
+ const ledger = await readLedger();
347
+ const use = ledger.byRow;
348
+ const reads = await readReads();
349
+ const report = proposeConsolidations(rows, use, reads, {
350
+ ...(args.jaccard !== undefined ? { jaccard: args.jaccard } : {}),
351
+ });
352
+ const shown = report.plans.slice(0, args.limit ?? 10);
353
+ const out = renderProposals({ ...report, plans: shown });
354
+ await record(
355
+ "consolidate_propose",
356
+ { clusters: shown.length, rows: report.rowsBefore, would_drop: report.rowsBefore - report.rowsAfter },
357
+ false,
358
+ );
359
+ return { content: out };
360
+ },
361
+ }));
362
+
332
363
  editor.add(validated(InitArgs, {
333
364
  name: "memory_init",
334
365
  description:
@@ -665,6 +696,13 @@ const impl = {
665
696
  const ledger = await readLedger();
666
697
  store.neverRetrieved = neverRetrieved(act, ledger).length;
667
698
  store.ledgerSince = ledger.since;
699
+ // Self-metrics (#44): what the store costs, how fast it grows, and how
700
+ // stale a capture is when it fires. Same rule as above — the numbers
701
+ // are the point, not a verdict on them.
702
+ store.bytes = act.reduce((n, m) => n + new TextEncoder().encode(formatMemory(m)).length, 0);
703
+ store.bytesPerRow = act.length ? Math.round(store.bytes / act.length) : 0;
704
+ store.rowsPerDay = rowsPerDay(act) ?? undefined;
705
+ store.captureLag = captureLag(await captureLagLines());
668
706
  return {
669
707
  content: renderMemoryReport({ status, store, blocked: await blockedRecent(6) }),
670
708
  };
@@ -1037,12 +1075,17 @@ const impl = {
1037
1075
  const msgs = await contextFn({ sessionID: sid });
1038
1076
  const transcript = flattenTranscript(msgs);
1039
1077
  if (transcript.length < 200) continue; // too thin to mine reliably
1078
+ // #44: how stale is a capture? Distance from the last message of
1079
+ // the transcript to this instant. Sessions idle for an hour
1080
+ // produce an hour-old capture, and the surfaces now say so.
1081
+ const lagMs = lagSince(msgs);
1040
1082
  const out = await generateApi.text({
1041
1083
  model: modelRef,
1042
1084
  prompt: buildCapturePrompt(transcript.slice(-8000), captureMax),
1043
1085
  });
1044
1086
  const text = typeof out === "string" ? out : out?.text ?? "";
1045
- for (const c of parseCandidates(text, captureMax)) {
1087
+ const candidates = parseCandidates(text, captureMax);
1088
+ for (const c of candidates) {
1046
1089
  const outcome = await runWriteGate(
1047
1090
  { ...c, tags: ["auto-capture"] },
1048
1091
  gateContext(),
@@ -1054,6 +1097,7 @@ const impl = {
1054
1097
  false,
1055
1098
  );
1056
1099
  }
1100
+ await recordCaptureLag(sid, lagMs, candidates.length ? "candidates" : "empty");
1057
1101
  } catch {
1058
1102
  // fail-closed: a broken capture attempt is invisible to the session
1059
1103
  }
package/src/inject.ts CHANGED
@@ -208,7 +208,9 @@ function useBoost(a: Memory | undefined, use?: UseSignals): number {
208
208
  // Date.parse only while the FORMAT agrees: a legacy second-precision stamp
209
209
  // ("…:01Z") and a millisecond stamp ("…:01.000Z") for the same instant order
210
210
  // wrong as strings, which would silently mis-rank the recency tie-break.
211
- function cmpTs(a: string, b: string): number {
211
+ // Exported for consolidate.ts — cluster ordering must not disagree with the
212
+ // ranking it is merging.
213
+ export function cmpTs(a: string, b: string): number {
212
214
  const na = Date.parse(a);
213
215
  const nb = Date.parse(b);
214
216
  if (!Number.isNaN(na) && !Number.isNaN(nb)) return na < nb ? -1 : na > nb ? 1 : 0;
package/src/schema.ts CHANGED
@@ -132,6 +132,17 @@ export const MergeReviewArgs = z.object({
132
132
  reason: z.string().describe("Why the survivor is canonical over the loser (written to evidence)"),
133
133
  });
134
134
 
135
+ export const ConsolidateArgs = z.object({
136
+ scope: z.string().describe("Only consider rows in this scope").optional(),
137
+ jaccard: z
138
+ .number()
139
+ .describe("Similarity floor for 'same statement' (default 0.55)")
140
+ .min(0.2)
141
+ .max(0.95)
142
+ .optional(),
143
+ limit: z.number().describe("Maximum proposals to report (default 10)").min(1).max(50).optional(),
144
+ });
145
+
135
146
  export const ExportArgs = z.object({
136
147
  scope: z.string().describe("Only export memories in this exact scope").optional(),
137
148
  file: z.string().describe("Destination path (default: <memory-root>/exports/)").optional(),
package/src/status.ts CHANGED
@@ -36,6 +36,14 @@ export interface StoreCounts {
36
36
  * ledger says so instead of inflating "never" (see `ledgerIsYoung`).
37
37
  */
38
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 };
39
47
  }
40
48
 
41
49
  /**
@@ -48,6 +56,60 @@ export function ledgerIsYoung(ledgerSince: string | null | undefined, now = Date
48
56
  return ledgerSince > new Date(now - 30 * 86_400_000).toISOString();
49
57
  }
50
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
+
51
113
  /**
52
114
  * Per-session ledger, incremented at the session.context injection decision
53
115
  * (so counts match exactly what was injected — an aborted turn still rode the
@@ -221,6 +283,17 @@ export async function blockedRecent(limit = 6): Promise<BlockedRow[]> {
221
283
  return rows.slice(-limit).reverse();
222
284
  }
223
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
+
224
297
  function ago(iso: string): string {
225
298
  const ms = Date.now() - new Date(iso).getTime();
226
299
  if (!Number.isFinite(ms) || ms < 0) return "now";
@@ -426,6 +499,15 @@ export function renderMemoryReport(input: {
426
499
  ` retrieved ${used} rows in the last 30d; never retrieved ${store.neverRetrieved} (${share}%)${basis} — reported, not acted on`,
427
500
  );
428
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(" · ")}`);
429
511
  out.push("", "Terminal (CLI/TUI) users: /memory opens this as a live panel; the footer shows a one-line badge.");
430
512
  return out.join("\n");
431
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,
@@ -307,6 +308,12 @@ function MemoryPanel(props: {
307
308
  (ledgerIsYoung(s()!.store.ledgerSince)
308
309
  ? " never retrieved (ledger since " + (s()!.store.ledgerSince?.slice(0, 10) ?? "no lines") + ")"
309
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)
310
317
  : "")}
311
318
  </text>
312
319
  </Show>