opencode-self-improvement 0.14.0 → 0.14.2
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/blocklist.ts +3 -2
- package/src/hits.ts +6 -2
- package/src/lock.ts +46 -3
- package/src/logfmt.ts +74 -6
- package/src/memory.ts +22 -4
- package/src/resolver.ts +9 -1
- package/src/undo.ts +5 -2
- package/src/viewer/mutate.ts +3 -2
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 proposes candidates, which face the same write gates. 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. 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.2",
|
|
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/blocklist.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
// memory scan must never pick it up.
|
|
6
6
|
import { join } from "node:path";
|
|
7
7
|
import { memoryRoot } from "./config.ts";
|
|
8
|
-
import { appendLog, formatLine, parseLine, readLines, writeAtomic } from "./logfmt.ts";
|
|
8
|
+
import { appendLog, fileIdentity, formatLine, parseLine, readLines, writeAtomic } from "./logfmt.ts";
|
|
9
9
|
import { withStoreLock, LOCK_WRITE } from "./lock.ts";
|
|
10
10
|
|
|
11
11
|
const BLOCKLIST_FILENAME = "blocklist.logfmt";
|
|
@@ -59,11 +59,12 @@ export async function removeBlock(ts: string): Promise<boolean> {
|
|
|
59
59
|
async () => {
|
|
60
60
|
const store = Bun.file(file);
|
|
61
61
|
if (!(await store.exists())) return false;
|
|
62
|
+
const since = await fileIdentity(file);
|
|
62
63
|
const kept = (await store.text()).split("\n").filter((l) => {
|
|
63
64
|
const row = parseLine(l);
|
|
64
65
|
return !(row && row.ts === ts);
|
|
65
66
|
});
|
|
66
|
-
await writeAtomic(file, kept.join("\n") + (kept.length ? "\n" : ""));
|
|
67
|
+
await writeAtomic(file, kept.join("\n") + (kept.length ? "\n" : ""), since);
|
|
67
68
|
return true;
|
|
68
69
|
},
|
|
69
70
|
LOCK_WRITE,
|
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/lock.ts
CHANGED
|
@@ -31,6 +31,10 @@ const STALE_MS = 10_000;
|
|
|
31
31
|
const DEFAULT_TIMEOUT_MS = 5_000;
|
|
32
32
|
const MIN_BACKOFF_MS = 1;
|
|
33
33
|
const MAX_BACKOFF_MS = 25;
|
|
34
|
+
// How many consecutive create-failures with a proven-absent lock file mean
|
|
35
|
+
// "this filesystem is not letting us create it" rather than "we are losing a
|
|
36
|
+
// race with a live holder". The wait is a fast, bounded spin, not a budget.
|
|
37
|
+
const ABSENT_THROW_STRIKES = 8;
|
|
34
38
|
|
|
35
39
|
export function lockFileFor(file: string): string {
|
|
36
40
|
return file + LOCK_SUFFIX;
|
|
@@ -84,12 +88,29 @@ async function timed(prev: Promise<void>, ms: number): Promise<boolean> {
|
|
|
84
88
|
return gained;
|
|
85
89
|
}
|
|
86
90
|
|
|
91
|
+
// The one probe that can answer "there is no holder" without itself being a
|
|
92
|
+
// creation attempt: stat reports a held file happily (Windows shares metadata
|
|
93
|
+
// reads with the handle owner), and ENOENT — uniquely — proves absence.
|
|
94
|
+
async function lockFileAbsent(lockPath: string): Promise<boolean> {
|
|
95
|
+
try {
|
|
96
|
+
await stat(lockPath);
|
|
97
|
+
return false;
|
|
98
|
+
} catch (probe) {
|
|
99
|
+
return (probe as NodeJS.ErrnoException).code === "ENOENT";
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
87
103
|
async function stealIfStale(lockPath: string, now: number): Promise<boolean> {
|
|
88
104
|
let age = -1;
|
|
89
105
|
try {
|
|
90
106
|
age = now - (await stat(lockPath)).mtimeMs;
|
|
91
107
|
} catch {
|
|
92
|
-
|
|
108
|
+
// Age undeterminable — typically the holder finished and removed the
|
|
109
|
+
// file a moment before this stat. "Not stealable" is the safe answer:
|
|
110
|
+
// the caller backs off within the budget and the next create wins.
|
|
111
|
+
// The old "retry the create immediately" here turned a stat that keeps
|
|
112
|
+
// failing into a hot spin that never consulted the budget at all.
|
|
113
|
+
return false;
|
|
93
114
|
}
|
|
94
115
|
if (age < STALE_MS) return false;
|
|
95
116
|
try {
|
|
@@ -112,6 +133,8 @@ async function holdFileLock<T>(
|
|
|
112
133
|
const token = `${process.pid}-${Math.random().toString(36).slice(2)}`;
|
|
113
134
|
const started = Date.now();
|
|
114
135
|
let backoff = MIN_BACKOFF_MS;
|
|
136
|
+
let firstErr: unknown;
|
|
137
|
+
let absentStrikes = 0;
|
|
115
138
|
for (;;) {
|
|
116
139
|
try {
|
|
117
140
|
const handle = await open(lockPath, "wx");
|
|
@@ -122,8 +145,23 @@ async function holdFileLock<T>(
|
|
|
122
145
|
}
|
|
123
146
|
break;
|
|
124
147
|
} catch (err) {
|
|
125
|
-
|
|
126
|
-
|
|
148
|
+
// Any creation failure means: wait for the current holder, whatever
|
|
149
|
+
// label it carries (POSIX EEXIST; Windows sharing violations EPERM/
|
|
150
|
+
// EACCES; or the file vanishing between this open and any later probe
|
|
151
|
+
// — the holder simply finished). Policies that trusted a label or a
|
|
152
|
+
// one-shot probe were tried and lost rows: throwing on non-EEXIST
|
|
153
|
+
// aborted writers on mislabelled contention, and throwing on a
|
|
154
|
+
// stat-probe ENOENT aborted them in the vanish race.
|
|
155
|
+
// The filesystem still gets the last word: if creation keeps failing
|
|
156
|
+
// while stat keeps proving NO lock file exists, there is no holder to
|
|
157
|
+
// wait for — our own ability to create files is what is broken, and
|
|
158
|
+
// the original error must surface instead of rotting into a timeout.
|
|
159
|
+
firstErr ??= err;
|
|
160
|
+
if (await lockFileAbsent(lockPath)) {
|
|
161
|
+
if (++absentStrikes >= ABSENT_THROW_STRIKES) throw firstErr;
|
|
162
|
+
} else {
|
|
163
|
+
absentStrikes = 0;
|
|
164
|
+
}
|
|
127
165
|
if (await stealIfStale(lockPath, Date.now())) {
|
|
128
166
|
opts.onEvent?.("steal", Date.now() - started);
|
|
129
167
|
continue;
|
|
@@ -135,6 +173,11 @@ async function holdFileLock<T>(
|
|
|
135
173
|
`memory store is busy: ${basename(file)} has been locked for ${Date.now() - started}ms — retry`,
|
|
136
174
|
);
|
|
137
175
|
}
|
|
176
|
+
// Proceeding without the lock is the designed concession to
|
|
177
|
+
// contention — but never while the lock file has been absent this
|
|
178
|
+
// whole time: on a filesystem where we cannot create it, writing
|
|
179
|
+
// "unlocked" would just mean writing unguarded.
|
|
180
|
+
if (absentStrikes > 0) throw firstErr;
|
|
138
181
|
return fn();
|
|
139
182
|
}
|
|
140
183
|
await sleep(backoff);
|
package/src/logfmt.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
// Minimal logfmt reader/writer shared by the durable store and the evidence
|
|
2
2
|
// log. Field order is preserved on write so chains are diffable.
|
|
3
3
|
import { dirname } from "node:path";
|
|
4
|
-
import { appendFile, mkdir, rename, unlink } from "node:fs/promises";
|
|
4
|
+
import { appendFile, mkdir, rename, stat, unlink } from "node:fs/promises";
|
|
5
|
+
|
|
6
|
+
const IS_WINDOWS = process.platform === "win32";
|
|
5
7
|
|
|
6
8
|
export type Fields = Record<string, unknown>;
|
|
7
9
|
|
|
@@ -94,25 +96,91 @@ export async function appendLog(file: string, line: string): Promise<void> {
|
|
|
94
96
|
await appendFile(file, next);
|
|
95
97
|
}
|
|
96
98
|
|
|
99
|
+
// A change-detection token for one file: any append, rewrite or replacement
|
|
100
|
+
// changes it. "absent" marks a file that does not exist yet. Readers of the
|
|
101
|
+
// freshness contract below take it BEFORE reading, so it pins the state the
|
|
102
|
+
// published content was derived from.
|
|
103
|
+
export async function fileIdentity(file: string): Promise<string> {
|
|
104
|
+
try {
|
|
105
|
+
const s = await stat(file, { bigint: true });
|
|
106
|
+
return `${s.ino}|${s.size}|${s.mtimeNs}`;
|
|
107
|
+
} catch (err) {
|
|
108
|
+
if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
|
|
109
|
+
return "absent";
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
97
113
|
// Publish whole-file content so no reader can observe a partial store. Recall,
|
|
98
114
|
// injection and the viewer read these files without taking the lock, so the
|
|
99
115
|
// handover is a same-directory rename (atomic on POSIX): a reader sees either
|
|
100
116
|
// the previous file or the new one, never a truncated middle. Callers hold the
|
|
101
117
|
// store lock for the whole read-modify-write.
|
|
102
|
-
|
|
118
|
+
//
|
|
119
|
+
// `since` is the fileIdentity() taken before the caller read the file it is
|
|
120
|
+
// deriving `content` from. With it, a Windows handover that fails on reader
|
|
121
|
+
// contention can retry without risking a stale publish (see handoverRename).
|
|
122
|
+
// Without it, publishing behaves exactly as it always has: one rename.
|
|
123
|
+
let tmpSeq = 0;
|
|
124
|
+
|
|
125
|
+
export async function writeAtomic(file: string, content: string, since?: string): Promise<void> {
|
|
103
126
|
await ensureDir(dirname(file));
|
|
104
|
-
//
|
|
105
|
-
//
|
|
106
|
-
|
|
127
|
+
// Unique PER CALL, not per process: the store lock guarantees one writer
|
|
128
|
+
// only until a starved waiter's budget expires and lock.ts lets it proceed
|
|
129
|
+
// anyway. That degraded writer can be inside writeAtomic for the same file
|
|
130
|
+
// at the same instant - with a pid-stable name its bytes would sit in the
|
|
131
|
+
// very temp the anchored publish's ≤2s retry keeps renaming, and the retry
|
|
132
|
+
// would publish THOSE bytes under our success report. One extra leftover
|
|
133
|
+
// per failed attempt is the (unlinkable) price of that safety.
|
|
134
|
+
const tmp = `${file}.${process.pid}.${++tmpSeq}.tmp`;
|
|
107
135
|
try {
|
|
108
136
|
await Bun.write(tmp, content);
|
|
109
|
-
await
|
|
137
|
+
await handoverRename(tmp, file, since);
|
|
110
138
|
} catch (err) {
|
|
111
139
|
await unlink(tmp).catch(() => undefined);
|
|
112
140
|
throw err;
|
|
113
141
|
}
|
|
114
142
|
}
|
|
115
143
|
|
|
144
|
+
// POSIX renames swap a file out from under an open reader; the handover needs
|
|
145
|
+
// one call, and a failure there is fatal, never contention. Windows mandatory
|
|
146
|
+
// locking instead REFUSES to replace a destination any reader still holds,
|
|
147
|
+
// while that handle lives. Readers of a small store file cycle their handle on
|
|
148
|
+
// a microsecond scale, so that failure is usually transient and worth a retry
|
|
149
|
+
// window (~2s, well inside the 5s lock budget) — but a retry alone is not safe
|
|
150
|
+
// here. If an unlocked writer (a starved lock waiter runs its write anyway;
|
|
151
|
+
// see lock.ts onTimeout) appends into the destination DURING the window, the
|
|
152
|
+
// retried rename publishes our now-stale copy over that row — a slower way to
|
|
153
|
+
// lose exactly what the immediate failure preserved. So the retry runs only
|
|
154
|
+
// while the destination still matches `since`, the identity from before the
|
|
155
|
+
// caller's read: match means no one moved the file and the blocker is a bare
|
|
156
|
+
// reader handle, a mismatch means the write's premise is gone and it fails
|
|
157
|
+
// with the original error, as the no-retry path always did. Hence also: no
|
|
158
|
+
// `since`, no retry.
|
|
159
|
+
async function handoverRename(tmp: string, file: string, since?: string): Promise<void> {
|
|
160
|
+
try {
|
|
161
|
+
await rename(tmp, file);
|
|
162
|
+
return;
|
|
163
|
+
} catch (err) {
|
|
164
|
+
if (!IS_WINDOWS || since === undefined) throw err;
|
|
165
|
+
const deadline = Date.now() + 2000;
|
|
166
|
+
let backoff = 1;
|
|
167
|
+
for (;;) {
|
|
168
|
+
const now = Date.now();
|
|
169
|
+
if (now >= deadline) throw err;
|
|
170
|
+
await new Promise((r) => setTimeout(r, Math.min(backoff, deadline - now)));
|
|
171
|
+
backoff = Math.min(backoff * 2, 50);
|
|
172
|
+
if ((await fileIdentity(file)) !== since) throw err; // destination moved; our copy is stale
|
|
173
|
+
try {
|
|
174
|
+
await rename(tmp, file);
|
|
175
|
+
return;
|
|
176
|
+
} catch {
|
|
177
|
+
// Still the reader's turn to block us (or a fresh one); the identity
|
|
178
|
+
// check at the top of the next pass is what distinguishes the two.
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
116
184
|
export async function readLines(file: string): Promise<string[]> {
|
|
117
185
|
const f = Bun.file(file);
|
|
118
186
|
if (!(await f.exists())) return [];
|
package/src/memory.ts
CHANGED
|
@@ -8,7 +8,16 @@ import { join, basename } from "node:path";
|
|
|
8
8
|
import { dateStr, memoryRoot, deletionsFile, snapshotDir, HITS_FILENAME } from "./config.ts";
|
|
9
9
|
import { repoScopeFor } from "./repokey.ts";
|
|
10
10
|
import { getCurrent } from "./state.ts";
|
|
11
|
-
import {
|
|
11
|
+
import {
|
|
12
|
+
appendLog,
|
|
13
|
+
ensureDir,
|
|
14
|
+
fileIdentity,
|
|
15
|
+
formatLine,
|
|
16
|
+
parseLine,
|
|
17
|
+
readLines,
|
|
18
|
+
writeAtomic,
|
|
19
|
+
type Fields,
|
|
20
|
+
} from "./logfmt.ts";
|
|
12
21
|
import { withStoreLock, LOCK_WRITE } from "./lock.ts";
|
|
13
22
|
import { blockedTs } from "./blocklist.ts";
|
|
14
23
|
import { containsSecret, redactSecrets } from "./secrets.ts";
|
|
@@ -319,6 +328,10 @@ async function stampRow(
|
|
|
319
328
|
return withStoreLock(
|
|
320
329
|
file,
|
|
321
330
|
async () => {
|
|
331
|
+
// Identity BEFORE the read: it pins the state `lines` was derived from,
|
|
332
|
+
// so writeAtomic can refuse to publish if anything moved the file
|
|
333
|
+
// meanwhile (Windows retry path — see logfmt.ts handoverRename).
|
|
334
|
+
const since = await fileIdentity(file);
|
|
322
335
|
const lines = await readLines(file);
|
|
323
336
|
const idx = lines.findIndex((l) => {
|
|
324
337
|
const f = parseLine(l);
|
|
@@ -331,7 +344,7 @@ async function stampRow(
|
|
|
331
344
|
if (next === null) return false;
|
|
332
345
|
lines[idx] = next;
|
|
333
346
|
await snapshotBefore(file);
|
|
334
|
-
await writeAtomic(file, lines.join("\n") + "\n");
|
|
347
|
+
await writeAtomic(file, lines.join("\n") + "\n", since);
|
|
335
348
|
return true;
|
|
336
349
|
},
|
|
337
350
|
LOCK_WRITE,
|
|
@@ -364,6 +377,10 @@ export async function markManySuperseded(
|
|
|
364
377
|
marked += await withStoreLock(
|
|
365
378
|
file,
|
|
366
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);
|
|
367
384
|
const lines = await readLines(file);
|
|
368
385
|
let touched = 0;
|
|
369
386
|
for (let i = 0; i < lines.length; i++) {
|
|
@@ -378,7 +395,7 @@ export async function markManySuperseded(
|
|
|
378
395
|
}
|
|
379
396
|
if (touched === 0) return 0;
|
|
380
397
|
await snapshotBefore(file);
|
|
381
|
-
await writeAtomic(file, lines.join("\n") + "\n");
|
|
398
|
+
await writeAtomic(file, lines.join("\n") + "\n", since);
|
|
382
399
|
return touched;
|
|
383
400
|
},
|
|
384
401
|
LOCK_WRITE,
|
|
@@ -528,6 +545,7 @@ export async function prune(scope: string, type: string, reason: string): Promis
|
|
|
528
545
|
await withStoreLock(
|
|
529
546
|
file,
|
|
530
547
|
async () => {
|
|
548
|
+
const since = await fileIdentity(file);
|
|
531
549
|
const lines = await readLines(file);
|
|
532
550
|
const kept: string[] = [];
|
|
533
551
|
let changed = false;
|
|
@@ -547,7 +565,7 @@ export async function prune(scope: string, type: string, reason: string): Promis
|
|
|
547
565
|
}
|
|
548
566
|
if (!changed) return;
|
|
549
567
|
snapshot.push(...(await snapshotFiles([file])));
|
|
550
|
-
await writeAtomic(file, kept.join("\n") + (kept.length ? "\n" : ""));
|
|
568
|
+
await writeAtomic(file, kept.join("\n") + (kept.length ? "\n" : ""), since);
|
|
551
569
|
},
|
|
552
570
|
LOCK_WRITE,
|
|
553
571
|
);
|
package/src/resolver.ts
CHANGED
|
@@ -277,7 +277,15 @@ async function walkSources(absDir: string, relDir: string, out: string[]): Promi
|
|
|
277
277
|
} catch {
|
|
278
278
|
// Directory vanished mid-walk: keep what was collected.
|
|
279
279
|
} finally {
|
|
280
|
-
|
|
280
|
+
// Close by awaiting, never by chaining off the return value: Bun 1.3.10
|
|
281
|
+
// returns undefined from DirHandle.close() (there the old `.catch()` chain
|
|
282
|
+
// threw a TypeError that killed the walk), 1.4.4 returns a Promise, and
|
|
283
|
+
// awaiting serves both — the optional call covers runtimes without it.
|
|
284
|
+
try {
|
|
285
|
+
await dh.close?.();
|
|
286
|
+
} catch {
|
|
287
|
+
// The walk is done: a handle that refuses to close is GC's problem.
|
|
288
|
+
}
|
|
281
289
|
}
|
|
282
290
|
}
|
|
283
291
|
|
package/src/undo.ts
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
import { lstat, realpath, stat } from "node:fs/promises";
|
|
14
14
|
import { basename, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
15
15
|
import { deletionsFile, snapshotDir } from "./config.ts";
|
|
16
|
-
import { ensureDir, parseLine, readLines, writeAtomic } from "./logfmt.ts";
|
|
16
|
+
import { ensureDir, fileIdentity, parseLine, readLines, writeAtomic } from "./logfmt.ts";
|
|
17
17
|
import { withStoreLock, LOCK_RESTORE } from "./lock.ts";
|
|
18
18
|
import { snapshotFiles } from "./memory.ts";
|
|
19
19
|
|
|
@@ -206,6 +206,9 @@ export async function restoreSnapshot(
|
|
|
206
206
|
return withStoreLock(
|
|
207
207
|
target,
|
|
208
208
|
async () => {
|
|
209
|
+
// Identity before the first read of `target` here: everything published
|
|
210
|
+
// below derives from what this read sees (logfmt.ts handoverRename).
|
|
211
|
+
const since = await fileIdentity(target);
|
|
209
212
|
const cur = Bun.file(target);
|
|
210
213
|
const curLines = (await cur.exists()) ? rows(await cur.text()) : [];
|
|
211
214
|
// Deliberate deletions are read inside the lock too, so a forget that
|
|
@@ -254,7 +257,7 @@ export async function restoreSnapshot(
|
|
|
254
257
|
);
|
|
255
258
|
}
|
|
256
259
|
await ensureDir(memoryRootDir);
|
|
257
|
-
await writeAtomic(target, out.length ? out.join("\n") + "\n" : "");
|
|
260
|
+
await writeAtomic(target, out.length ? out.join("\n") + "\n" : "", since);
|
|
258
261
|
return { target, restored: true, mode, safety, concurrentAdded, concurrentChanged, deletedOmitted };
|
|
259
262
|
},
|
|
260
263
|
LOCK_RESTORE,
|
package/src/viewer/mutate.ts
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
import { deletionsFile } from "../config.ts";
|
|
10
10
|
import { addBlock, removeBlock } from "../blocklist.ts";
|
|
11
11
|
import { record, chainId } from "../evidence.ts";
|
|
12
|
-
import { appendLog, formatLine, parseLine, readLines, writeAtomic } from "../logfmt.ts";
|
|
12
|
+
import { appendLog, fileIdentity, formatLine, parseLine, readLines, writeAtomic } from "../logfmt.ts";
|
|
13
13
|
import { withStoreLock, LOCK_WRITE } from "../lock.ts";
|
|
14
14
|
import {
|
|
15
15
|
appendMemory,
|
|
@@ -106,6 +106,7 @@ export async function deleteMemory(input: DeleteInput): Promise<MutationResult>
|
|
|
106
106
|
await withStoreLock(
|
|
107
107
|
target.file,
|
|
108
108
|
async () => {
|
|
109
|
+
const since = await fileIdentity(target.file);
|
|
109
110
|
const lines = await readLines(target.file);
|
|
110
111
|
const kept = lines.filter((l) => {
|
|
111
112
|
const f = parseLine(l);
|
|
@@ -113,7 +114,7 @@ export async function deleteMemory(input: DeleteInput): Promise<MutationResult>
|
|
|
113
114
|
});
|
|
114
115
|
if (kept.length === lines.length) throw new Error(`memory line not found: ${input.ts}`);
|
|
115
116
|
snapshot = await snapshotFiles([target.file]);
|
|
116
|
-
await writeAtomic(target.file, kept.join("\n") + (kept.length ? "\n" : ""));
|
|
117
|
+
await writeAtomic(target.file, kept.join("\n") + (kept.length ? "\n" : ""), since);
|
|
117
118
|
},
|
|
118
119
|
LOCK_WRITE,
|
|
119
120
|
);
|