opencode-self-improvement 0.11.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 +34 -0
- package/package.json +1 -1
- package/src/capture.ts +16 -0
- package/src/evidence.ts +23 -0
- package/src/index.ts +19 -3
- package/src/status.ts +82 -0
- package/src/tui.tsx +7 -0
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.
|
|
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/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/index.ts
CHANGED
|
@@ -30,7 +30,7 @@ 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,
|
|
@@ -54,6 +54,9 @@ import {
|
|
|
54
54
|
writeStatus,
|
|
55
55
|
type Measured,
|
|
56
56
|
type SessionStats,
|
|
57
|
+
captureLag,
|
|
58
|
+
captureLagLines,
|
|
59
|
+
rowsPerDay,
|
|
57
60
|
type StatusPayload,
|
|
58
61
|
type StoreCounts,
|
|
59
62
|
} from "./status.ts";
|
|
@@ -72,7 +75,7 @@ import {
|
|
|
72
75
|
import { getCurrent, setCurrent } from "./state.ts";
|
|
73
76
|
import { resolveRepo, setRepoScope, rememberSessionDir, sessionDir } from "./repokey.ts";
|
|
74
77
|
import { readLines } from "./logfmt.ts";
|
|
75
|
-
import { buildCapturePrompt, flattenTranscript, parseCandidates, parseModelRef } from "./capture.ts";
|
|
78
|
+
import { buildCapturePrompt, flattenTranscript, lagSince, parseCandidates, parseModelRef } from "./capture.ts";
|
|
76
79
|
import { redactSecrets } from "./secrets.ts";
|
|
77
80
|
import { flattenMemoryText } from "./sanitize.ts";
|
|
78
81
|
import { bunFloorWarning } from "./runtime.ts";
|
|
@@ -665,6 +668,13 @@ const impl = {
|
|
|
665
668
|
const ledger = await readLedger();
|
|
666
669
|
store.neverRetrieved = neverRetrieved(act, ledger).length;
|
|
667
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());
|
|
668
678
|
return {
|
|
669
679
|
content: renderMemoryReport({ status, store, blocked: await blockedRecent(6) }),
|
|
670
680
|
};
|
|
@@ -1037,12 +1047,17 @@ const impl = {
|
|
|
1037
1047
|
const msgs = await contextFn({ sessionID: sid });
|
|
1038
1048
|
const transcript = flattenTranscript(msgs);
|
|
1039
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);
|
|
1040
1054
|
const out = await generateApi.text({
|
|
1041
1055
|
model: modelRef,
|
|
1042
1056
|
prompt: buildCapturePrompt(transcript.slice(-8000), captureMax),
|
|
1043
1057
|
});
|
|
1044
1058
|
const text = typeof out === "string" ? out : out?.text ?? "";
|
|
1045
|
-
|
|
1059
|
+
const candidates = parseCandidates(text, captureMax);
|
|
1060
|
+
for (const c of candidates) {
|
|
1046
1061
|
const outcome = await runWriteGate(
|
|
1047
1062
|
{ ...c, tags: ["auto-capture"] },
|
|
1048
1063
|
gateContext(),
|
|
@@ -1054,6 +1069,7 @@ const impl = {
|
|
|
1054
1069
|
false,
|
|
1055
1070
|
);
|
|
1056
1071
|
}
|
|
1072
|
+
await recordCaptureLag(sid, lagMs, candidates.length ? "candidates" : "empty");
|
|
1057
1073
|
} catch {
|
|
1058
1074
|
// fail-closed: a broken capture attempt is invisible to the session
|
|
1059
1075
|
}
|
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>
|