opencode-self-improvement 0.14.1 → 0.14.3
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 +205 -441
- package/package.json +1 -1
- package/src/hits.ts +6 -2
- package/src/index.ts +35 -9
- package/src/memory.ts +5 -1
package/README.md
CHANGED
|
@@ -1,165 +1,125 @@
|
|
|
1
1
|
# Opencode-Self-Improvement
|
|
2
2
|
|
|
3
|
-
Durable memory for opencode, plus a one-command per-repo setup.
|
|
3
|
+
Durable memory for [opencode](https://opencode.ai): the decisions, commands and facts an agent should keep across sessions, plus a one-command per-repo setup.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
Every memory passes four write gates, injection is budgeted and cache-stable, and nothing is ever deleted — updates supersede and `memory_undo` rolls back.
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
## What you get
|
|
7
|
+
## Quick start
|
|
9
8
|
|
|
10
|
-
|
|
11
|
-
keep across sessions (`memory_init`, `memory_remember`, `memory_recall`,
|
|
12
|
-
`memory_update`, `memory_forget`, `memory_list`, `memory_undo`,
|
|
13
|
-
`memory_evidence`, `memory_export`, `memory_import`, `memory_decay`,
|
|
14
|
-
`memory_status`).
|
|
15
|
-
- **Memory at a glance** — the terminal shows a footer badge (injected chars
|
|
16
|
-
vs budget + a cache-health dot) and a `/memory` panel; desktop/web/IDE get
|
|
17
|
-
the same report in-chat via `/memory-report`, including the *measured*
|
|
18
|
-
prompt-cache hit rate. See [Memory at a glance](#memory-at-a-glance).
|
|
19
|
-
- **`/repo-init`** — for each repo: indexes the code graph and remembers the
|
|
20
|
-
test/build commands, keyed to the git head. The command installs itself; no
|
|
21
|
-
setup beyond the plugin.
|
|
22
|
-
- **Memory-aware compaction** — durable memories are handed to the compaction
|
|
23
|
-
summarizer, so a long session doesn't get an amnesia wipe exactly when it
|
|
24
|
-
needs its memory most.
|
|
25
|
-
- **Export / import (JSONL)** — `memory_export` / `memory_import` back the store
|
|
26
|
-
up or move it between machines. Every imported row re-enters through the same
|
|
27
|
-
write gates, so an export can't smuggle junk in.
|
|
28
|
-
- **Injection-resistant by construction** — every injected memory block frames
|
|
29
|
-
itself as *reference data, never instructions*; rows that arrived through a
|
|
30
|
-
path the gates can't fully vouch for carry a visible `[via import]` /
|
|
31
|
-
`[via auto-capture]` provenance marker; and the `status:"open"` frontier
|
|
32
|
-
exemption is only honored for files carrying a machine-made export header.
|
|
33
|
-
- **Decay** — `memory_decay` retires stale open threads. Dry run by default;
|
|
34
|
-
supersede-not-delete, snapshot-first, undoable.
|
|
35
|
-
- **Auto-capture (opt-in)** — with `autoCapture` on, session-idle events get one
|
|
36
|
-
cheap model pass that proposes memory candidates; every candidate still faces
|
|
37
|
-
the same write gates. Off by default, so the install stays zero-token.
|
|
38
|
-
- Automatically de-dupes similar memories and avoids contradictions by searching for existing memories before saving new ones.
|
|
39
|
-
- **Write gates** — every memory passes 4 checks before it sticks: code references are
|
|
40
|
-
verified against your actual repo, near-duplicates are collapsed, contradictions with
|
|
41
|
-
superseded memories are rejected. Blocked writes are logged with a reason
|
|
42
|
-
(`memory_evidence`), and nothing is ever deleted — updates supersede the old row and
|
|
43
|
-
`memory_undo` rolls back.
|
|
44
|
-
- **Safe across concurrent sessions** — the daily store file is shared by every
|
|
45
|
-
opencode session on the machine plus the viewer, so the whole-file rewrites
|
|
46
|
-
(update, forget, undo, viewer delete) hold a per-file lock that is honored
|
|
47
|
-
across processes, and hand the new file over with an atomic rename. Another
|
|
48
|
-
session's write is never overwritten, and a reader never sees a half-written
|
|
49
|
-
store.
|
|
50
|
-
- Automatically looks for insights when you complete the verification gates (tests, linting, etc)
|
|
51
|
-
- Always defaults to memories first before sending a prompt to the LLM, which saves tokens!
|
|
9
|
+
**1. Add the plugin** to `~/.config/opencode/opencode.jsonc` (global) or a project `opencode.jsonc`:
|
|
52
10
|
|
|
53
|
-
|
|
11
|
+
```json
|
|
12
|
+
{
|
|
13
|
+
"$schema": "https://opencode.ai/config.json",
|
|
14
|
+
"plugins": ["opencode-self-improvement"]
|
|
15
|
+
}
|
|
16
|
+
```
|
|
54
17
|
|
|
55
|
-
|
|
56
|
-
auto-capture prompt before that prompt leaves the plugin, at the write gate
|
|
57
|
-
before content is hashed or analysed, and again in `appendMemory`, the final
|
|
58
|
-
write choke point used by gated writes and the viewer's edit/restore-entry
|
|
59
|
-
paths. Credential-shaped values in memory content become `[redacted]`.
|
|
60
|
-
Credential-shaped `scope`, `tags`, or `issue` metadata is rejected instead of
|
|
61
|
-
being silently rewritten.
|
|
62
|
-
|
|
63
|
-
The rules cover OpenAI `sk-` tokens; GitHub `ghp_`, `gho_`, and `github_pat_`
|
|
64
|
-
tokens; Slack `xoxb-` and `xoxp-` tokens; AWS `AKIA` access-key IDs; Google
|
|
65
|
-
`AIza` API keys; bearer tokens containing digits; PEM private-key blocks; and
|
|
66
|
-
high-entropy values assigned to names ending in `_KEY`, `_TOKEN`, `_SECRET`,
|
|
67
|
-
or `_PASSWORD` (plus `password`). This is deliberately best-effort, not a
|
|
68
|
-
guarantee: it can miss hex-only secrets, passwords with few character classes,
|
|
69
|
-
and credentials written in prose without an assignment.
|
|
70
|
-
|
|
71
|
-
`memory_remember` still replies `Remembered` when content was redacted, so the
|
|
72
|
-
stored text can differ from what was sent. Redaction is forward-only: existing
|
|
73
|
-
stores are not scrubbed, and `memory_export` writes whatever is already stored
|
|
74
|
-
verbatim. See [issue #74](https://github.com/abogartz/opencode-self-improvement/issues/74)
|
|
75
|
-
for the separate existing-store work.
|
|
76
|
-
|
|
77
|
-
Auto-capture is off by default, so capture-prompt redaction protects opt-in
|
|
78
|
-
installs. The write-gate and `appendMemory` checks apply to every install.
|
|
79
|
-
|
|
80
|
-
## Token cost, on purpose
|
|
81
|
-
|
|
82
|
-
Memory plugins have a reputation for burning tokens and busting the provider's
|
|
83
|
-
prompt cache on every message. This one is built the other way around:
|
|
84
|
-
|
|
85
|
-
- **Epoch-frozen injection.** The "Relevant durable memory" block is computed
|
|
86
|
-
once per epoch — first prompt of a session, a change to the memory store, or
|
|
87
|
-
a compaction — and stays byte-identical in between. A stable system prefix
|
|
88
|
-
means the provider's prompt cache survives ordinary turns instead of being
|
|
89
|
-
invalidated on every message.
|
|
90
|
-
- **Two-concept evidence gate.** A free-text prompt must share at least two
|
|
91
|
-
distinct concepts with a memory for it to be injected; keyword-length
|
|
92
|
-
queries (one or two words — a deliberate search) need only one. Injection
|
|
93
|
-
stays quiet on single-word coincidences, which `memory_recall` still
|
|
94
|
-
reaches on the pull path — rare and right beats frequent and maybe.
|
|
95
|
-
- **Hard character budgets.** The relevance block and each contextual pull are
|
|
96
|
-
capped at 1200 characters by default; the session-start open-threads frontier
|
|
97
|
-
has its own 3600-character cap (see Options). All are trimmed at whole-memory
|
|
98
|
-
boundaries — never cut mid-sentence.
|
|
99
|
-
- **Evidence is never injected**, and the standing system digest is two lines.
|
|
100
|
-
- **Receipts, not promises.** The plugin measures your session's actual
|
|
101
|
-
prompt-cache usage (from each turn's `tokens.cache` accounting) and shows it
|
|
102
|
-
next to the badge — so a cache hit rate you can watch, not just a byte-freeze
|
|
103
|
-
claim you have to trust.
|
|
18
|
+
**2. Restart opencode.** It installs the package and its dependencies at startup, and the plugin installs its own slash commands.
|
|
104
19
|
|
|
105
|
-
|
|
106
|
-
store writes) using the plugin's real injection code:
|
|
20
|
+
**3. Run `/repo-init`** in each repo you work in. It indexes the code graph, stores the test / build / lint / typecheck commands as memories, and writes an init stamp tied to the current git head. Rerun `/repo-init force` after a refactor.
|
|
107
21
|
|
|
108
|
-
|
|
109
|
-
| --- | ---: | ---: | ---: | ---: |
|
|
110
|
-
| A — recompute per prompt, uncapped (naive) | 20 | 25742 | 1287.1 | 1838 |
|
|
111
|
-
| B — epoch freeze + 1200-char cap (shipped) | 4 | 19990 | 999.5 | 1139 |
|
|
22
|
+
Needs Bun 1.3.0 or newer in the opencode build (the tested floor); older Bun reports a startup warning.
|
|
112
23
|
|
|
113
|
-
|
|
114
|
-
the character count: B's block is byte-identical between store changes, so the
|
|
115
|
-
prompt cache stays warm across ordinary turns. Reproduce (byte-identical
|
|
116
|
-
output):
|
|
24
|
+
On opencode v2 the CLI works too:
|
|
117
25
|
|
|
118
26
|
```sh
|
|
119
|
-
|
|
27
|
+
opencode plugin add opencode-self-improvement
|
|
28
|
+
opencode plugin update opencode-self-improvement
|
|
120
29
|
```
|
|
121
30
|
|
|
122
|
-
|
|
31
|
+
After that, memory is just conversation: ask the agent to remember something and it sticks.
|
|
123
32
|
|
|
124
|
-
|
|
125
|
-
source tree, and GATE-2's stale-ref scan does the same for every memory in
|
|
126
|
-
the scope. The original resolver enumerated the whole tree (a glob pass per
|
|
127
|
-
extension, `node_modules` included) **per call form** — a write citing a few
|
|
128
|
-
symbols paid N full-tree scans: ~0.4s each in a small repo, seconds in a
|
|
129
|
-
monorepo. A write now builds one tree index — a single recursive walk that
|
|
130
|
-
prunes `node_modules`/VCS/dot dirs — shared by both gates, and source files
|
|
131
|
-
are read in bounded-parallel chunks and cached, so each file is read at most
|
|
132
|
-
once per write. Measured on a 5,300-file fixture (300 sources + 5,000
|
|
133
|
-
`node_modules` decoys), scope seeded with 5 embedded call forms:
|
|
33
|
+
## What you get
|
|
134
34
|
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
35
|
+
- **`memory_*` tools** — `memory_init`, `memory_remember`, `memory_recall`, `memory_update`, `memory_forget`, `memory_list`, `memory_undo`, `memory_status`, `memory_evidence`, `memory_export`, `memory_import`, `memory_decay`, `memory_consolidate`, `memory_merge_review`.
|
|
36
|
+
- **`/repo-init`** — per-repo setup: code graph index plus build/test commands, keyed to the git head.
|
|
37
|
+
- **Write gates** — code references are verified against your actual repo, near-duplicates are collapsed, contradictions with superseded memories are rejected. Blocked writes are logged with a reason in `memory_evidence`.
|
|
38
|
+
- **Memory-aware compaction** — durable memories are handed to the compaction summarizer, so a long session keeps its facts.
|
|
39
|
+
- **Auto-capture (opt-in)** — on the idle and compaction triggers, one cheap model pass per trigger proposes candidates, which face the same write gates; a 5-minute cooldown per session and trigger bounds the spend ([per-trigger numbers](bench/capture-trigger-results.md)). Off by default.
|
|
40
|
+
- **Repo scoping** — rows belong to the repo that wrote them; project A's facts never surface in project B.
|
|
41
|
+
- **Safe across concurrent sessions** — whole-file rewrites hold a per-file lock honored across processes and hand the new file over with an atomic rename.
|
|
42
|
+
- **Decay** — `memory_decay` retires stale open threads. Dry run by default, snapshot-first, undoable.
|
|
43
|
+
- **Consolidation** — `memory_consolidate` proposes near-duplicate merges, and only when replaying the store's own use ledger shows the merged row catches at least as many reads as the best single member. It writes nothing.
|
|
44
|
+
- **Export / import (JSONL)** — back the store up or move it between machines; every imported row re-enters through the write gates.
|
|
45
|
+
- **Surfaces** — a terminal footer badge and `/memory` panel, `/memory-report` for chat clients, a `memory_status` tool, and a browser admin editor. See [Surfaces](#surfaces).
|
|
46
|
+
- **Secret redaction** — credential-shaped values in content become `[redacted]`. See [Secret redaction](#secret-redaction).
|
|
47
|
+
|
|
48
|
+
Memory is stored outside every repository, under `~/.config/opencode/memory` by default (override with `OPENCODE_MEMORY_DIR`). To start over, delete that directory.
|
|
140
49
|
|
|
141
|
-
|
|
142
|
-
the write cites. In real `node_modules`-heavy repos the old per-form scan
|
|
143
|
-
measured 400–700ms, so the gap there is 20–100×. Reproduce:
|
|
50
|
+
## Options
|
|
144
51
|
|
|
145
|
-
|
|
146
|
-
|
|
52
|
+
Zero configuration is the default. To tune, use the object form of the plugin entry in `opencode.json(c)`:
|
|
53
|
+
|
|
54
|
+
```json
|
|
55
|
+
{
|
|
56
|
+
"plugins": [{ "package": "opencode-self-improvement", "options": { "injectBudget": 1200, "frontierBudget": 3600 } }]
|
|
57
|
+
}
|
|
147
58
|
```
|
|
148
59
|
|
|
149
|
-
|
|
60
|
+
| Option | Default | What it does |
|
|
61
|
+
| --- | --- | --- |
|
|
62
|
+
| `injectBudget` | `1200` | Character cap on the injected relevance block and each contextual pull; trimmed at whole-memory boundaries. Env fallback: `OPENCODE_MEMORY_INJECT_BUDGET`. |
|
|
63
|
+
| `frontierBudget` | `3 × injectBudget` | Character cap on the session-start open-threads block. A thread longer than the budget is not injected and is reported as omitted. Env fallback: `OPENCODE_MEMORY_FRONTIER_BUDGET`. |
|
|
64
|
+
| `autoCapture` | `false` | Master switch for auto-capture. Off by default, so the install stays zero-token. |
|
|
65
|
+
| `captureModel` | — | `"provider/id"` model used for auto-capture. Required when `autoCapture` is on; missing or invalid disables capture with a startup warning. |
|
|
66
|
+
| `captureMax` | `3` | Maximum candidates proposed per capture pass. |
|
|
67
|
+
| `captureOnCompact` | `true` | When `autoCapture` is on, also mine the transcript at compaction, before the summarizer replaces it. Its 5-minute cooldown is separate from the idle one, so the two triggers' hit-rates stay measurable. Setting it while `autoCapture` is off does nothing and reports a startup warning. |
|
|
68
|
+
| `notifyBlocked` | `true` | Terminal (TUI) only: toast when a write gate blocks a write. Blocks are always in `memory_evidence` either way. |
|
|
69
|
+
|
|
70
|
+
### Environment variables
|
|
71
|
+
|
|
72
|
+
| Variable | Purpose |
|
|
73
|
+
| --- | --- |
|
|
74
|
+
| `OPENCODE_MEMORY_DIR` | Store location (default `~/.config/opencode/memory`). |
|
|
75
|
+
| `OPENCODE_MEMORY_INJECT_BUDGET` | Fallback for `injectBudget`. |
|
|
76
|
+
| `OPENCODE_MEMORY_FRONTIER_BUDGET` | Fallback for `frontierBudget`. |
|
|
77
|
+
| `OPENCODE_COMMANDS_DIR` | Where the plugin mirrors its slash commands (default `~/.config/opencode/commands`). |
|
|
78
|
+
| `OPENCODE_CBM_BIN` | Path to a `codebase-memory-mcp` binary. See [Code graph](#code-graph-optional). |
|
|
79
|
+
| `OPENCODE_VIEWER_PORT` | Admin editor port (default `8787`). |
|
|
80
|
+
| `OPENCODE_VIEWER_ALLOWED_HOSTS` | Comma-separated hosts beyond loopback. See [Surfaces](#surfaces). |
|
|
81
|
+
|
|
82
|
+
## How memory is written
|
|
83
|
+
|
|
84
|
+
Four gates run before anything is stored, and each emits an ordered evidence line:
|
|
85
|
+
|
|
86
|
+
1. **GATE-1 — code references resolve.** Call signatures and paths embedded in the memory are checked against your live source tree.
|
|
87
|
+
2. **GATE-2 — no stale memory applies here.** References that drifted out of date are superseded or the write is blocked.
|
|
88
|
+
3. **GATE-3 — no duplicates.** Near-duplicates collapse into the existing row; a contradiction with a superseded memory is rejected.
|
|
89
|
+
4. **GATE-4 — promotion or block.** The row lands, or the call returns the reason.
|
|
90
|
+
|
|
91
|
+
Nothing is deleted: `memory_update` supersedes the previous row, `memory_forget` records a retirement, and `memory_undo` restores a snapshot. `memory_update` takes a `query` that picks the row — its id, a clock fragment such as `00:11:22.123`, or a unique substring of its text. Omit it to update the newest entry of that scope and type. A `query` that matches nothing, or several rows, writes nothing and says so.
|
|
150
92
|
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
93
|
+
## Repo scoping
|
|
94
|
+
|
|
95
|
+
Rows are stamped with your git origin (an id that survives re-clones and moves between machines) or, without an origin, a hash of the normalized directory path. `repoPath` keeps the human-readable path, so rows written before hashing keep matching.
|
|
96
|
+
|
|
97
|
+
Injection, recall, the frontier block, compaction, `memory_forget` and decay only see the current repo plus global rows. Preferences that should follow you everywhere go in with `memory_remember global: true`. Rows written before scoping existed, and rows restored through the viewer, are global — upgrading changes nothing.
|
|
98
|
+
|
|
99
|
+
## Token cost and caching
|
|
100
|
+
|
|
101
|
+
- **Epoch-frozen injection.** The relevance block is computed once per epoch — first prompt of a session, a change to the store, or a compaction — and stays byte-identical in between, so the provider's prompt cache survives ordinary turns.
|
|
102
|
+
- **Two-concept threshold.** A free-text prompt must share at least two distinct concepts with a memory for it to be injected; keyword-length queries (one or two words) need only one. Silence on single-word coincidences is deliberate; `memory_recall` still reaches them on the pull path.
|
|
103
|
+
- **Hard budgets.** Relevance block and each pull are capped at `injectBudget` characters, the frontier at `frontierBudget`, trimmed at whole-memory boundaries.
|
|
104
|
+
- **Evidence is never injected**, and the standing system digest is two lines.
|
|
105
|
+
- **Measured, not claimed.** The plugin reads each turn's `tokens.cache` accounting and displays the actual hit rate next to the badge.
|
|
106
|
+
|
|
107
|
+
Deterministic workload (50 memories, 20 prompts, 3 mid-session store writes) through the plugin's real injection code:
|
|
108
|
+
|
|
109
|
+
| Policy | Recomputes | Injected chars (20 turns) | Avg/turn | Worst block |
|
|
110
|
+
| --- | ---: | ---: | ---: | ---: |
|
|
111
|
+
| A — recompute per prompt, uncapped | 20 | 25742 | 1287.1 | 1838 |
|
|
112
|
+
| B — epoch freeze + 1200-char cap (shipped) | 4 | 19990 | 999.5 | 1139 |
|
|
113
|
+
|
|
114
|
+
Policy B injects 22.3% fewer characters, and its block is byte-identical between store changes so the prompt cache stays warm. Reproduce (byte-identical output):
|
|
155
115
|
|
|
156
116
|
```sh
|
|
157
|
-
bun bench
|
|
117
|
+
bun run bench
|
|
158
118
|
```
|
|
159
119
|
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
120
|
+
## Recall quality
|
|
121
|
+
|
|
122
|
+
No vector database, no embedding model, no API key. What the keyword matcher gives up, measured against classic BM25 on a deterministic eval (store of 200, k=3 — the production injection limit):
|
|
163
123
|
|
|
164
124
|
| Query, vs. the stored memory | share | R@1 | R@3 | with `kw` R@1 | with `kw` R@3 |
|
|
165
125
|
| --- | ---: | ---: | ---: | ---: | ---: |
|
|
@@ -167,51 +127,38 @@ right memory (store of 200; k=3 = the production injection limit):
|
|
|
167
127
|
| near — reworded, one overlap | 17% | 28% | 28% | 67% | 72% |
|
|
168
128
|
| strict — zero shared words | 37% | 0% | 0% | 26% | 26% |
|
|
169
129
|
|
|
170
|
-
"with `kw`" is the same matcher over the same store
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
- **
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
- Caveats, honestly: the dataset is synthetic (52 memories / 105 queries, a
|
|
203
|
-
fictional project), its class mix is deliberately adversarial (far richer in
|
|
204
|
-
zero-overlap paraphrases than real prompts), and scoring is single-gold.
|
|
205
|
-
|
|
206
|
-
Full methodology, all store sizes: `bench/recall-results.md`
|
|
207
|
-
(regenerate with `bun bench:recall`).
|
|
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:
|
|
130
|
+
"with `kw`" is the same matcher over the same store with each row's write-time keywords indexed; the only changed variable is the index.
|
|
131
|
+
|
|
132
|
+
- **In-project prompts are overwhelmingly lexical** (`bun test`, "the rate limiter", "staging deploys"): 98–100% R@3, flat from store size 50 to 500.
|
|
133
|
+
- **Single-overlap guessing was traded away.** Free-text prompts that share one concept abstain rather than force a guess; wrong top-memory fell to 6%. `memory_recall` still covers them.
|
|
134
|
+
- **Zero-overlap paraphrase is the real limit, and write time is where it is answered.** `memory_remember` and auto-capture ask each row for 3–5 `kw` aliases (other names, other verb forms, the literal command); they are indexed and never rendered. Strict R@1 0% → 26%, near R@1 28% → 67%. A permutation control (every row given someone else's aliases) scores 29%/35%, so the gain is meaning rather than extra tokens. The limit is narrowed, not removed.
|
|
135
|
+
- **Caveats.** The dataset is synthetic (52 memories / 105 queries, a fictional project), its class mix is deliberately adversarial, and scoring is single-gold.
|
|
136
|
+
|
|
137
|
+
Full methodology and all store sizes: `bench/recall-results.md`.
|
|
138
|
+
|
|
139
|
+
```sh
|
|
140
|
+
bun run bench:recall
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
## Write latency
|
|
144
|
+
|
|
145
|
+
A write that cites code references builds one tree index — a single recursive walk that prunes `node_modules` and VCS directories — shared by GATE-1 and GATE-2, and reads each source file at most once. Measured on a 5,300-file fixture (300 sources + 5,000 `node_modules` decoys), scope seeded with 5 embedded call forms:
|
|
146
|
+
|
|
147
|
+
| Call forms in the write | Shipped | One scan per form |
|
|
148
|
+
| --- | ---: | ---: |
|
|
149
|
+
| 1 | 17ms | 105ms |
|
|
150
|
+
| 3 | 15ms | 136ms |
|
|
151
|
+
| 5 | 20ms | 169ms |
|
|
152
|
+
|
|
153
|
+
The shipped column is flat: the tree is walked once no matter how many references the write cites.
|
|
154
|
+
|
|
155
|
+
```sh
|
|
156
|
+
bun run bench:write
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
## The store keeps score
|
|
160
|
+
|
|
161
|
+
The plugin keeps a **use ledger** (`<memory-root>/hits.logfmt`, append-only, rotated at 2 MB, never ingested as a memory) and reports it in `memory_status` and the `/memory` panel:
|
|
215
162
|
|
|
216
163
|
```
|
|
217
164
|
STORE
|
|
@@ -220,314 +167,131 @@ STORE
|
|
|
220
167
|
24.1 KB total · 604 B per row · 1.3 rows/day (30d) · capture lag p50 42 s / p95 6 min
|
|
221
168
|
```
|
|
222
169
|
|
|
223
|
-
- **
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
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.
|
|
170
|
+
- **Credit comes from three distinct sources** — the row rode the injected block, `memory_recall` returned it, or a grep/read pull appended it — because "the model asked" and "the harness offered" are different facts. Credit requires ≥2 shared terms with the query and is throttled to one line per memory per session per source per hour.
|
|
171
|
+
- **No prompt content is stored.** The ledger keeps a scan-truncated string from the *memory* side, never your message.
|
|
172
|
+
- **Reinforcement is a tie-break only** (`useBoost ≤ 1.0`): a recently used row wins a tie and can never outrank a real score gap. In consolidation the most recently used member of a cluster is never the merge loser.
|
|
173
|
+
- **`never retrieved` is stated, not acted on.** Pruning is your decision. Retired rows cannot inherit reinforcement: ledger rows are verified against the store on read.
|
|
239
174
|
- **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
175
|
|
|
275
|
-
##
|
|
176
|
+
## Consolidation
|
|
276
177
|
|
|
277
|
-
|
|
278
|
-
2. In any repo, run:
|
|
178
|
+
`memory_consolidate` finds near-duplicates and proposes merges. It writes nothing; each proposal prints the exact `memory_merge_review` call that resolves it, and resolving is supersede-not-delete.
|
|
279
179
|
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
```
|
|
180
|
+
- **Deterministic.** The canonical row is the survivor's prose verbatim plus the absorbed rows' aliases as keywords. No model rewrites anything.
|
|
181
|
+
- **Proven by recorded reads.** Every read the ledger recorded for a cluster is replayed against the merged store, and a merge is proposed only when the canonical row catches at least as many of the cluster's own reads as the best single member did alone. A cluster with no recorded reads is reported as *unmeasured* and never merged on resemblance.
|
|
283
182
|
|
|
284
|
-
|
|
183
|
+
On the eval dataset the pass takes 200 rows to 52 with **R@3 52 → 53 and R@1 52 → 50**, and store-wide injected characters 25 945c → 6 933c. Both the regression and the budget swap are bounded in CI (`test/consolidate-bench.test.ts`).
|
|
285
184
|
|
|
286
|
-
##
|
|
185
|
+
## Secret redaction
|
|
287
186
|
|
|
288
|
-
|
|
289
|
-
`~/.config/opencode/opencode.jsonc` (global) or any project `opencode.jsonc`:
|
|
187
|
+
One best-effort credential rule set (`src/secrets.ts`) runs over the auto-capture prompt before it leaves the plugin, at the write gate before content is hashed or analysed, and again in the final write choke point used by gated writes and the viewer's edit and restore paths.
|
|
290
188
|
|
|
291
|
-
|
|
292
|
-
{
|
|
293
|
-
"$schema": "https://opencode.ai/config.json",
|
|
294
|
-
"plugins": ["opencode-self-improvement"]
|
|
295
|
-
}
|
|
296
|
-
```
|
|
297
|
-
|
|
298
|
-
Opencode installs the package (and its dependencies) automatically with Bun at
|
|
299
|
-
startup. Quit and restart opencode; the plugin loads and `/repo-init` installs
|
|
300
|
-
itself. Nothing else to do.
|
|
189
|
+
Covered: OpenAI `sk-`, GitHub `ghp_` / `gho_` / `github_pat_`, Slack `xoxb-` / `xoxp-`, AWS `AKIA`, Google `AIza`, bearer tokens containing digits, PEM private-key blocks, and high-entropy values assigned to names ending in `_KEY`, `_TOKEN`, `_SECRET` or `_PASSWORD` (plus `password`).
|
|
301
190
|
|
|
302
|
-
|
|
303
|
-
older than 1.3.0 (this repo's tested floor) the plugin says so once at startup
|
|
304
|
-
and memory features may misbehave.
|
|
191
|
+
Limits worth knowing:
|
|
305
192
|
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
for what's current — and bump it when you want to move. On Opencode v2 you
|
|
311
|
-
can also manage it with the CLI:
|
|
193
|
+
- It can miss hex-only secrets, low-diversity passwords, and credentials written in prose without an assignment.
|
|
194
|
+
- Credential-shaped `scope`, `tags` or `issue` metadata is rejected rather than silently rewritten.
|
|
195
|
+
- `memory_remember` still replies `Remembered` when content was redacted, so the stored text can differ from what was sent.
|
|
196
|
+
- Redaction is forward-only: existing stores are not scrubbed, and `memory_export` writes what is already stored verbatim.
|
|
312
197
|
|
|
313
|
-
|
|
314
|
-
opencode plugin add opencode-self-improvement
|
|
315
|
-
opencode plugin update opencode-self-improvement
|
|
316
|
-
```
|
|
198
|
+
## Export and move between machines
|
|
317
199
|
|
|
318
|
-
|
|
319
|
-
<summary>Install from a clone (development)</summary>
|
|
200
|
+
`memory_export` writes the live store as JSONL: a machine-readable header line (`{_export, version, exportedAt, count}`) followed by one JSON object per line (`{ts,type,scope,content,status,tags,issue}`), active rows only. `memory_import` reads such a file back. Default path is `<memory-root>/exports/<timestamp>.jsonl`; pass `file` to choose one and `scope` to export a single scope.
|
|
320
201
|
|
|
321
|
-
```sh
|
|
322
|
-
git clone https://github.com/abogartz/opencode-self-improvement.git
|
|
323
|
-
cd opencode-self-improvement
|
|
324
|
-
bun install
|
|
325
202
|
```
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
```json
|
|
330
|
-
{
|
|
331
|
-
"$schema": "https://opencode.ai/config.json",
|
|
332
|
-
"plugins": ["/full/path/to/opencode-self-improvement/index.ts"]
|
|
333
|
-
}
|
|
203
|
+
Export my memories to ~/memories.jsonl # memory_export
|
|
204
|
+
# …copy the file to the other machine…
|
|
205
|
+
Import ~/memories.jsonl # memory_import
|
|
334
206
|
```
|
|
335
207
|
|
|
336
|
-
|
|
208
|
+
Every imported row re-enters through the same four gates as `memory_remember` (tagged `import`, original tags preserved), and the tool reports a tally:
|
|
337
209
|
|
|
338
|
-
|
|
210
|
+
| Outcome | Meaning |
|
|
211
|
+
| --- | --- |
|
|
212
|
+
| `promoted` | passed the gates and was stored |
|
|
213
|
+
| `collapsed` | near-duplicate of an existing memory; nothing written |
|
|
214
|
+
| `blocked` | rejected by a gate; reason in `memory_evidence` |
|
|
215
|
+
| `skipped` | malformed line; never reached the gates |
|
|
216
|
+
| `downgraded` | imported as settled because its `status:"open"` could not be vouched for |
|
|
339
217
|
|
|
340
|
-
|
|
218
|
+
An open row is exempt from reference grounding, so that status is honored only for files carrying an export header. Even with a header: an open row claiming `repo:"global"` is downgraded, and imported `repo` / `repoPath` stamps are kept only when they match the importing session's current repo — foreign stamps are dropped and the row is stamped for the importing repo. Re-running the same import in the same repo is a no-op.
|
|
341
219
|
|
|
342
|
-
|
|
343
|
-
`test`, `smoke`), and the same sequence is one command locally:
|
|
220
|
+
## Surfaces
|
|
344
221
|
|
|
345
|
-
|
|
346
|
-
bun run gate # typecheck + lint + unit tests + terminal smoke & BDD
|
|
347
|
-
bun run gate:hooks # once per clone: run the gate automatically on `git push`
|
|
348
|
-
```
|
|
222
|
+
Same data behind each one (`memory_status`; no model call).
|
|
349
223
|
|
|
350
|
-
**
|
|
351
|
-
a BDD scenario in `e2e/` describing the behavior as a user would observe it —
|
|
352
|
-
before any implementation code and before unit tests. Then write the unit
|
|
353
|
-
tests for the pieces, then the code until everything is green. If no scenario
|
|
354
|
-
turns red first, the feature has no observable contract.
|
|
355
|
-
|
|
356
|
-
The `e2e/` suite is what keeps a load-error release from shipping again: it
|
|
357
|
-
boots the **real opencode CLI** against each candidate in a fully isolated
|
|
358
|
-
instance (fresh config, fresh db, fresh memory store, empty `HOME`) driven by
|
|
359
|
-
a scripted OpenAI-compatible fake model — no API keys anywhere. Scenarios
|
|
360
|
-
cover loading from the source tree and from the **packed npm artifact
|
|
361
|
-
installed runtime-deps-only** (the same semantics as opencode's plugin
|
|
362
|
-
cache), plus BDD flows for remember, recall, exact duplicates, near duplicates,
|
|
363
|
-
ungrounded claims, and forget. Needs `opencode` on `PATH` locally (or set
|
|
364
|
-
`OPENCODE_BIN`).
|
|
224
|
+
**Terminal (opencode CLI)** — the plugin ships a TUI half (`@opencode/plugin/tui`) that loads automatically:
|
|
365
225
|
|
|
366
|
-
|
|
226
|
+
- **Footer badge** — `● mem 1157/1200c · cache 96%`: the injected block against its budget, plus the measured session prompt-cache hit rate. The dot is green (stable and warm), yellow (recent recompute, or 50–90% reads) or red (last turn served almost nothing from cache); `—` until the first assistant turn.
|
|
227
|
+
- **`/memory`** — session panel: **CONTEXT** (chars and estimated tokens riding now, % of budget, requests this epoch has ridden, session totals, abstentions), **CACHE** (busts this session and the measured cache-served share of prompt tokens), **INJECTED BLOCK** (the verbatim block, or an explicit abstention), **RECENT BLOCKED WRITES** (with gate reasons), **STORE** (active / superseded / open / scopes, plus `malformed` when a row's `ts` is not a valid ISO instant — those rows are skipped by every reader). Keys: `r` refresh, `f` fullscreen.
|
|
228
|
+
- **Block toast** when a write is refused (`"notifyBlocked": false` to silence).
|
|
367
229
|
|
|
368
|
-
|
|
369
|
-
the plugin entry in `opencode.json(c)` instead of the plain string:
|
|
230
|
+
**Desktop / web / IDE** — the terminal slots do not exist there, so use the self-installed **`/memory-report`** chat command: the same sections rendered in the conversation.
|
|
370
231
|
|
|
371
|
-
|
|
372
|
-
{
|
|
373
|
-
"plugins": [{ "package": "opencode-self-improvement", "options": { "injectBudget": 1200, "frontierBudget": 3600 } }]
|
|
374
|
-
}
|
|
375
|
-
```
|
|
376
|
-
|
|
377
|
-
| Option | Default | What it does |
|
|
378
|
-
| --- | --- | --- |
|
|
379
|
-
| `injectBudget` | `1200` | Character cap on the injected relevance block and each contextual pull; trimmed at whole-memory boundaries. Env fallback: `OPENCODE_MEMORY_INJECT_BUDGET`. |
|
|
380
|
-
| `frontierBudget` | `3 × injectBudget` (`3600` by default) | Character cap on the session-start open-threads block. A thread longer than this budget is not injected and is visibly reported as omitted; raise this option (or `OPENCODE_MEMORY_FRONTIER_BUDGET`) to include longer planning threads. |
|
|
381
|
-
| `autoCapture` | `false` (off) | When on, each session-idle event makes one cheap model pass that proposes memory candidates. Every candidate still goes through the 4-gate write pipeline — capture can never bypass the gates. Off by default: the zero-token install stays zero-token. |
|
|
382
|
-
| `captureModel` | — | `"provider/id"` model used for auto-capture. Required when `autoCapture` is on; a missing or invalid value disables capture with a startup warning. |
|
|
383
|
-
| `captureMax` | `3` | Maximum candidates proposed per idle event. |
|
|
384
|
-
| `notifyBlocked` | `true` (on) | Terminal (TUI) half only: toast when the write gate blocks a memory write. `false` keeps the panel quiet; blocks are always in `memory_evidence` regardless. |
|
|
232
|
+
**Browser editor** — `bun memory-view`, then http://127.0.0.1:8787. Bound to loopback; requests are checked against `Host` and `Origin`, so other hosts must be listed explicitly in `OPENCODE_VIEWER_ALLOWED_HOSTS`. Listing a non-loopback host serves the store over plain HTTP with no authentication — only do it on a network you control.
|
|
385
233
|
|
|
386
234
|
## Code graph (optional)
|
|
387
235
|
|
|
388
|
-
`/repo-init` also indexes the repo into a queryable knowledge graph via
|
|
389
|
-
[`codebase-memory-mcp`](https://github.com/DeusData/codebase-memory-mcp),
|
|
390
|
-
pinned to `0.11.0` as an optional dependency, so opencode's auto-install at
|
|
391
|
-
startup brings it in. If a copy is already on your `PATH`, that one is used
|
|
392
|
-
instead; override explicitly with `OPENCODE_CBM_BIN=/path/to/codebase-memory-mcp`.
|
|
393
|
-
When no graph binary is available, `/repo-init` still records scripts and the
|
|
394
|
-
init stamp — the graph is a lookup bonus, not a requirement (see below).
|
|
395
|
-
|
|
396
|
-
Manual install of the pinned binary (if you want it globally):
|
|
236
|
+
`/repo-init` also indexes the repo into a queryable knowledge graph via [`codebase-memory-mcp`](https://github.com/DeusData/codebase-memory-mcp), pinned to `0.11.0` as an optional dependency. A copy already on your `PATH` is used instead; override with `OPENCODE_CBM_BIN=/path/to/codebase-memory-mcp`. Install the pinned binary globally if you prefer:
|
|
397
237
|
|
|
398
238
|
```sh
|
|
399
239
|
curl -fsSL https://raw.githubusercontent.com/DeusData/codebase-memory-mcp/main/install.sh | bash
|
|
400
240
|
```
|
|
401
241
|
|
|
402
|
-
|
|
242
|
+
When no graph binary is available, `/repo-init` still records scripts and the init stamp.
|
|
403
243
|
|
|
404
|
-
|
|
244
|
+
## Installing a specific version
|
|
405
245
|
|
|
406
|
-
-
|
|
407
|
-
|
|
408
|
-
|
|
246
|
+
An unpinned entry resolves `@latest` exactly once and is never re-resolved afterwards, so updates are deliberate: `opencode plugin update opencode-self-improvement`. To pin, append `@<version>` — see [npm](https://www.npmjs.com/package/opencode-self-improvement) for what is current.
|
|
247
|
+
|
|
248
|
+
<details>
|
|
249
|
+
<summary>Install from a clone (development)</summary>
|
|
409
250
|
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
251
|
+
```sh
|
|
252
|
+
git clone https://github.com/abogartz/opencode-self-improvement.git
|
|
253
|
+
cd opencode-self-improvement
|
|
254
|
+
bun install
|
|
255
|
+
```
|
|
415
256
|
|
|
416
|
-
|
|
417
|
-
as `00:11:25.867`, or a unique substring of its text. Omit it to update the newest
|
|
418
|
-
entry of that scope and type. A `query` matching nothing, or matching several rows,
|
|
419
|
-
writes nothing and says so rather than updating the wrong memory.
|
|
257
|
+
Then point the `plugins` entry at the local file instead:
|
|
420
258
|
|
|
421
|
-
|
|
259
|
+
```json
|
|
260
|
+
{
|
|
261
|
+
"$schema": "https://opencode.ai/config.json",
|
|
262
|
+
"plugins": ["/full/path/to/opencode-self-improvement/index.ts"]
|
|
263
|
+
}
|
|
264
|
+
```
|
|
422
265
|
|
|
423
|
-
|
|
424
|
-
remote (an id that survives re-clones and moves between machines) or, with no
|
|
425
|
-
remote, the repo path. Injection, recall, the frontier block, compaction,
|
|
426
|
-
`memory_forget`, and decay only ever see the current repo plus global rows —
|
|
427
|
-
project A's facts never surface in project B. Preferences and habits that
|
|
428
|
-
should follow you everywhere go in with `memory_remember global: true`.
|
|
429
|
-
Memories written before this existed, and ones restored through the viewer,
|
|
430
|
-
are global (visible everywhere), so upgrading changes nothing; exports carry
|
|
431
|
-
origin stamps, so scoping survives a machine hop.
|
|
266
|
+
After changes, `git pull` and restart opencode.
|
|
432
267
|
|
|
433
|
-
|
|
268
|
+
</details>
|
|
434
269
|
|
|
435
|
-
|
|
436
|
-
(`{_export, version, exportedAt, count}`) followed by one JSON object per line
|
|
437
|
-
(`{ts,type,scope,content,status,tags,issue}`), active rows only (superseded
|
|
438
|
-
history stays in the store). `memory_import` reads such a file back. Defaults
|
|
439
|
-
to `<memory-root>/exports/<timestamp>.jsonl`; pass `file` to choose the path
|
|
440
|
-
and `scope` to export just one scope.
|
|
270
|
+
## Development
|
|
441
271
|
|
|
442
|
-
|
|
272
|
+
Nothing merges without the full gate; CI runs it as required checks (`lint`, `test`, `smoke`), and the same sequence is one command locally:
|
|
443
273
|
|
|
444
|
-
```
|
|
445
|
-
|
|
446
|
-
#
|
|
447
|
-
Import ~/memories.jsonl # memory_import
|
|
274
|
+
```sh
|
|
275
|
+
bun run gate # typecheck + lint + unit tests + terminal smoke & BDD
|
|
276
|
+
bun run gate:hooks # once per clone: run the gate on `git push`
|
|
448
277
|
```
|
|
449
278
|
|
|
450
|
-
|
|
451
|
-
write pipeline as `memory_remember` (tagged `import`, original tags preserved),
|
|
452
|
-
and the tool reports a tally of outcomes per line —
|
|
279
|
+
**Feature order is BDD-first.** A new feature starts by adding or fixing a scenario in `e2e/` that describes the behavior as a user would observe it — before implementation code and before unit tests. Then the unit tests for the pieces, then the code until everything is green. If no scenario turns red first, the feature has no observable contract.
|
|
453
280
|
|
|
454
|
-
|
|
455
|
-
| --- | --- |
|
|
456
|
-
| `promoted` | passed the gates and was stored |
|
|
457
|
-
| `collapsed` | near-duplicate of an existing memory; nothing written |
|
|
458
|
-
| `blocked` | rejected by a gate; reason is in `memory_evidence` |
|
|
459
|
-
| `skipped` | malformed line; never reaches the gates |
|
|
460
|
-
| `downgraded` | `status:"open"` without an export header to vouch for it, claiming `repo:"global"`, or carrying an unverifiable stamp when the importing session has no repo scope; imported as settled |
|
|
461
|
-
|
|
462
|
-
The frontier policy matters because an open row is exempt from ref grounding:
|
|
463
|
-
a hand-written JSONL can't hand its rows that free pass (the header is
|
|
464
|
-
friction, not a signature — the real defense is that imported content always
|
|
465
|
-
injects framed as data and marked `[via import]`). Even with a header, an
|
|
466
|
-
imported open row claiming `repo:"global"` is downgraded, so one file can't add
|
|
467
|
-
an open thread to every repo. Imported `repo` and `repoPath` stamps are honored
|
|
468
|
-
only when they match the importing session's current repo (an explicit
|
|
469
|
-
`repo:"global"` on a settled row is kept); foreign stamps are discarded and the
|
|
470
|
-
row is stamped for the importing repo instead. When there is no current repo
|
|
471
|
-
scope, stamps are kept as they are (dropping them would widen the row to
|
|
472
|
-
global) and a stamped open row is downgraded, since its stamp can't be verified.
|
|
473
|
-
|
|
474
|
-
So re-running the same import in the same repo is a no-op (everything
|
|
475
|
-
collapses). Copying an export to a fresh machine and importing it from that
|
|
476
|
-
repo is how you seed a new laptop from an old one.
|
|
477
|
-
|
|
478
|
-
## Memory at a glance
|
|
479
|
-
|
|
480
|
-
"Wait, what did the memory plugin just do?" — answered differently per client,
|
|
481
|
-
same data (`memory_status` tool under the hood; no model call):
|
|
482
|
-
|
|
483
|
-
**Terminal (opencode CLI)** — the plugin ships a TUI half
|
|
484
|
-
(`@opencode/plugin/tui`) that loads automatically:
|
|
485
|
-
|
|
486
|
-
- a footer badge: `● mem 1157/1200c · cache 96%` — the injected block against
|
|
487
|
-
its budget, and the measured session prompt-cache hit rate. The dot is green
|
|
488
|
-
(stable + warm), yellow (a recent recompute, or 50–90% reads), or red (last
|
|
489
|
-
turn served almost nothing from cache). `—` until the first assistant turn.
|
|
490
|
-
- **`/memory`** opens a session panel (every number is this session only):
|
|
491
|
-
- **CONTEXT** — exact chars + estimated tokens riding now, % of the budget,
|
|
492
|
-
requests the current epoch has ridden, session-lifetime totals, and how
|
|
493
|
-
many requests abstained (silence is a feature)
|
|
494
|
-
- **CACHE** — the receipts, in plain language: cache busts this session
|
|
495
|
-
(0 = memory has never rewritten a byte of your history), the measured
|
|
496
|
-
share of prompt tokens the provider served from cache (≥90% reads =
|
|
497
|
-
"memory is cache-invisible"), or — when the provider reports no usage at
|
|
498
|
-
all — the structural proof instead: the same block bytes rode every
|
|
499
|
-
request with zero busts
|
|
500
|
-
- **INJECTED BLOCK** — the verbatim block riding your prompts, or an explicit
|
|
501
|
-
"abstained: no vocabulary overlap"
|
|
502
|
-
- **RECENT BLOCKED WRITES** — that `memory_remember` that didn't stick,
|
|
503
|
-
with its gate reason
|
|
504
|
-
- **STORE** — active / superseded / open / scopes (plus `malformed`, only when the store contains rows whose `ts` is not a valid ISO instant — those are skipped by every reader, never loaded)
|
|
505
|
-
- keys: `r` refresh, `f` fullscreen
|
|
506
|
-
- a warning toast when a write is blocked (opt out: `"notifyBlocked": false`)
|
|
507
|
-
|
|
508
|
-
**Desktop / web / IDE** — no TUI slots there (they're terminal-only), so use
|
|
509
|
-
the self-installed **`/memory-report`** chat command: the same four sections,
|
|
510
|
-
rendered in the conversation. For editing, the browser admin (`bun memory-view`)
|
|
511
|
-
works everywhere.
|
|
512
|
-
|
|
513
|
-
## Admin Tool
|
|
514
|
-
|
|
515
|
-
Editing and deleting memories is easy!
|
|
516
|
-
|
|
517
|
-
Run `bun memory-view` in your terminal and visit http://127.0.0.1:8787 in your browser.
|
|
281
|
+
`e2e/` boots the **real opencode CLI** against each candidate in a fully isolated instance (fresh config, fresh db, fresh memory store, empty `HOME`) driven by a scripted OpenAI-compatible fake model — no API keys. It covers loading from the source tree and from the packed npm artifact installed runtime-deps-only, plus BDD flows for remember, recall, exact and near duplicates, ungrounded claims, and forget. Needs `opencode` on `PATH` locally, or set `OPENCODE_BIN`. A `test-windows` leg also runs the suite on Windows; it reports without gating merges.
|
|
518
282
|
|
|
519
283
|
## Troubleshooting
|
|
520
284
|
|
|
521
285
|
| Problem | Fix |
|
|
522
286
|
| --- | --- |
|
|
523
287
|
| `memory_*` tools not available | The plugin didn't load. Restart opencode and check the `plugins` entry in your config. |
|
|
524
|
-
| `memory_remember` says blocked | A gate rejected the write
|
|
525
|
-
| `invalid arguments to memory_*` | The
|
|
526
|
-
| STORE shows `N malformed` |
|
|
527
|
-
| `memory store is busy
|
|
528
|
-
|
|
|
529
|
-
|
|
|
530
|
-
|
|
|
531
|
-
|
|
|
288
|
+
| `memory_remember` says blocked | A gate rejected the write: a stale code reference, a cited path that doesn't exist in the repo, overlap with a superseded memory, or an ambiguous claim. The reason is in `memory_evidence`; rephrase against current code and retry. |
|
|
289
|
+
| `invalid arguments to memory_*` | The call didn't match the tool's input schema; nothing was done and the message names the offending fields. Gate blocks look different (`blocked at GATE (…)`). |
|
|
290
|
+
| STORE shows `N malformed` | A daily file has a `ts=` that is not a valid ISO instant (typically a hand-edit). Every reader skips those rows; fix the `ts=` or restore the file with `memory_undo`. |
|
|
291
|
+
| `memory store is busy` | Another session or the viewer held that store file for over 5s. Ordinary writes proceed anyway; only `memory_undo` and the viewer's restore refuse, because a forced rollback under a live writer would drop rows. Retry. A lock left by a killed process is taken over after 10s. |
|
|
292
|
+
| Stray `*.logfmt.lock` or `*.tmp` in the store | Write bookkeeping; safe to delete while nothing is writing. |
|
|
293
|
+
| `/repo-init` missing from the command list | The self-install couldn't write to `~/.config/opencode/commands/`. Create it and restart, or ask the model to "init memory for this repo" — the same tool. |
|
|
294
|
+
| Init says `Graph: unavailable` | `codebase-memory-mcp` couldn't start. Install pinned `0.11.0` or point `OPENCODE_CBM_BIN` at the binary. Scripts are still remembered without it. |
|
|
295
|
+
| Stale plugin after an update | `opencode plugin update opencode-self-improvement` (or bump the pinned `@version` in the `plugins` entry) and restart opencode. |
|
|
296
|
+
| Auto-capture does nothing | `autoCapture` needs a valid `captureModel` in `provider/id` form; a bad one disables capture with a startup warning. `captureOnCompact` alone does nothing. Rejected candidates are logged as evidence, not errors — check `memory_evidence`. |
|
|
532
297
|
| Reset all memories | Delete `~/.config/opencode/memory/`. |
|
|
533
|
-
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-self-improvement",
|
|
3
|
-
"version": "0.14.
|
|
3
|
+
"version": "0.14.3",
|
|
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/hits.ts
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
// already exists inside that row.
|
|
17
17
|
import { join } from "node:path";
|
|
18
18
|
import { memoryRoot, HITS_FILENAME } from "./config.ts";
|
|
19
|
-
import { appendLog, bracketList, formatLine, parseLine, readLines, writeAtomic } from "./logfmt.ts";
|
|
19
|
+
import { appendLog, bracketList, fileIdentity, formatLine, parseLine, readLines, writeAtomic } from "./logfmt.ts";
|
|
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";
|
|
@@ -66,8 +66,12 @@ async function rotateIfNeeded(): Promise<void> {
|
|
|
66
66
|
const file = Bun.file(hitsFile());
|
|
67
67
|
const size = await file.size;
|
|
68
68
|
if (size <= MAX_HITS_BYTES) return;
|
|
69
|
+
// #106: anchor the halving like every other whole-file publish (#89) - on
|
|
70
|
+
// Windows the rename can be refused by a reader's handle, and the retry is
|
|
71
|
+
// only safe while nothing else moved this file.
|
|
72
|
+
const since = await fileIdentity(hitsFile());
|
|
69
73
|
const lines = (await file.text()).split("\n").filter((l) => l.trim());
|
|
70
|
-
await writeAtomic(hitsFile(), lines.slice(Math.floor(lines.length / 2)).join("\n") + "\n");
|
|
74
|
+
await writeAtomic(hitsFile(), lines.slice(Math.floor(lines.length / 2)).join("\n") + "\n", since);
|
|
71
75
|
}
|
|
72
76
|
|
|
73
77
|
/**
|
package/src/index.ts
CHANGED
|
@@ -196,6 +196,34 @@ const CAPTURE_COMPACT_TAG = "auto_capture_compaction";
|
|
|
196
196
|
// more than one location).
|
|
197
197
|
let bunFloorChecked = false;
|
|
198
198
|
|
|
199
|
+
// Auto-capture cooldown, shared by EVERY setup() registration (#108): setup
|
|
200
|
+
// runs for more than one location, and per-closure cooldown maps made those
|
|
201
|
+
// registrations strangers - one compaction could pay for two model calls on
|
|
202
|
+
// one transcript. Same module-level shape as `turns` in src/lock.ts; the key
|
|
203
|
+
// names the trigger, so measuring one trigger is still not confounded by the
|
|
204
|
+
// other having fired moments ago.
|
|
205
|
+
const lastCaptureRun = new Map<string, number>();
|
|
206
|
+
|
|
207
|
+
const CAPTURE_COOLDOWN_MS = 5 * 60_000;
|
|
208
|
+
|
|
209
|
+
/** True if this trigger may fire for this session now; records the fire. */
|
|
210
|
+
function captureCooldownPasses(trigger: "idle" | "compaction", sid: string, now: number): boolean {
|
|
211
|
+
const key = `${trigger}:${sid}`;
|
|
212
|
+
if (now - (lastCaptureRun.get(key) ?? 0) < CAPTURE_COOLDOWN_MS) return false;
|
|
213
|
+
// Sessions churn and a long-lived server must not grow one entry per
|
|
214
|
+
// session forever; oldest-inserted go first (the ledger throttle's rule).
|
|
215
|
+
if (lastCaptureRun.size > 2000) {
|
|
216
|
+
for (const k of [...lastCaptureRun.keys()].slice(0, 1000)) lastCaptureRun.delete(k);
|
|
217
|
+
}
|
|
218
|
+
lastCaptureRun.set(key, now);
|
|
219
|
+
return true;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Clear the cooldown windows (tests; also what a process restart does). */
|
|
223
|
+
export function resetCaptureCooldowns(): void {
|
|
224
|
+
lastCaptureRun.clear();
|
|
225
|
+
}
|
|
226
|
+
|
|
199
227
|
// The real setup implementation, written against the loose local PluginCtx
|
|
200
228
|
// (the only members of the V2 context this plugin actually touches).
|
|
201
229
|
const impl = {
|
|
@@ -1075,7 +1103,6 @@ const impl = {
|
|
|
1075
1103
|
);
|
|
1076
1104
|
} else {
|
|
1077
1105
|
const controller = new AbortController();
|
|
1078
|
-
const lastRun = new Map<string, number>();
|
|
1079
1106
|
const eventApi = ctx.event;
|
|
1080
1107
|
const generateApi = ctx.generate;
|
|
1081
1108
|
// Arrow wrapper: keep the receiver bound. The harness fakes are closures,
|
|
@@ -1150,8 +1177,7 @@ const impl = {
|
|
|
1150
1177
|
if (typeof sid !== "string") continue;
|
|
1151
1178
|
setCurrent({ sessionID: sid });
|
|
1152
1179
|
const now = Date.now();
|
|
1153
|
-
if (
|
|
1154
|
-
lastRun.set(sid, now);
|
|
1180
|
+
if (!captureCooldownPasses("idle", sid, now)) continue; // 5-min cooldown, shared across setups
|
|
1155
1181
|
try {
|
|
1156
1182
|
await captureSession(sid, "", "idle");
|
|
1157
1183
|
} catch {
|
|
@@ -1165,16 +1191,16 @@ const impl = {
|
|
|
1165
1191
|
captureCleanup = () => controller.abort();
|
|
1166
1192
|
|
|
1167
1193
|
// The compaction trigger needs no extra subscription: the session
|
|
1168
|
-
// compaction hook (registered above) calls through this seam.
|
|
1169
|
-
// cooldown
|
|
1170
|
-
//
|
|
1194
|
+
// compaction hook (registered above) calls through this seam. The
|
|
1195
|
+
// cooldown names the trigger, so measuring a compaction capture is
|
|
1196
|
+
// not confounded by an idle fire moments before - and lives at
|
|
1197
|
+
// module level, so a second setup() cannot double-pay one
|
|
1198
|
+
// compaction (#108).
|
|
1171
1199
|
if (captureOnCompact) {
|
|
1172
|
-
const lastCompactRun = new Map<string, number>();
|
|
1173
1200
|
onCompactCapture = (sid, messages) => {
|
|
1174
1201
|
if (controller.signal.aborted) return;
|
|
1175
1202
|
const now = Date.now();
|
|
1176
|
-
if (
|
|
1177
|
-
lastCompactRun.set(sid, now);
|
|
1203
|
+
if (!captureCooldownPasses("compaction", sid, now)) return; // 5-min cooldown
|
|
1178
1204
|
void guarded("session.compaction (auto-capture)", () =>
|
|
1179
1205
|
captureSession(sid, flattenTranscript(messages), "compaction", messages),
|
|
1180
1206
|
);
|
package/src/memory.ts
CHANGED
|
@@ -377,6 +377,10 @@ export async function markManySuperseded(
|
|
|
377
377
|
marked += await withStoreLock(
|
|
378
378
|
file,
|
|
379
379
|
async () => {
|
|
380
|
+
// #106: identity BEFORE the read, like every other whole-file
|
|
381
|
+
// read-modify-write (#89's contract) - the publish below may retry a
|
|
382
|
+
// Windows handover only while the destination still matches this.
|
|
383
|
+
const since = await fileIdentity(file);
|
|
380
384
|
const lines = await readLines(file);
|
|
381
385
|
let touched = 0;
|
|
382
386
|
for (let i = 0; i < lines.length; i++) {
|
|
@@ -391,7 +395,7 @@ export async function markManySuperseded(
|
|
|
391
395
|
}
|
|
392
396
|
if (touched === 0) return 0;
|
|
393
397
|
await snapshotBefore(file);
|
|
394
|
-
await writeAtomic(file, lines.join("\n") + "\n");
|
|
398
|
+
await writeAtomic(file, lines.join("\n") + "\n", since);
|
|
395
399
|
return touched;
|
|
396
400
|
},
|
|
397
401
|
LOCK_WRITE,
|