opencode-self-improvement 0.30.5 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,10 +1,10 @@
1
1
  # Opencode-Self-Improvement
2
2
 
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.
3
+ Durable memory for [opencode](https://opencode.ai): the decisions, commands and facts an agent should still know next week, plus a one-command per-repo setup.
4
4
 
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.
5
+ Say "we use Bun, not npm — npm keeps breaking the lockfile" on Monday. A session you start on Tuesday already knows it, and why. A memory that turns out wrong is superseded, never deleted, and `memory_undo` rolls it back.
6
6
 
7
- Every figure in this README carries a provenance marker: **measured** (read off a live store), **bench** (a deterministic synthetic workload, reproducible with the command printed under the table), or **illustrative** (sample output showing shape, not a measurement). A number without a marker is a claim that has not been checked.
7
+ Every figure here carries a marker: **measured** (read off a live store), **bench** (a deterministic synthetic workload, reproducible with the command printed under the table), or **illustrative** (sample output showing shape, not a measurement). A number without a marker is a claim that has not been checked.
8
8
 
9
9
  ## Quick start
10
10
 
@@ -17,43 +17,68 @@ Every figure in this README carries a provenance marker: **measured** (read off
17
17
  }
18
18
  ```
19
19
 
20
- **2. Restart opencode.** It installs the package and its dependencies at startup, and the plugin installs its own slash commands. On desktop, a later config edit needs `opencode service restart`: relaunching the app leaves the background service — and the plugin options it already parsed — alive.
20
+ **2. Restart opencode.** On the desktop app a later config edit needs `opencode service restart`: relaunching the app leaves the background service, and the options it already parsed, alive.
21
21
 
22
- **3. Run `/repo-init`** in each repo you work in. It stores the test / build / lint / typecheck commands as memories and records an init stamp tied to the current git head. The stamp is plugin bookkeeping under `<memory-root>/init-stamps/`, not a memory row, so no session can forge it (#374). A store left by an older release migrates once: its `init-stamp` row is honoured only when an `init_complete` audit line names it (and at the head that line names), is then retired, and is withheld from recall and injection either way (#376). Rerun `/repo-init force` after a refactor.
22
+ **3. Run `/repo-init`** in each repo you work in. It stores that repo's test / build / lint / typecheck commands as memories, so the next session does not rediscover them. Rerun `/repo-init force` after a refactor.
23
23
 
24
- Needs Bun 1.3.0 or newer in the opencode build (the tested floor); older Bun reports a startup warning.
24
+ After that, memory is just conversation: ask the agent to remember something and it sticks.
25
25
 
26
- On opencode v2 the CLI works too:
26
+ <details>
27
+ <summary>Other ways to install, and the version floor</summary>
27
28
 
28
29
  ```sh
29
30
  opencode plugin add opencode-self-improvement
30
31
  opencode plugin update opencode-self-improvement
31
32
  ```
32
33
 
33
- After that, memory is just conversation: ask the agent to remember something and it sticks.
34
+ Needs Bun 1.3.0 or newer in the opencode build (the tested floor); older Bun reports a startup warning.
35
+
36
+ An unpinned entry resolves `@latest` exactly once and is never re-resolved afterwards, so updates are deliberate: run `opencode plugin update` when you want one. To pin, append `@<version>` — see [npm](https://www.npmjs.com/package/opencode-self-improvement) for what is current.
37
+
38
+ To work on the plugin instead, clone it and point the entry at the checkout:
39
+
40
+ ```sh
41
+ git clone https://github.com/abogartz/opencode-self-improvement.git
42
+ cd opencode-self-improvement && bun install
43
+ ```
44
+
45
+ ```json
46
+ { "plugins": ["/full/path/to/opencode-self-improvement/index.ts"] }
47
+ ```
48
+
49
+ Then `git pull` and restart opencode to update.
50
+
51
+ </details>
34
52
 
35
53
  ## What you get
36
54
 
37
- - **`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`.
38
- - **`/repo-init`** — per-repo setup: build/test commands as memories, keyed to the git head.
39
- - **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`, which reads one real calendar day inside `evidence/` at a time — its `date` is a date, never a path.
40
- - **Memory-aware compaction** — durable memories are handed to the compaction summarizer, so a long session keeps its facts.
41
- - **Auto-capture (experimental, opt-in)** — in progress and **not working yet**. The design: on the turn-end and compaction triggers, one cheap model pass per trigger proposes candidates, which face the same write gates, with a 5-minute cooldown per session and trigger bounding the spend. What is not true today: it has never been observed firing on a live opencode 2.x store, so enabling it may cost model calls and store nothing. See [Auto-capture is experimental](#auto-capture-is-experimental).
42
- - **Repo scoping** — rows belong to the repo that wrote them; project A's facts never surface in project B.
43
- - **Safe across concurrent sessions** — a whole-file rewrite holds a lock honoured across processes and hands the new file over with an atomic rename. The lock is a SQLite database beside each store file, claimed with `BEGIN IMMEDIATE`, so a process that is killed releases it at once and a normal write creates and deletes nothing ([#407](https://github.com/abogartz/opencode-self-improvement/issues/407)).
44
- - **Decay** — `memory_decay` retires stale open threads. Dry run by default, snapshot-first, undoable.
45
- - **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.
46
- - **Export / import (JSONL)** — back the store up or move it between machines; every imported row re-enters through the write gates.
47
- - **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).
48
- - **Secret redaction** — credential-shaped values in content become `[redacted]`. See [Secret redaction](#secret-redaction).
55
+ Think of it as a lab notebook the agent keeps for your repo, plus a librarian who checks every entry before filing it.
56
+
57
+ - **Write gates — a CI check for facts.** A memory citing `parseHeader()` in a file you deleted is refused before it is stored, not after a future session trusts it. Near-duplicates collapse, and a contradiction with a retired memory is rejected. Every refusal lands in `memory_evidence` with its reason.
58
+ - **Budgeted injection.** Relevant memories ride the prompt on their own, capped at `injectBudget` characters. The block is cache-stable: a write somewhere else in the store does not cost you a cache miss.
59
+ - **Repo scoping.** Every row carries the repo that wrote it, so project A's facts never surface in project B. A preference you want everywhere goes in with `memory_remember global: true`.
60
+ - **Nothing is deleted.** `memory_update` supersedes the old row, `memory_forget` records a retirement, `memory_undo` restores a snapshot.
61
+ - **Memory-aware compaction** — a long session hands its durable facts to the summarizer instead of losing them.
62
+ - **Safe across concurrent sessions** — a reader sees the previous store file or the new one, never half of either.
63
+ - **Decay and consolidation** — `memory_decay` retires stale open threads, `memory_consolidate` proposes near-duplicate merges. Both are dry-run-first and write nothing you did not approve.
64
+ - **Export / import (JSONL)** — back the store up or move it between machines; every imported row re-enters through the same gates.
65
+ - **Surfaces** — a footer badge, the `/memory` panel, `/memory-report` for chat clients, and a browser admin editor. See [Surfaces](#surfaces).
66
+ - **Secret redaction** — credential-shaped values become `[redacted]`. See [Secret redaction](#secret-redaction).
67
+ - **`memory_*` tools** — `memory_remember`, `memory_recall`, `memory_update`, `memory_forget`, `memory_undo`, `memory_status`, `memory_evidence`, `memory_export`, `memory_import`, `memory_decay`, `memory_consolidate`, `memory_merge_review`, `memory_list`, `memory_init`.
68
+ - **Auto-capture** — at the end of a turn, and again at compaction, one cheap model pass reads what just happened and proposes facts worth keeping. They face the same write gates as anything you save by hand. On by default, and it inherits your session's model; `autoCapture: false` turns it off. See [Auto-capture](#auto-capture).
49
69
 
50
70
  Memory is stored outside every repository, under `~/.config/opencode/memory` by default (override with `OPENCODE_MEMORY_DIR`). To start over, delete that directory.
51
71
 
52
- A write publishes a **complete replacement file** under a per-file lock, so a concurrent reader sees the previous file or the new one, never a partial record. New store directories are `0700` and new files `0600` on POSIX, subject to a more restrictive umask. A memory root on SMB, NFS or a OneDrive-mounted folder is **not supported** — the lock's write-ahead log needs shared memory that SQLite cannot mmap there. Lock scope and why it is one file rather than the store, the Windows reader handle that can refuse a replacement, permission migration and what it does not revoke: [docs/store-concurrency.md](docs/store-concurrency.md).
53
-
54
72
  ## Options
55
73
 
56
- Zero configuration is the default. To tune, use the object form of the plugin entry in `opencode.json(c)`:
74
+ Zero configuration is the default. Two options change what the model sees:
75
+
76
+ | Option | Default | What it does |
77
+ | --- | --- | --- |
78
+ | `injectBudget` | `1200` | Character cap on the injected relevance block and each contextual pull. |
79
+ | `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. |
80
+
81
+ Anything else goes in the object form of the plugin entry in `opencode.json(c)`:
57
82
 
58
83
  ```json
59
84
  {
@@ -61,62 +86,54 @@ Zero configuration is the default. To tune, use the object form of the plugin en
61
86
  }
62
87
  ```
63
88
 
64
- | Option | Default | What it does |
65
- | --- | --- | --- |
66
- | `injectBudget` | `1200` | Character cap on the injected relevance block and each contextual pull; trimmed at whole-memory boundaries. Env fallback: `OPENCODE_MEMORY_INJECT_BUDGET`. |
67
- | `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`. |
68
- | `contradictionSurface` | `true` | Experimental: compare guided constant claims with bounded source reads and render a class-specific CONFLICT verdict. Set `false` to skip code checks and retain plain guidance. See [Contradiction authority policy](#contradiction-authority-policy-experimental-349--351). |
69
- | `autoCapture` | `false` | Master switch for auto-capture, which is **experimental and has never fired on a verified live store** — see [Auto-capture is experimental](#auto-capture-is-experimental). Off by default, so the install stays zero-token. |
70
- | `captureModel` | — | `"provider/id"` model used for auto-capture. Required when `autoCapture` is on; missing or invalid disables capture with a startup warning. |
71
- | `captureMax` | `3` | Maximum candidates proposed per capture pass. |
72
- | `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 turn-end one, so the two triggers' hit-rates stay measurable. Setting it while `autoCapture` is off does nothing and reports a startup warning. |
73
- | `captureGuidedRules` | `false` | POC: deterministic guided-candidate pre-pass. The user's own lines decide which stated values or rules are guided (numbers, rates, currency, explicit rule assertions) and attach the verbatim quote; the capture model may phrase such a row but cannot clear the flag or the quote, and a guided quote the user never wrote is refused at the write boundary instead of silently stripped. Fires alongside the model pass only — no extra model calls. |
74
- | `notifyBlocked` | `true` | Terminal (TUI) only: toast when a write gate blocks a write. Blocks are always in `memory_evidence` either way. |
75
-
76
- ### Environment variables
77
-
78
- | Variable | Purpose |
79
- | --- | --- |
80
- | `OPENCODE_MEMORY_DIR` | Store location (default `~/.config/opencode/memory`). |
81
- | `OPENCODE_MEMORY_ALLOW_OUTSIDE_PATHS` | Operator-only. When truthy, `memory_export`/`memory_import` accept paths anywhere on disk instead of confining themselves to the store. Off by default. See [Export and move between machines](#export-and-move-between-machines). |
82
- | `OPENCODE_MEMORY_INJECT_BUDGET` | Fallback for `injectBudget`. |
83
- | `OPENCODE_MEMORY_FRONTIER_BUDGET` | Fallback for `frontierBudget`. |
84
- | `OPENCODE_MEMORY_DEDUP` | Near-duplicate suppression inside a `memory_recall` window. **ON by default at `0.8`** (content-token Jaccard, same scope): the newest copy of a near-clone is kept and the rest skipped, so the window fills with distinct facts. Rows that disagree on a negation word are never suppressed. `0` restores the plain top-`limit` slice. |
85
- | `OPENCODE_MEMORY_SYMPTOM` | **ON by default**: `learning` and `blocker` rows must open their content with the observable trigger a future session will hit — `"When <symptom>: <fact>"`. Set `off` (or `0`/`false`) for automation holding a pre-convention backlog. `scripts/symptom-fixer.ts` repairs old rows offline. |
86
- | `OPENCODE_MEMORY_QUERY_GATE` | **ON by default**: a `memory_recall` match must share **two** whole words once the query has three content words — the rule the injected relevance block already applies. Set `off` for the matcher's permissive one-word admission. |
87
- | `OPENCODE_COMMANDS_DIR` | Where the plugin mirrors its slash commands (default `~/.config/opencode/commands`). |
88
- | `OPENCODE_VIEWER_HOST` | Interface the editor binds to (default `127.0.0.1`). A non-loopback bind serves the store over plain HTTP with no authentication — only do it on a network you control. See [Surfaces](#surfaces). |
89
- | `OPENCODE_VIEWER_PORT` | Admin editor port (default `8787`). |
90
- | `OPENCODE_VIEWER_ALLOWED_HOSTS` | Comma-separated hosts beyond loopback. See [Surfaces](#surfaces). |
89
+ The capture options (`autoCapture`, `captureModel`, `captureMax`, `captureOnCompact`, `captureGuidedRules`) are described where the feature is: [Auto-capture](#auto-capture). `contradictionSurface` is described with the verdict table in [Contradiction authority policy](#contradiction-authority-policy-experimental-349--351). Every option and environment variable, including what an invalid value does: [docs/options.md](docs/options.md).
91
90
 
92
- `OPENCODE_MEMORY_DEDUP`, `OPENCODE_MEMORY_SYMPTOM` and `OPENCODE_MEMORY_QUERY_GATE` switch behaviour a measurement decided, and each has an invalid-value rule the table above has no room for — an out-of-range `DEDUP` turns the pass off rather than clamping, and a metadata-only `memory_update` is exempt from `SYMPTOM`. Full behaviour and the evidence behind each: [docs/flags.md](docs/flags.md).
91
+ Read [docs/flags.md](docs/flags.md) before flipping `OPENCODE_MEMORY_DEDUP`, `OPENCODE_MEMORY_SYMPTOM` or `OPENCODE_MEMORY_QUERY_GATE`. Each switches off behaviour a measurement decided, and each has an invalid-value rule that surprises people: an out-of-range `DEDUP` turns the suppression pass off rather than clamping to the nearest bound, and a metadata-only `memory_update` is exempt from `SYMPTOM` so legacy rows can still be retagged.
93
92
 
94
- ## Auto-capture is experimental
93
+ ## Auto-capture
95
94
 
96
- **Status: in progress, and not working yet.** Auto-capture has never been observed firing on a live opencode 2.x store. It is shipped behind `autoCapture` because the plumbing is finished — the trigger, the model pass, the gates, the cooldown — not because the outcome has been verified. Treat it as a switch that may cost model calls and store nothing.
95
+ Auto-capture is the part that notices facts on its own instead of waiting to be asked. At the end of a turn — and again at compaction, before the summarizer replaces the transcript — one cheap model pass reads what just happened and proposes up to `captureMax` candidates. They face the same four write gates as anything you save by hand, and a 5-minute cooldown per session and trigger bounds the spend.
97
96
 
98
- What has been established, and by which kind of evidence, is itemised in [docs/auto-capture-evidence.md](docs/auto-capture-evidence.md): trigger events checked against a host recording rather than a declared type, the path run under simulated host traffic, teardown bounds, a real-host `opencode run` scenario, and the availability bench measured across budgets and store sizes. Read that file before quoting any figure in it — two of the entries are defects found in the measuring bench itself, and the corrected numbers are the ones recorded there.
97
+ It is **on by default** and needs no model name to run. With `captureModel` unset, each pass uses the model your session is already using, or the host default. Set `autoCapture: false` to stop the plugin reading sessions and calling a model for capture entirely:
99
98
 
100
- What is **not** established: that a live host with a live model completes a capture end to end (no `auto_capture_*` line exists anywhere in the maintainer's evidence history), and anything about quality — what auto-capture would write, how often it duplicates a memory you would have written yourself, and what it costs. `bench/capture-trigger-results.md` is a **bench** simulation of trigger *timing* with a scripted extractor; it answers "which moment is worth mining", not "does the shipped feature work".
99
+ ```json
100
+ {
101
+ "plugins": [{ "package": "opencode-self-improvement", "options": { "autoCapture": false } }]
102
+ }
103
+ ```
101
104
 
102
- **Am I armed?** `memory_evidence` answers on the `plugin_load` line: `capture=off` (the option is not on), `invalid_model` (`captureModel` is not `provider/id`), `no_capabilities` (the host did not expose what capture needs) or `capture=on`, next to `subscribed=[…]` listing the event types that subscription really reacts to. On desktop this needs `opencode service restart` after an edit — relaunching the app keeps the old service and its already-parsed options alive, so `capture=` can report a value your config no longer contains. `capture=on` plus no `auto_capture_*` line after a session means the pass did not complete, not that your configuration is wrong; #404 is the known cause and its fix is on this branch.
105
+ Name `captureModel` only to pin one model for the pass. An explicit value that is not `provider/id` turns auto-capture off with a startup warning rather than substituting a model you did not choose.
103
106
 
104
- ## How memory is written
107
+ **What that default means for your data.** Because the switch is on, installing this plugin sends a copy of the conversation to your configured model at every turn-end and every compaction. The copy excludes reasoning content and runs through the credential scrubber first, and anything the pass proposes still faces the same write gates as a manual save — but the read itself is real, and it goes out over your provider. Set `autoCapture: false` if you do not want that.
108
+
109
+ | Option | Default | What it does |
110
+ | --- | --- | --- |
111
+ | `autoCapture` | `true` | Master switch. On, so a plain install mines turn ends. Set `false` for no capture model call at all. |
112
+ | `captureModel` | inherits | `"provider/id"` model for the pass. Unset means the session's own model, else the host default. An explicit malformed value disables capture with a startup warning. |
113
+ | `captureMax` | `3` | Maximum candidates proposed per pass. |
114
+ | `captureOnCompact` | `true` | Also mine the transcript at compaction. Its 5-minute cooldown is separate from the turn-end one, so both triggers' hit-rates stay measurable. Setting it while `autoCapture` is `false` does nothing. |
115
+ | `captureGuidedRules` | `false` | POC: a deterministic pre-pass marks the values and rules you stated outright — numbers, rates, currency, explicit rule assertions — and attaches your verbatim quote. The capture model may rephrase such a row but cannot clear the flag or invent the quote: a quote you never wrote is refused at the write boundary rather than stripped silently. No extra model calls. |
105
116
 
106
- Promotion evidence keeps a bounded sample of the session's code-engagement call IDs — audit pointers, not a complete history — while grounding and attribution use the full in-memory ledger. Existing evidence day-files are left unchanged: no backfill, no compaction, no deletion. What is sampled and why: [docs/write-gates.md](docs/write-gates.md).
117
+ **The honest caveat.** The trigger fires and the write survives on a real host: `e2e/capture.test.ts` drives `opencode run` and a capture pass starts in 12 of 12 runs. What has not been seen is a live store completing a pass — no `auto_capture_*` line exists anywhere in the maintainer's evidence history — and nothing about quality is measured: what auto-capture would write, how often it duplicates a memory you would have written yourself, and what it costs. Because the switch is on by default, that unmeasured pass runs on every install unless you turn it off; `autoCapture: false` is the one-line answer if you would rather wait for the numbers.
107
118
 
108
- Four gates run before anything is stored, and each emits an ordered evidence line:
119
+ What has been established, and by which kind of evidence, is itemised in [docs/auto-capture-evidence.md](docs/auto-capture-evidence.md). Read that file before quoting any figure in it — two of the entries are defects found in the measuring bench itself, and the corrected numbers are the ones recorded there. `bench/capture-trigger-results.md` is a **bench** simulation of trigger *timing* with a scripted extractor; it answers "which moment is worth mining", not "does this earn its keep".
120
+
121
+ **Am I armed?** `memory_evidence` answers on the `plugin_load` line: `capture=on` (the default), `capture=off` (`autoCapture: false`), `invalid_model` (`captureModel` is set but is not `provider/id`), `no_capabilities` (the host did not expose what capture needs), or `switch_mismatch` (`captureOnCompact` is on while `autoCapture` is `false`). The same line carries `subscribed=[…]`, listing the event types that subscription really reacts to. On desktop this needs `opencode service restart` after an edit — relaunching the app keeps the old service and its already-parsed options alive, so `capture=` can report a value your config no longer contains. `capture=on` plus no `auto_capture_*` line after a session means the pass did not complete, not that your configuration is wrong; #404 found that mechanism and its fix is merged.
122
+
123
+ ## How memory is written
124
+
125
+ A memory is a claim about your code, so it gets checked like one. Four gates run before anything is stored, and each emits an ordered evidence line:
109
126
 
110
127
  1. **GATE-1 — code references resolve.** Call signatures and paths embedded in the memory are checked against your live source tree.
111
128
  2. **GATE-2 — no stale memory applies here.** References that drifted out of date are superseded or the write is blocked.
112
129
  3. **GATE-3 — no duplicates.** Near-duplicates collapse into the existing row; a contradiction with a superseded memory is rejected.
113
130
  4. **GATE-4 — promotion or block.** The row lands, or the call returns the reason.
114
131
 
115
- 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. A prose edit carries over ordinary tags, issue link, retrieval keywords, open/settled standing, and repository to the new row, while capture-only guidance provenance is removed — updating a `global` row from one machine keeps it global for every other. Naming a row an earlier update already superseded reports the duplicate when the live successor already holds that exact content; when only the metadata you name differs, the update runs against the successor instead of dead-ending. And a failure after the new row is durable is reported as `PARTIAL` — the message names what failed, the replacement stands on disk, and `memory_undo` (merge or force) brings the old row back.
132
+ Nothing is deleted. `memory_update` supersedes the old row and `memory_forget` records a retirement, so history stays readable, and `memory_undo` restores a snapshot when a change turns out wrong. `memory_update` picks its row by `query` — an id, a clock fragment such as `00:11:22.123`, or a unique substring of its text — and a query that matches nothing, or several rows, writes nothing and says so. What carries over to the new row, what a `PARTIAL` reply means for the rows on disk, and what promotion evidence samples: [docs/write-gates.md](docs/write-gates.md).
116
133
 
117
134
  ### Contradiction authority policy (experimental, #349 / #351)
118
135
 
119
- `contradictionSurface` defaults to `true`; set it to `false` to keep plain guidance without code checks. Guided capture can attach a declared constant's `ref`, the user's value as `claim`, and an authority `klass`:
136
+ You and the code disagree about a constant. Who is right depends on what you said, so capture records the kind of statement:
120
137
 
121
138
  | Captured statement | Class | Verdict on a detected conflict |
122
139
  | --- | --- | --- |
@@ -130,7 +147,7 @@ The code check accepts only a unique top-level `const` with a literal value, run
130
147
 
131
148
  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.
132
149
 
133
- Injection, recall, the frontier block, compaction, `memory_forget` and decay see the current repo plus global rows, resolved from the calling session's identity at flow entry. Writes follow the stricter direction: a named session whose repository cannot be resolved has **no write target**, so `memory_remember`, `memory_update`, `memory_import` and auto-capture refuse it (evidence `write_refused`) rather than stamp your content into another workspace or publish it as an unstamped row. Preferences that should follow you everywhere go in with `memory_remember global: true`.
150
+ Reads — injection, recall, the frontier block, compaction, `memory_forget` and decay — see the current repo plus global rows. Writes follow the stricter direction: a named session whose repository cannot be resolved has **no write target**, so `memory_remember`, `memory_update`, `memory_import` and auto-capture refuse it (evidence `write_refused`) rather than stamp your content into another workspace or publish it as an unstamped row. Preferences that should follow you everywhere go in with `memory_remember global: true`.
134
151
 
135
152
  Identity derivation and legacy hashes, evidence attribution when a session moves repositories mid-operation, and the viewer's separate admin seat: [docs/repo-scoping.md](docs/repo-scoping.md).
136
153
 
@@ -158,20 +175,18 @@ Two results. Only two are quoted, each with its `n` and the seat it ran on, beca
158
175
 
159
176
  ## Token cost and caching
160
177
 
161
- - **Section-frozen injection.** The whole memory section — standing digest, open-thread frontier, relevance block — is computed once per epoch and delivered byte-identically until something the model actually needs changes. The epoch's authority is the **rendered bytes**, not the store fingerprint: a promoted row that changes nothing visible costs no cache bust.
162
- - **A session never pays for bytes it is not riding.** A memory *you* saved in this session is a fact you already produced — it is in your own transcript. A correction, blocklisting, redaction or supersession of a row you are riding, and anything another session, the viewer or an import wrote, still land on your next request.
163
- - **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.
164
- - **Identifiers split.** `getUserAccount`, `get_user_account`, `get-user-account` and `get.user.account` are one concept to the matcher rather than four, and a memory citing `src/recall/score.ts` answers a session that typed the path ([#409](https://github.com/abogartz/opencode-self-improvement/issues/409)).
165
- - **User-stated guidance rides ahead of relevance.** A row auto-capture tagged `user-guided` — something you said outright, like "the correct sales tax rate is 8.25%" — rides the block ahead of the lexical picks: newest-first, at most three, inside `injectBudget`. The tag is minted by auto-capture alone; `memory_remember`, `memory_update` replacements and JSONL imports strip it, because always-riding priority is a poisoning amplifier.
166
- - **Hard budgets.** Relevance block and each pull are capped at `injectBudget` characters, the frontier at `frontierBudget`, trimmed at whole-memory boundaries. Nothing volatile rides the cached prefix: no row count, no latest timestamp.
167
- - **Receipts, not claims.** The plugin reads each turn's `tokens.cache` accounting and shows the actual hit rate next to the badge, with the session's `output` and `reasoning` split. A host that reports neither shows nothing, never a zero.
168
- - **Auto-capture bills separately, and it is an estimate.** Capture is its own model call made after the turn, so it appears in no session's usage, and the host exposes no receipt for it. `memory_status` reports chars/4 with `receipt=none` and the words "estimate, no provider receipt". Quote that number as an estimate or not at all.
178
+ Injecting memory costs prompt bytes, and prompt bytes are what a provider bills against. So the plugin treats the injected block like a cached HTTP response: it is recomputed only when the content the model is actually reading changes, and until then it is delivered byte-identically and served from cache.
169
179
 
170
- **Bench** — on a deterministic workload the shipped policy injects **12.3% fewer characters** than the naive policy, measured over the whole memory section: bytes on a synthetic run, not tokens and not a provider bill. The four-policy comparison table, what the invalidation counter does and does not count, what the workload cannot show, and a provider audit reported by its author (input tokens only, not a total and not a saving) are all in [docs/injection-cost.md](docs/injection-cost.md). Reproduce the byte workload with `bun run bench`.
180
+ - **The frozen bytes are the authority, not the store fingerprint.** A row promoted elsewhere in the store that changes nothing visible costs no cache bust. A memory *you* saved in this session is already in your own transcript, so it does not bust your cache either; a correction of a row you are riding, or anything another session, the viewer or an import wrote, still lands on your next request.
181
+ - **Two concepts, not one.** A free-text prompt must share at least two distinct concepts with a memory to be injected; one- and two-word queries need only one. `memory_recall` still reaches the single-word coincidences when you ask on purpose. Identifier spellings count once: `getUserAccount`, `get_user_account`, `get-user-account` and `get.user.account` are one concept rather than four ([#409](https://github.com/abogartz/opencode-self-improvement/issues/409)).
182
+ - **Things you said outright ride first.** A row auto-capture tagged `user-guided` — "the correct sales tax rate is 8.25%" — rides ahead of the lexical picks, newest-first, at most three, inside the budget. Only auto-capture mints the tag; `memory_remember`, updates and imports strip it, because always-riding priority is a poisoning amplifier.
183
+ - **Budgets are hard, receipts are real.** The block and each pull are capped at `injectBudget` characters, the frontier at `frontierBudget`, trimmed at whole-memory boundaries. The badge shows the provider's own `tokens.cache` accounting; a host that reports nothing shows nothing. Auto-capture is the one place with no receipt at all — it is its own call after the turn — so `memory_status` prints it as `receipt=none`, an estimate.
184
+
185
+ **Bench** — on a deterministic workload the shipped policy injects **12.3% fewer characters** than the naive policy, measured over the whole memory section: bytes on a synthetic run, not tokens and not a provider bill. The four-policy table, what the invalidation counter does and does not count, what the workload cannot show, and an author-reported provider audit (input tokens only, not a total and not a saving): [docs/injection-cost.md](docs/injection-cost.md). Reproduce the byte workload with `bun run bench`.
171
186
 
172
187
  ## Recall quality
173
188
 
174
- No vector database, no embedding model, no API key. **Bench** — what the keyword matcher gives up, measured against classic BM25 on a deterministic eval (store of 200, k=3 — the production injection limit):
189
+ No vector database, no embedding model, no API key: a keyword matcher. That is a trade, and here is the price, measured against classic BM25 on a deterministic eval (store of 200, k=3 — the production injection limit). **Bench**:
175
190
 
176
191
  | Query, vs. the stored memory | share | R@1 | R@3 | with `kw` R@1 | with `kw` R@3 |
177
192
  | --- | ---: | ---: | ---: | ---: | ---: |
@@ -181,13 +196,11 @@ No vector database, no embedding model, no API key. **Bench** — what the keywo
181
196
 
182
197
  "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.
183
198
 
184
- - **In-project prompts are overwhelmingly lexical** (`bun test`, "the rate limiter", "staging deploys"): 98–100% R@3, flat from store size 50 to 500.
185
- - **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.
186
- - **Zero-overlap paraphrase is the real limit, and write time is where it is answered.** `memory_remember` asks each row for 3–5 `kw` aliases (other names, other verb forms, the literal command); auto-capture asks for the same list, so these numbers are measured through the tool path rather than through capture. Keywords 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.
187
- - **`memory_recall` returns 5 rows by default, not 20.** A live audit joined 1,090 recall events to their session transcripts: a returned row at rank 1 shows up in a later tool call at 3.4x the rate of a random store row, ranks 2–3 at 2.4x, and ranks 11–20 at 1.16x — noise against a 0.129 null. The old default returned 17.7 rows per call, so most of the window was context nobody read. At limit 5, recall@1 and recall@3 are unchanged, precision rises 4.1% → 13.1%, and 74% of the returned characters disappear; every gold row the cut dropped sat at ranks 6–20. Pass `limit` for a wider sweep ([#409](https://github.com/abogartz/opencode-self-improvement/issues/409)).
188
- - **Caveats.** The dataset is synthetic (52 memories / 105 queries, a fictional project), its class mix is deliberately adversarial, and scoring is single-gold.
199
+ - **Most in-project prompts are lexical** (`bun test`, "the rate limiter", "staging deploys"): 98–100% R@3, flat from store size 50 to 500.
200
+ - **A zero-overlap paraphrase is the real limit, and write time is where you answer it.** "How we deploy" will not match a session that types "ship to staging" unless you say so: `memory_remember` asks each row for 3–5 `kw` aliases — other names, other verb forms, the literal command — indexed and never rendered. Strict R@1 0% → 26%, near R@1 28% → 67%. Narrowed, not removed.
201
+ - **`memory_recall` returns 5 rows, not 20.** A live audit of 1,090 recall events found a rank-1 row used in a later tool call at 3.4x the rate of a random store row, and ranks 11–20 at 1.16x — noise. Cutting the default from 17.7 rows left recall@1 and recall@3 unchanged, raised precision 4.1% → 13.1%, and dropped 74% of the returned characters ([#409](https://github.com/abogartz/opencode-self-improvement/issues/409)). Pass `limit` for a wider sweep.
189
202
 
190
- Full methodology and all store sizes: `bench/recall-results.md`.
203
+ The abstain-by-design rule, the permutation control behind the `kw` numbers, and the eval's caveats — a synthetic dataset, an adversarial class mix, single-gold scoring: [docs/recall-quality.md](docs/recall-quality.md). Full methodology and all store sizes: `bench/recall-results.md`.
191
204
 
192
205
  ```sh
193
206
  bun run bench:recall
@@ -211,7 +224,7 @@ bun run bench:write
211
224
 
212
225
  ## The store keeps score
213
226
 
214
- 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. Illustrative output — shape, not a measurement:
227
+ The plugin keeps a use ledger — a due-date card for every row: who looked at it, when, and how it reached them. It is append-only, never ingested as a memory, and reported in `memory_status` and the `/memory` panel. Illustrative output — shape, not a measurement:
215
228
 
216
229
  ```
217
230
  STORE
@@ -220,17 +233,19 @@ STORE
220
233
  24.1 KB total · 604 B per row · 1.3 rows/day (30d)
221
234
  ```
222
235
 
223
- - **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.
224
- - **No prompt content is stored.** The ledger keeps a scan-truncated string from the *memory* side, never your message.
225
- - **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.
226
- - **`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.
227
- - **Aggregate STORE counts are machine-wide by decision (#213 B).** They count every repository's rows in the shared store on this machine, never just the reading session's repository — the numbers describe the store, not your slice of it. Privacy applies to the content surfaces instead: `memory_evidence` and the recent-blocked-writes list in `memory_status` and `/memory` follow each reader's repository visibility (#306).
228
- - **Capture lag** is how stale the newest message was when auto-capture fired. The line prints only when at least one `capture_lag` sample exists, which needs auto-capture to have fired — see [Auto-capture is experimental](#auto-capture-is-experimental).
236
+ - **Use has 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. No prompt content is stored: the ledger keeps a scan-truncated string from the *memory* side, never your message.
237
+ - **Reinforcement is a tie-break only** (`useBoost ≤ 1.0`): a recently used row wins a tie and can never outrank a real score gap.
238
+ - **`never retrieved` is stated, not acted on.** Pruning is your decision.
239
+ - **Aggregate STORE counts are machine-wide by decision (#213 B)** — they describe the store on this machine, not your slice of it. Privacy applies to the content surfaces instead: `memory_evidence` and the recent-blocked-writes list follow each reader's repository visibility (#306).
240
+
241
+ The credit rule and its throttle, the consolidation tie-break, and capture lag: [docs/use-ledger.md](docs/use-ledger.md).
229
242
 
230
243
  ## Consolidation
231
244
 
232
245
  `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.
233
246
 
247
+ The rule is: never merge two entries unless every question that used to find either one still finds the merged row.
248
+
234
249
  - **Deterministic.** The canonical row is the survivor's prose verbatim plus the absorbed rows' aliases as keywords. No model rewrites anything.
235
250
  - **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.
236
251
 
@@ -245,7 +260,7 @@ One best-effort credential rule set (`src/secrets.ts`) replaces recognized value
245
260
  - again in the final write choke point used by gated writes and by the viewer's edit and restore paths;
246
261
  - at the durable audit boundaries — every evidence line, every supersede field written into a retired row, and every deletion-audit reason.
247
262
 
248
- So a recognized credential cannot persist in `evidence/`, in `deletions.logfmt`, or in a tombstoned row, whichever path carried it.
263
+ So a recognized credential cannot persist in a new `evidence/` line, in a deletion-audit `reason`, or in a supersede field written into a retired row, whichever path carried it. It is not scrubbed from everything those paths touch — see the limits below.
249
264
 
250
265
  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`).
251
266
 
@@ -255,12 +270,13 @@ Limits worth knowing:
255
270
  - Credential-shaped `scope`, `tags` or `issue` metadata is rejected rather than silently rewritten.
256
271
  - `memory_remember` still replies `Remembered` when content was redacted, so the stored text can differ from what was sent.
257
272
  - Redaction is forward-only: existing stores are not scrubbed. `memory_export` scrubs credentials out of `content`, `issue`, `scope`, `tags` and `kw` as it serialises, so the file that leaves the machine carries `[redacted]` where a stored row still holds a token; the store itself is untouched, and origin stamps (`repo`, `repoPath`) are written as stored. The scrubber is a best-effort sweep over known token families and high-entropy credential-shaped values — an exotic credential can survive it, so an export is still a file you hand out deliberately.
273
+ - Deleting a row copies it, it does not scrub it. `deletions.logfmt` keeps the deleted row's `content`, `tags`, `kw` and `issue` exactly as the row held them — a restore-entry built from that line has to re-stamp and re-attach precisely what was there — and redacts only the `reason`. So deleting a row that predates redaction writes its credential into the audit. Snapshots carry whatever a stored row holds, for the same reason. That retention is deliberate (#292).
258
274
 
259
275
  ## Export and move between machines
260
276
 
261
- `memory_export` writes the live store **as its caller can read it** as JSONL: from a plugin session that means its own repository plus global rows; full-store breadth belongs to a session-less caller outside the plugin (the library route — the viewer has no export route). The format is 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>-<unique>.jsonl` — a unique name created exclusively, so two exports in the same second never replace each other's artifact; `file` must name a path **inside the store** - exports under `<memory-root>/exports` (a relative path resolves against it), imports anywhere under `<memory-root>` - and `scope` exports a single scope.
277
+ `memory_export` writes the store as JSONL, **as its caller can read it**: from a plugin session that means your repository plus global rows. Full-store breadth belongs to a session-less caller outside the plugin — the library route; the viewer has no export route. `memory_import` reads such a file back, and every imported row re-enters through the same four gates as `memory_remember` (tagged `import`, original tags preserved).
262
278
 
263
- Both tools are model-facing, so a path is not a privilege: an export cannot write to `~/.gitconfig` or anywhere else outside the store, and an import cannot read outside it. Symbolic links are resolved before the check — including an `exports/` directory that is itself a link — so a link cannot carry a request out of the store. Exports are written `0600` and opened `O_NOFOLLOW` (both POSIX; on Windows the check before the write is the only guard). (Hardlinks are beyond any path check: a link planted inside `exports/` shares an inode with its target. That, and a narrow window on intermediate path components, are the boundary's known limits.) To move a store between machines, copy the file in:
279
+ To move a store between machines:
264
280
 
265
281
  ```
266
282
  Export my memories # -> <memory-root>/exports/<timestamp>-<unique>.jsonl
@@ -268,9 +284,9 @@ Export my memories # -> <memory-root>/exports/<time
268
284
  Import <memory-root>/memories.jsonl # memory_import
269
285
  ```
270
286
 
271
- An operator running a one-off migration can restore the old anywhere-on-disk behavior with `OPENCODE_MEMORY_ALLOW_OUTSIDE_PATHS=1`. It is read from the plugin process's own environment, so a model cannot grant it to itself through a tool argument.
287
+ Both tools are model-facing, so a path is not a privilege: `file` must stay inside the store — exports under `<memory-root>/exports`, imports anywhere under `<memory-root>` — and a symbolic link cannot carry a request out of it. Pass `scope` to export one scope. An operator running a one-off migration can restore the old anywhere-on-disk behaviour with `OPENCODE_MEMORY_ALLOW_OUTSIDE_PATHS=1`, which is read from the plugin process's own environment so a model cannot grant it to itself. The file format and the confinement rules with their known limits: [docs/import-quarantine.md](docs/import-quarantine.md).
272
288
 
273
- Every imported row re-enters through the same four gates as `memory_remember` (tagged `import`, original tags preserved), and the tool reports a tally:
289
+ The import reply is a tally, not a yes/no:
274
290
 
275
291
  | Outcome | Meaning |
276
292
  | --- | --- |
@@ -280,9 +296,9 @@ Every imported row re-enters through the same four gates as `memory_remember` (t
280
296
  | `skipped` | malformed line; never reached the gates |
281
297
  | `downgraded` | imported as settled because its `status:"open"` could not be vouched for |
282
298
 
283
- Import and auto-capture also scan incoming prose for instruction-override, role-header and download/execute patterns. A promoted match is tagged `quarantine` and withheld from recall, prompt and frontier injection, compaction anchors, contextual pull, consolidation and decay; review it in the viewer's **quarantined** filter.
299
+ Import and auto-capture also scan incoming prose for instruction-override, role-header and download/execute patterns. A promoted match is tagged `quarantine` and withheld from recall, prompt and frontier injection, compaction anchors, contextual pull, consolidation and decay. Think of it as a spam folder, not a virus scanner: legitimate documentation can match, and several forms evade it. Review the queue in the viewer's **quarantined** filter.
284
300
 
285
- This is a heuristic review queue, not a prompt-injection detector: legitimate documentation can match, and several forms evade it. What the screen covers, what it misses, how an existing store is re-tagged, what releasing quarantine does and what it leaves alone, and why direct `memory_remember` and viewer edits are not scanned: [docs/import-quarantine.md](docs/import-quarantine.md).
301
+ What the screen covers, what it misses, how an existing store is re-tagged, what releasing quarantine does and what it leaves alone, and why direct `memory_remember` and viewer edits are not scanned: [docs/import-quarantine.md](docs/import-quarantine.md).
286
302
 
287
303
  ## Surfaces
288
304
 
@@ -291,38 +307,12 @@ Same data behind each one (`memory_status`; no model call).
291
307
  **Terminal (opencode CLI)** — the plugin ships a TUI half (`@opencode/plugin/tui`) that loads automatically:
292
308
 
293
309
  - **Footer badge** — illustrative `● 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, and `—` throughout on a provider that reports no cache usage.
294
- - **`/memory`** — session panel: **CONTEXT** (chars and estimated tokens riding now, % of budget, the full memory section riding the prompt — digest + frontier + block — 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.
310
+ - **`/memory`** — session panel: **CONTEXT** (what is riding the prompt now and how much of the budget it uses), **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.
295
311
  - **Block toast** when a write is refused (`"notifyBlocked": false` to silence).
296
312
 
297
313
  **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.
298
314
 
299
- **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.
300
-
301
- ## Installing a specific version
302
-
303
- 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.
304
-
305
- <details>
306
- <summary>Install from a clone (development)</summary>
307
-
308
- ```sh
309
- git clone https://github.com/abogartz/opencode-self-improvement.git
310
- cd opencode-self-improvement
311
- bun install
312
- ```
313
-
314
- Then point the `plugins` entry at the local file instead:
315
-
316
- ```json
317
- {
318
- "$schema": "https://opencode.ai/config.json",
319
- "plugins": ["/full/path/to/opencode-self-improvement/index.ts"]
320
- }
321
- ```
322
-
323
- After changes, `git pull` and restart opencode.
324
-
325
- </details>
315
+ **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. `OPENCODE_VIEWER_HOST` changes the bind interface.
326
316
 
327
317
  ## Development
328
318
 
@@ -332,30 +322,17 @@ Nothing merges without the full gate; CI runs it as required checks (`lint`, `te
332
322
  bun run gate # typecheck + lint + unit tests + terminal smoke & BDD
333
323
  bun run gate:hooks # once per clone: run the gate on `git push`
334
324
  bun run format # apply the shared two-space TypeScript/TSX style
335
- bun run format:check # check formatting without changing files
336
325
  ```
337
326
 
338
- `bun run typecheck` runs `tsc --noEmit` on its own. In CI it runs inside the job named `lint`, so a green `lint` check silently implies tsc. The rest of the mapping: `bun run test` is the `test` job (re-run in `test-windows`, which reports but cannot gate merges), and `bun run test:e2e` is the `smoke` job.
339
-
340
- `bun run lint` checks lint rules and TypeScript/TSX formatting; CI calls the same command. Lint warnings remain advisory, while formatting differences fail the check. Markdown commands, prose, JSON data and historical benchmark records are outside the formatter's scope.
341
-
342
- Use Bun **1.4.4** for development checks, matching CI. `bun run test` and `bun run test:e2e` run files across at most four worker processes with Bun's file isolation; cases inside each file stay sequential because fixtures share environment variables and module state. The local gate uses those same scripts. To diagnose order-dependent failures in the original shared-process mode, run `bun test ./test/` or `bun test ./e2e/ --timeout 240000` directly.
343
-
344
- **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.
327
+ Use Bun **1.4.4** for development checks, matching CI. `bun run test` and `bun run test:e2e` run files across at most four worker processes; cases inside each file stay sequential because fixtures share environment variables and module state.
345
328
 
346
- `e2e/` boots the **real opencode CLI** in a fully isolated instance against a scripted fake model — no API keys, no shared store. It needs `opencode` on `PATH` locally, or `OPENCODE_BIN`. A `test-windows` leg also runs the suite on Windows; it reports without gating merges.
329
+ **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. If no scenario turns red first, the feature has no observable contract.
347
330
 
348
- **The published surface is `package.json`.** `exports` is the only import surface other code can reach; `files` is the packaging list. A new top-level file, or anything the plugin reads at runtime outside those paths, must be added to `files` or it works from the checkout and vanishes from the npm artifact. What the smoke suite boots and how that miss turns red: [docs/development.md](docs/development.md).
331
+ `e2e/` boots the **real opencode CLI** in a fully isolated instance against a scripted fake model — no API keys, no shared store. It needs `opencode` on `PATH` locally, or `OPENCODE_BIN`.
349
332
 
350
- ### Before a release
333
+ **The published surface is `package.json`.** A new top-level file, or anything the plugin reads at runtime outside the packaged paths, must be added to `files` or it works from the checkout and vanishes from the npm artifact.
351
334
 
352
- ```sh
353
- bun scripts/test-sweep.ts --validate # every pattern still lands on one site
354
- bun scripts/test-sweep.ts --selftest # the instrument can still go red
355
- bun scripts/test-sweep.ts --fail-on-survivors # exits 4 when anything survives
356
- ```
357
-
358
- `scripts/test-sweep.ts` audits the test suite rather than the plugin: each mutant breaks exactly one claimed invariant in a detached worktree, and the suite has to notice. A mutant no test kills is an unpinned invariant — the audit's output, not a red check. The ritual and its cadence, why the sweep never belongs in CI, and which benchmark artifacts stay out of git: [docs/pre-release-ritual.md](docs/pre-release-ritual.md).
335
+ How the local commands map to CI job names, what the smoke suite really boots, and the pre-release mutation sweep with its artifact policy: [docs/development.md](docs/development.md) and [docs/pre-release-ritual.md](docs/pre-release-ritual.md).
359
336
 
360
337
  ## Troubleshooting
361
338
 
@@ -364,13 +341,9 @@ bun scripts/test-sweep.ts --fail-on-survivors # exits 4 when anything survive
364
341
  | `memory_*` tools not available | The plugin didn't load. Restart opencode and check the `plugins` entry in your config. |
365
342
  | `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. |
366
343
  | `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 (…)`). |
367
- | 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`. |
368
- | `memory store is busy` | A store write exhausted its 5s lock-wait budget. Appends, rewrites, and restores refuse that mutation rather than proceed unlocked and risk losing another writer's rows. Retry after contention clears. An operation spanning several files or steps may have completed earlier steps; refusal is not a rollback of those steps. If the reply reports `PARTIAL`, inspect the named rows and `memory_evidence` / `memory_undo` before retrying. A process that is killed releases the lock when it dies — there is no stale window to wait out. |
369
- | Stray `*.logfmt.lock` or `*.tmp` in the store | Write bookkeeping left by an older release; safe to delete while nothing is writing. Current releases leave `.store-lock.<file>.sqlite` beside each store file and `.store-batch.<name>.sqlite`: coordination state, holding no rows, one file per lock, safe to delete while nothing is writing. |
344
+ | `memory store is busy` | A store write exhausted its 5s lock-wait budget, so the mutation is refused rather than run unlocked. Retry after contention clears. An operation spanning several files or steps may have completed earlier steps; refusal is not a rollback of those steps. If the reply reports `PARTIAL`, inspect the named rows and `memory_evidence` / `memory_undo` before retrying. A process that is killed releases the lock when it dies — there is no stale window to wait out. |
370
345
  | Writes report a disk I/O error and the store is on a share | The lock's write-ahead log needs mmap'd shared memory, which SQLite does not support on network filesystems. SMB, NFS and OneDrive-mounted roots are unsupported — move `OPENCODE_MEMORY_DIR` to local disk. |
371
- | `/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. |
372
- | `memory_init` rejects a call naming `mode` | The code-graph integration was removed (#231) and the tool schema refuses unknown arguments — drop `mode` from the call. Stamps written by older versions (their text carries `graph=`/`mode=`) still read fine; no re-init is forced. |
373
346
  | Stale plugin after an update | `opencode plugin update opencode-self-improvement` (or bump the pinned `@version` in the `plugins` entry) and restart opencode. On desktop use `opencode service restart`: relaunching the app leaves the background service — and the plugin version and options it already parsed — alive. |
374
- | `Error: Plugin is not configured` right after `plugin add` | An opencode bug ([#54654](https://github.com/anomalyco/opencode/issues/54654)), not a config problem: the first `plugin list/check/update` against a cold background service reads the plugin inventory before activation finishes. The plugin is installed and loading — just run the command again. |
375
- | Auto-capture does nothing | Auto-capture is **experimental and has never fired on a verified live store** — see [Auto-capture is experimental](#auto-capture-is-experimental). `memory_evidence` says which case you are in from the `plugin_load` line: `capture=off` (option not on), `invalid_model` (`captureModel` must be `provider/id`; a bad one disables capture with a startup warning), `no_capabilities` (host did not expose what capture needs), or `capture=on`. `captureOnCompact` alone does nothing. `capture=on` with no `auto_capture_*` line after a session is the open bug, not your config. Rejected candidates log as evidence, not errors. On desktop, changing any of these options needs `opencode service restart`. |
376
- | Reset all memories | Stop any running opencode session first, then delete `~/.config/opencode/memory/`. On Windows the delete fails with `EBUSY` while a session is live: the store lock is an open SQLite connection, and Windows will not delete a directory that contains one. |
347
+ | Auto-capture does nothing | `memory_evidence` says which case you are in from the `plugin_load` line: `capture=on` (the default), `capture=off` (you set `autoCapture: false`), `invalid_model`, `no_capabilities` or `switch_mismatch`. `capture=on` with no `auto_capture_*` line after a session means the pass did not complete, and is not your configuration — see [Auto-capture](#auto-capture). On desktop, changing any of these options needs `opencode service restart`. |
348
+
349
+ `STORE` showing malformed rows, stray lock files in the store, a missing `/repo-init`, a `memory_init` call naming `mode`, `Error: Plugin is not configured` right after `plugin add`, and a clean reset on Windows: [docs/troubleshooting.md](docs/troubleshooting.md).
@@ -1,9 +1,16 @@
1
1
  # Auto-capture: what the evidence covers
2
2
 
3
+ Three different claims get confused constantly, so this file names them
4
+ separately: the event fires, the write survives, and a live store with a live
5
+ model completes a pass. The first two are shown. The third has never been
6
+ observed.
7
+
3
8
  What has been established about auto-capture, by what kind of evidence,
4
9
  and what remains unverified. The status and the arm/diagnose answer stay
5
10
  in the README; this is the record behind them.
6
11
 
12
+ ## What has been established
13
+
7
14
  What is established, from tests and fixtures (no live store involved):
8
15
 
9
16
  - **The trigger events are ones the host actually emits.** Capture subscribes to `session.execution.succeeded` and `session.execution.interrupted`, the two turn-end events present in a recording of the desktop service (`test/fixtures/host-events.jsonl`). `session.idle`, `session.status` and `session.execution.failed` are *declared* by the host but absent from that recording, so they deliberately do not trigger capture; `test/event-fidelity.test.ts` refuses a trigger that is only declared. An earlier revision subscribed to `session.idle` and stayed silent for days with no signal — reading a declared event as an emitted one is the failure that fixture exists to prevent.
@@ -16,7 +23,7 @@ What is established, from tests and fixtures (no live store involved):
16
23
 
17
24
  - **The availability policy is measured against its alternatives, and against its own measuring stick.** `bun run bench:availability` (`bench/availability-results.md`) runs one capture pass over a 197-row store five times — no check, tag (as shipped), drop-at-read (the P3 preview), drop-hardened, and the original rule replayed from the pinned `362655c` module — with the byte budget swept over five sizes and the background resampled at 0/30/90/180 rows, because a claim measured at one budget or one store size is a claim about that budget. Tagging keeps all 10 new transport facts and retrieves 14 of 14 retrievable queries at every budget and every store size, where the original rule keeps 6 of 10 and retrieves 7 at every budget: that rule deleted four of ten new facts on a command mention alone, and a deleted fact cannot be retrieved. The ceiling is stated next to every recall figure and measured on the exact rows the arms retrieve: 14 of the 21 curated transport queries retrieve their own gold when that gold is the ONLY row in the store, so the tag arm's 14 is the achievable maximum and 9/21 was never 43% recall. The counterfactual is printed beside it — strip the keywords the capture reply carries and the ceiling falls to 9/21, because five of these pairs are retrievable only through the keyword list. A 25-case bank of every adversarial verdict this matcher has been found guilty of is re-decided on every run, one repo per case, and asserted in `bun test` because CI runs no bench. Writing those controls found two defects in the bench itself — verdicts keyed on `ts`, which is not unique when a pass writes rows in one millisecond, and a byte column summed across 21 queries and labelled per-block — and the corrected numbers are in the file. The report also states what it cannot measure: the check marks 6 of 16 rows a pass writes and 0 of 180 background rows, and that 0 is a fixture artefact rather than a base rate, because no seeded row quotes the tracked tree. It also tests the tag's justification directly: empty the tracked text and all 6 verdicts disappear, which is the property a read-time policy would keep and a delete would not.
18
25
 
19
- What is not established:
26
+ ## What has not been established
20
27
 
21
28
  - That a live host with a live model completes a capture end to end. The event and the pass are no longer in doubt — `e2e/capture.test.ts` shows a real `opencode run` turn firing a real pass — but no `auto_capture_*` line and no `capture_lag` line exists anywhere in the maintainer's evidence history (checked 2026-10-26 through 2026-10-29), and #404 found the mechanism by which a CLI session would produce none even when everything else works — the fix is on this branch, but no live store has been observed completing a pass yet. A live trial armed on 2026-10-26 was stood down on 2026-10-29 without ever firing, so it answered nothing.
22
29
  - Anything about quality on a live store. What auto-capture would write, how often it duplicates a memory you would have written yourself, and what it costs remain unmeasured. `bench/capture-trigger-results.md` is a **bench** simulation of trigger *timing* with a scripted extractor — its compaction world captured 0 rows and 4 of its 6 controls report FAIL. It answers "which moment is worth mining", not "does the shipped feature work".
@@ -1,8 +1,36 @@
1
1
  # Contradiction authority: the code check and its limits
2
2
 
3
- The scan behind a CONFLICT verdict, what it refuses to decide, and what is
4
- accepted as residual risk. The verdict table stays in the README.
3
+ You say the retry limit has to be `5`; the code says `3`. Before the plugin
4
+ takes sides it has to be sure it is reading a real declaration, so the check is
5
+ deliberately narrow — and what it refuses to decide is the more useful half of
6
+ this document.
5
7
 
6
- The code check accepts a unique top-level `const` with a literal value. Comments, string examples, local declarations and computed expressions cannot establish an authority verdict. The scan is limited to 300 source files, 256 KiB per file and depth 3, preferring `src/`; it does not follow source links or resolve imports. Ambiguous declarations, unreadable/invalid source, exhausted budgets or an undecidable claim keep the plain guidance and staleness caveat. The JavaScript/TypeScript parser loads only when a row needs a code check; explicit opt-out never loads it. Use attribution keeps the stored row's identity and prose while coverage counts only references present in the delivered text.
8
+ The verdict table stays in the README.
7
9
 
8
- Accepted residual: a user-stated **wrong spec** still classifies as `spec`. Its verdict follows that stated requirement even if it breaks the current tests. The plugin does not infer hidden-suite authority or silently override the user's requirement. Asking an oracle or inventing an extra authority class is outside this contract. Capture classification can be wrong; a code comparison verifies a value mismatch, not the user's intent. Per the [maintainer's rollout decision](https://github.com/abogartz/opencode-self-improvement/pull/363#pullrequestreview-5819556342), the default is ON for full benchmarking after merge and can be revisited. The seat-model and merged-main confidence runs in #350–#352 remain outstanding; enabling the feature is not a claim that those benchmarks passed.
10
+ ## What the check will read
11
+
12
+ One thing: a unique top-level `const` with a literal value. Comments, string
13
+ examples, local declarations and computed expressions cannot establish an
14
+ authority verdict. The scan is bounded to 300 source files, 256 KiB per file
15
+ and depth 3, preferring `src/`, and it does not follow source links or resolve
16
+ imports.
17
+
18
+ Anything it cannot settle — an ambiguous declaration, unreadable or invalid
19
+ source, an exhausted budget, a claim outside its reach — keeps the plain
20
+ guidance and its staleness caveat and emits no verdict. The JavaScript/TypeScript
21
+ parser loads only when a row needs a code check; an explicit opt-out never
22
+ loads it. Use attribution keeps the stored row's identity and prose while
23
+ coverage counts only references present in the delivered text.
24
+
25
+ ## The residual, accepted
26
+
27
+ A user-stated **wrong spec** still classifies as `spec`, and its verdict
28
+ follows that stated requirement even if it breaks the current tests. The plugin
29
+ does not infer a hidden test suite's authority and does not silently override
30
+ the user's requirement. Asking an oracle or inventing an extra authority class
31
+ is outside this contract.
32
+
33
+ Classification can also simply be wrong: a code comparison verifies a value
34
+ mismatch, not the user's intent.
35
+
36
+ Per the [maintainer's rollout decision](https://github.com/abogartz/opencode-self-improvement/pull/363#pullrequestreview-5819556342), the default is ON for full benchmarking after merge and can be revisited. The seat-model and merged-main confidence runs in #350–#352 remain outstanding; enabling the feature is not a claim that those benchmarks passed.
@@ -1,8 +1,28 @@
1
1
  # Development internals
2
2
 
3
- What the smoke suite really boots, and how the published npm surface is
4
- decided. The commands and the BDD-first rule stay in the README.
3
+ What the local commands really run, what the smoke suite boots, and how the
4
+ published npm surface is decided. The commands themselves and the BDD-first
5
+ rule stay in the README.
6
+
7
+ ## Local command to CI job
8
+
9
+ | Local command | Where it runs in CI | Gates a merge |
10
+ | --- | --- | --- |
11
+ | `bun run typecheck` | inside the job named `lint` | yes, under that name |
12
+ | `bun run lint` | `lint` | yes |
13
+ | `bun run test` | `test`, re-run in `test-windows` | `test` yes; `test-windows` reports only |
14
+ | `bun run test:e2e` | `smoke` | yes |
15
+
16
+ `tsc --noEmit` has no check of its own in CI — it runs inside `lint`, so a green `lint` silently implies a green typecheck.
17
+
18
+ `bun run lint` checks lint rules and TypeScript/TSX formatting, and CI calls the same command. Lint warnings stay advisory; formatting differences fail the check. Markdown commands, prose, JSON data and historical benchmark records are outside the formatter's scope.
19
+
20
+ The test scripts run files across at most four worker processes with Bun's file isolation. To reproduce an order-dependent failure the way it would appear in one shared process, run `bun test ./test/` or `bun test ./e2e/ --timeout 240000` directly.
21
+
22
+ ## What the smoke suite boots
5
23
 
6
24
  `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.
7
25
 
8
- **The published surface is defined in `package.json`.** `exports` is the only import surface other code can reach (`.` → `index.ts`, `./tui` → `src/tui/panel.tsx`); `files` is the packaging list. `files` covers `src/`, so anything reachable from an `exports` target ships, but a new top-level file or directory — or anything the plugin reads at runtime outside those paths — must be added to `files` or it works from the checkout and vanishes from the npm artifact. The packed-artifact load in `e2e/` turns that miss red.
26
+ ## The published surface is `package.json`
27
+
28
+ `exports` is the only import surface other code can reach (`.` → `index.ts`, `./tui` → `src/tui/panel.tsx`); `files` is the packaging list. `files` covers `src/`, so anything reachable from an `exports` target ships, but a new top-level file or directory — or anything the plugin reads at runtime outside those paths — must be added to `files` or it works from the checkout and vanishes from the npm artifact. The packed-artifact load in `e2e/` turns that miss red.
package/docs/flags.md CHANGED
@@ -4,6 +4,13 @@ The three flags that encode a measured finding rather than a preference:
4
4
  what each one enforces, the evidence behind it, and what an invalid value
5
5
  does. The README's table gives the default and the effect.
6
6
 
7
+ `OPENCODE_MEMORY_SYMPTOM` is the clearest case. A lesson saved as "in this
8
+ session we fixed the flaky test" shares no words with the query a future
9
+ session types, so it gets filed and never found: measured, 0 of 8 diary-shaped
10
+ rows surfaced, against ranks 1–7 when the same lesson opens with the symptom.
11
+ The flag therefore refuses the diary form at the write gate instead of storing
12
+ something unrecoverable.
13
+
7
14
  ## Flag behaviour
8
15
 
9
16
  | Variable | Full behaviour |
@@ -1,5 +1,8 @@
1
1
  # Import, quarantine and the viewer's edit path
2
2
 
3
+ A quarantined row is a spam-folder row, not a deleted one: it stays in the
4
+ store where you can read it, and is withheld from everything the model reads.
5
+
3
6
  What the prose screen catches and misses, how an existing store gets
4
7
  re-tagged, what releasing quarantine does, and which writes it does not
5
8
  cover. The README keeps the export/import contract and the tally.
@@ -18,4 +21,16 @@ The viewer is a trusted admin editor: its edits and deleted-entry restores do no
18
21
 
19
22
  Existing stores are not rescanned. A byte-identical import that collapses into an existing row does not retroactively tag that row. Export preserves quarantined rows and their tags to avoid data loss; an exported released row can be quarantined again when re-import promotes it on another machine.
20
23
 
21
- 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.
24
+ ## The file format, and what an import will believe
25
+
26
+ A header line (`{_export, version, exportedAt, count}`) followed by one JSON object per line (`{ts,type,scope,content,status,tags,issue}`), active rows only.
27
+
28
+ An open row is exempt from reference grounding, so that status is honored only for files carrying an export header — a hand-written file without one imports such rows as settled. 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.
29
+
30
+ ## Keeping a path inside the store
31
+
32
+ Both tools are model-facing, so a path is treated as untrusted input rather than as permission. An export cannot write to `~/.gitconfig` or anywhere else outside the store, and an import cannot read outside it. Symbolic links are resolved before the check — including an `exports/` directory that is itself a link — so a link cannot carry a request out of the store. Exports are written `0600` and opened `O_NOFOLLOW` (both POSIX; on Windows the check before the write is the only guard).
33
+
34
+ The default name is `<memory-root>/exports/<timestamp>-<unique>.jsonl`, created exclusively, so two exports in the same second never replace each other's artifact.
35
+
36
+ Two limits no path check can close. A hard link planted inside `exports/` shares an inode with its target, so writing through it writes the target. And the check covers the final component more tightly than the intermediate path components, leaving a narrow window there. Both are stated rather than fixed because closing them means giving up the feature.
@@ -1,9 +1,14 @@
1
1
  # Injection epochs and their measured cost
2
2
 
3
+ Prompt caching turns a boring question into an expensive one: how often do the
4
+ bytes in front of the model actually change? The plugin's answer is to freeze
5
+ the memory section and re-render only when the frozen bytes would genuinely
6
+ differ — the same reason you cache an HTTP response by its body rather than by
7
+ how many times the database was touched.
8
+
9
+ Every figure here is bytes on a synthetic workload: not tokens, not a bill.
3
10
  The epoch mechanism, the deterministic byte workload behind the injection
4
- claim, and a provider audit reported by its author. Every figure here keeps
5
- the label it carried in the README: bytes are bytes, not tokens and not a
6
- bill.
11
+ claim, and a provider audit reported by its author.
7
12
 
8
13
  - **Section-frozen injection.** The whole memory section — standing digest, open-thread frontier, relevance block — is computed once per epoch and delivered byte-identically until something the model actually needs changes. The epoch's authority is the **rendered bytes**, not the store fingerprint: a promoted row that changes nothing visible costs no cache bust.
9
14
  - **A session never pays for bytes it is not riding.** A memory *you* saved in this session is a fact you already produced — it is in your own transcript — so it never busts your cache. The test is not "did the store change" but "would the frozen bytes still have been produced from the same inputs, minus the rows this session authored since": a correction, blocklisting, redaction or supersession of a row you are riding, and anything another session, the viewer or an import wrote, all still land on your next request.
@@ -15,7 +20,7 @@ bill.
15
20
  - **Nothing volatile on the cached prefix.** The standing digest carries no row count and no latest timestamp. Both used to ride the very front of the system prompt, so every saved memory rewrote the prefix and made the next request re-bill the whole conversation; the exact numbers now live where they are free — the footer badge, `/memory`, `memory_status`, the viewer.
16
21
  - **Evidence is never injected**, and the standing system digest is two lines.
17
22
  - **Measured, not claimed.** The plugin reads each turn's `tokens.cache` accounting and displays the actual hit rate next to the badge. The same receipts now carry what the session generated — `output` and `reasoning`, shown split, because on a reasoning-heavy seat the completion side is where the cost actually goes. A host that reports neither shows nothing, never a zero.
18
- - **Auto-capture bills separately, and it is an estimate.** Capture is its own model call made after the turn, so it appears in no session's usage: read from session numbers, the plugin's own cost is exactly zero. The host exposes no receipt for it — `ctx.generate` has one member, `text`, resolving to `{ text }` with no `usage` — so `memory_status` reports chars/4 with `receipt=none` and the words "estimate, no provider receipt" on the line. Quote that number as an estimate or not at all. A pass disposed during teardown is not billed: its store is already gone, so the count undercounts by one call there.
23
+ - **Auto-capture bills separately, and it is an estimate.** Capture is its own model call made after the turn, so it appears in no session's usage: read from session numbers, the plugin's own cost is exactly zero. That reading is the misleading one — auto-capture is on by default, so the call happens on installs that never set an option. The host exposes no receipt for it — `ctx.generate` has one member, `text`, resolving to `{ text }` with no `usage` — so `memory_status` reports chars/4 with `receipt=none` and the words "estimate, no provider receipt" on the line. Quote that number as an estimate or not at all. A pass disposed during teardown is not billed: its store is already gone, so the count undercounts by one call there.
19
24
 
20
25
  **Bench** — deterministic workload (50 memories, 20 prompts, 3 mid-session store writes made *by the measured session*) through the plugin's real injection code. Every column is measured on the full memory section — the bytes a request actually sends — because prompt caching is a property of those bytes:
21
26
 
@@ -0,0 +1,41 @@
1
+ # Options and environment variables
2
+
3
+ Every knob, in one place. The README keeps the ones you are likely to set; this
4
+ file is the complete reference, including what an invalid value does.
5
+
6
+ ## Plugin options
7
+
8
+ Set them in the object form of the plugin entry in `opencode.json(c)`:
9
+
10
+ ```json
11
+ {
12
+ "plugins": [{ "package": "opencode-self-improvement", "options": { "injectBudget": 1200, "frontierBudget": 3600 } }]
13
+ }
14
+ ```
15
+
16
+ | Option | Default | What it does |
17
+ | --- | --- | --- |
18
+ | `injectBudget` | `1200` | Character cap on the injected relevance block and each contextual pull; trimmed at whole-memory boundaries. Env fallback: `OPENCODE_MEMORY_INJECT_BUDGET`. |
19
+ | `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`. |
20
+ | `contradictionSurface` | `true` | Experimental: compare guided constant claims with bounded source reads and render a class-specific CONFLICT verdict. Set `false` to skip code checks and retain plain guidance. See [docs/contradiction-authority.md](contradiction-authority.md). |
21
+ | `notifyBlocked` | `true` | Terminal (TUI) only: toast when a write gate blocks a write. Blocks are always in `memory_evidence` either way. |
22
+ | `autoCapture` | `true` | Master switch for auto-capture. On, so a plain install mines turn ends and compactions. Set `false` for no capture model call at all. |
23
+ | `captureModel` | inherits | `"provider/id"` model used for auto-capture. Unset means the model the session is using, else the host default. An explicit value that is not `provider/id` disables capture with a startup warning rather than substituting a model. |
24
+ | `captureMax` | `3` | Maximum candidates proposed per capture pass. |
25
+ | `captureOnCompact` | `true` | When auto-capture is armed, also mine the transcript at compaction, before the summarizer replaces it. Its 5-minute cooldown is separate from the turn-end one, so the two triggers' hit-rates stay measurable. Setting it while `autoCapture` is `false` does nothing and reports `switch_mismatch` on the `plugin_load` line. |
26
+ | `captureGuidedRules` | `false` | POC: deterministic guided-candidate pre-pass. The user's own lines decide which stated values or rules are guided (numbers, rates, currency, explicit rule assertions) and attach the verbatim quote; the capture model may phrase such a row but cannot clear the flag or the quote, and a guided quote the user never wrote is refused at the write boundary instead of silently stripped. Fires alongside the model pass only — no extra model calls. |
27
+
28
+ ## Environment variables
29
+
30
+ | Variable | Purpose |
31
+ | --- | --- |
32
+ | `OPENCODE_MEMORY_DIR` | Store location (default `~/.config/opencode/memory`). |
33
+ | `OPENCODE_MEMORY_ALLOW_OUTSIDE_PATHS` | Operator-only. When truthy, `memory_export`/`memory_import` accept paths anywhere on disk instead of confining themselves to the store. Off by default. It is read from the plugin process's own environment, so a model cannot grant it to itself through a tool argument. See [docs/import-quarantine.md](import-quarantine.md). |
34
+ | `OPENCODE_MEMORY_INJECT_BUDGET` | Fallback for `injectBudget`. |
35
+ | `OPENCODE_MEMORY_FRONTIER_BUDGET` | Fallback for `frontierBudget`. |
36
+ | `OPENCODE_COMMANDS_DIR` | Where the plugin mirrors its slash commands (default `~/.config/opencode/commands`). |
37
+ | `OPENCODE_VIEWER_HOST` | Interface the editor binds to (default `127.0.0.1`). A non-loopback bind serves the store over plain HTTP with no authentication — only do it on a network you control. |
38
+ | `OPENCODE_VIEWER_PORT` | Admin editor port (default `8787`). |
39
+ | `OPENCODE_VIEWER_ALLOWED_HOSTS` | Comma-separated hosts beyond loopback. |
40
+
41
+ `OPENCODE_MEMORY_DEDUP`, `OPENCODE_MEMORY_SYMPTOM` and `OPENCODE_MEMORY_QUERY_GATE` are documented separately in [docs/flags.md](flags.md): they switch behaviour that a measurement decided, so the evidence behind each one matters more than the default.
@@ -1,5 +1,9 @@
1
1
  # Pre-release ritual: mutation sweep and artifact policy
2
2
 
3
+ A fire drill for the test suite: break one claimed invariant on purpose and
4
+ see whether anything notices. A mutant that no test kills is not a scandal —
5
+ it is a list of what the suite has been claiming without pinning.
6
+
3
7
  What `scripts/test-sweep.ts` measures, when a person runs it, and which
4
8
  benchmark artifacts stay out of git.
5
9
 
@@ -0,0 +1,52 @@
1
+ # Recall quality: what the keyword matcher gives up
2
+
3
+ A keyword matcher finds a memory when the words overlap. That is its whole
4
+ trick, and its whole weakness: "how we deploy" and "ship to staging" are the
5
+ same fact with no word in common. This file is what that costs, measured, and
6
+ what you can do about it at write time.
7
+
8
+ The headline table stays in the README. Full methodology and all store sizes:
9
+ `bench/recall-results.md`, reproduced with `bun run bench:recall`.
10
+
11
+ ## Write-time keywords are the answer to paraphrase
12
+
13
+ `memory_remember` asks each row for 3–5 `kw` aliases: other names for the same
14
+ thing, other verb forms, the literal command. Keywords are indexed and never
15
+ rendered into the prompt, so they cost nothing to store and nothing to inject.
16
+
17
+ **Bench** — the same matcher over the same store, with the only changed
18
+ variable being the index:
19
+
20
+ - strict (zero shared words) R@1 0% → 26%
21
+ - near (one overlap) R@1 28% → 67%
22
+
23
+ A permutation control — every row given someone else's aliases — scores
24
+ 29%/35%, so the gain is meaning rather than extra tokens. Auto-capture asks for
25
+ the same list, so these numbers are measured through the tool path rather than
26
+ through capture. The limit is narrowed, not removed.
27
+
28
+ ## Abstaining is a feature
29
+
30
+ Free-text prompts that share one concept with a memory abstain rather than
31
+ force a guess. Wrong top-memory fell to 6%. The cost is silence in cases where
32
+ a lucky guess would have been right; `memory_recall` still covers them when you
33
+ ask on purpose.
34
+
35
+ ## Why the default window is 5 rows
36
+
37
+ A live audit joined 1,090 recall events to their session transcripts. A
38
+ returned row at rank 1 shows up in a later tool call at 3.4x the rate of a
39
+ random store row, ranks 2–3 at 2.4x, and ranks 11–20 at 1.16x — noise against a
40
+ 0.129 null. The old default returned 17.7 rows per call, so most of the window
41
+ was context nobody read.
42
+
43
+ At limit 5, recall@1 and recall@3 are unchanged, precision rises 4.1% → 13.1%,
44
+ and 74% of the returned characters disappear. Every gold row the cut dropped sat
45
+ at ranks 6–20. Pass `limit` for a wider sweep ([#409](https://github.com/abogartz/opencode-self-improvement/issues/409)).
46
+
47
+ ## Caveats on the eval
48
+
49
+ The dataset is synthetic — 52 memories and 105 queries about a fictional
50
+ project — its class mix is deliberately adversarial, and scoring is
51
+ single-gold. Read the numbers as a comparison between matchers on one fixed
52
+ set, not as a prediction about your repository.
@@ -1,11 +1,35 @@
1
1
  # Repo scoping: identity, visibility and write refusal
2
2
 
3
- How a row's repository is derived and matched, which surfaces see what, and
4
- why an unresolved session has no write target. The README states the rule;
5
- this is the boundary detail.
3
+ Every row carries a label saying which repository wrote it. The label is
4
+ checked on the way in as well as the way out, and the two directions are not
5
+ symmetric: reading one extra project's memories is a nuisance, while writing
6
+ your private note into the wrong project is damage. So reads are permissive and
7
+ writes are strict.
8
+
9
+ The README states the rule; this is the boundary detail.
10
+
11
+ ## Identity
6
12
 
7
13
  Legacy whole-path-lowercased hashes accompanied by `repoPath` are matched to that directory (including real aliases), so a distinct case-sensitive sibling cannot inherit its memories or evidence. Remote-derived identities still share across clones. Stamps without `repoPath` retain key-only matching; their historical identity source cannot be recovered from the key alone.
8
14
 
9
- Injection, recall, the frontier block, compaction, `memory_forget` and decay only see the current repo plus global rows, resolved from the calling session's identity at flow entry. A session that reaches a plugin instance is bound to that instance's own workspace on first contact — in a process hosting several workspaces, one session never borrows the repository some other workspace's setup left behind. A session whose repository cannot be resolved at all sees global rows only; "unknown" is never "everything". Writes follow that rule in the stricter direction: a named session with no resolved repository has **no write target**, so `memory_remember`, `memory_update`, `memory_import` and auto-capture refuse it (evidence `write_refused`) and store nothing — the alternatives were stamping your private content into whichever workspace's `setup()` ran last, or publishing it to every project as an unstamped row. A caller that names no session at all (the viewer process, a restore, a script) keeps the process scope, and an explicit `global: true` is a deliberate owner. Evidence lines carry the same stamp, so `memory_evidence` answers from the caller's repo plus global lines; a line a named session wrote while its repository was unresolvable is private to that session, and only an explicitly global (or predating-stamps) line reads as global. Preferences that should follow you everywhere go in with `memory_remember global: true`. Rows written before scoping existed are global, and the viewer (an admin surface over every repo) edits and restores a row with its own repo stamp — the viewer's missing session scope never decides a row's visibility. `memory_merge_review` applies the same rule to its inputs: a session may merge exactly the rows it may read — global rows plus its own repo's, from either seat — and a row id it merely knows is not authority to retire another repo's memory. Upgrading changes nothing.
15
+ ## Who sees what
16
+
17
+ Injection, recall, the frontier block, compaction, `memory_forget` and decay only see the current repo plus global rows, resolved from the calling session's identity at flow entry. A session that reaches a plugin instance is bound to that instance's own workspace on first contact — in a process hosting several workspaces, one session never borrows the repository some other workspace's setup left behind. A session whose repository cannot be resolved at all sees global rows only; "unknown" is never "everything".
18
+
19
+ ## Why an unresolved session cannot write
20
+
21
+ Writes follow that rule in the stricter direction. A named session with no resolved repository has **no write target**, so `memory_remember`, `memory_update`, `memory_import` and auto-capture refuse it (evidence `write_refused`) and store nothing. The alternatives were stamping your private content into whichever workspace's `setup()` ran last, or publishing it to every project as an unstamped row.
22
+
23
+ A caller that names no session at all (the viewer process, a restore, a script) keeps the process scope, and an explicit `global: true` is a deliberate owner. Preferences that should follow you everywhere go in with `memory_remember global: true`. Rows written before scoping existed are global. Upgrading changes nothing.
24
+
25
+ `memory_merge_review` applies the same rule to its inputs: a session may merge exactly the rows it may read — global rows plus its own repo's, from either seat — and a row id it merely knows is not authority to retire another repo's memory.
26
+
27
+ ## Evidence attribution
28
+
29
+ Evidence lines carry the same stamp, so `memory_evidence` answers from the caller's repo plus global lines; a line a named session wrote while its repository was unresolvable is private to that session, and only an explicitly global (or predating-stamps) line reads as global.
30
+
31
+ Gate-authored evidence and its init/capture lifecycle records capture attribution at operation entry: if a session moves repositories while the operation runs, its audit lines remain in the starting repository's partition and can be read with `memory_evidence` from a session bound there. Init start/complete/skip, capture outcomes/refusals, and capture lag share that captured owner. A captured named session with no resolved repository keeps a session-private `sid` label even on lifecycle records that suppress call metadata; otherwise an unstamped line would appear global.
32
+
33
+ ## The viewer
10
34
 
11
- Gate-authored evidence and its init/capture lifecycle records capture attribution at operation entry: if a session moves repositories while the operation runs, its audit lines remain in the starting repository's partition and can be read with `memory_evidence` from a session bound there. Init start/complete/skip, capture outcomes/refusals, and capture lag share that captured owner. A captured named session with no resolved repository keeps a session-private `sid` label even on lifecycle records that suppress call metadata; otherwise an unstamped line would appear global. Viewer audit attribution and cancellation of in-flight capture are separate boundaries.
35
+ The viewer is an admin surface over every repo: it edits and restores a row with its own repo stamp, and the viewer's missing session scope never decides a row's visibility. Viewer audit attribution and cancellation of in-flight capture are separate boundaries.
@@ -1,5 +1,10 @@
1
1
  # Store concurrency, publication and permissions
2
2
 
3
+ Replacing a store file while other sessions are reading it is the whole
4
+ problem. The answer is a book swap, not a page rewrite: the writer builds the
5
+ complete new file, then swaps it in under a lock. A reader therefore sees the
6
+ old file or the new one, never a half-written record.
7
+
3
8
  How a store file is replaced, what the lock covers, and what the plugin
4
9
  does and does not do about permissions. The README states the user-visible
5
10
  rules and links here.
@@ -10,4 +15,12 @@ The lock covers one **file**, not the store directory. Two sessions writing diff
10
15
 
11
16
  Two unsupported placements. The write-ahead log needs mmap'd shared memory, which SQLite does not provide on network filesystems, so a memory root on SMB, NFS or a OneDrive-mounted folder is **not supported**: writes there can report a disk I/O error rather than serialise. Configure `OPENCODE_MEMORY_DIR` on local disk. And during the update that introduced this lock, a session still running the previous release honours `<date>.logfmt.lock` while an updated session honours the SQLite lock, so those two do not exclude each other until every running session has restarted.
12
17
 
13
- On POSIX systems, new store directories use owner-only `0700` permissions and new files use `0600` (subject to a more restrictive umask). This includes temporary replacements, snapshots, locks (the lock database beside each store file), status files, and append-only logs. Accessing an existing store attempts to remove group/other permissions from its root; existing directories and appended/status files are tightened when written, without adding owner permissions. Old descendants are not recursively migrated: a successfully tightened root prevents other users from traversing to them. If directory chmod reports `EPERM`, `EROFS`, `EOPNOTSUPP`, or `ENOSYS` (for example an immutable or foreign-owned root, or a mount without chmod support), reads remain available with the existing permissions: owner-only traversal is not guaranteed. Correct ownership, mount support, or permissions outside the plugin when that privacy guarantee is required. File permission enforcement on writes remains unchanged. Existing ancestors outside the store are left unchanged. A store root that is itself a symlink is refused; configure its real directory instead. These modes do not revoke already-open handles or protect copies/hard links outside the private root. On Windows, privacy depends on the directory's ACL; the plugin does not change Windows ACLs.
18
+ On POSIX systems, new store directories use owner-only `0700` permissions and new files use `0600` (subject to a more restrictive umask) — including temporary replacements, snapshots, locks, status files and append-only logs. Accessing an existing store removes group/other permissions from its root, and tightens directories and files as they are written. Old descendants are not migrated recursively: a tightened root already stops other users from reaching them.
19
+
20
+ Three limits on that guarantee, stated plainly because they are privacy limits.
21
+
22
+ 1. If chmod reports `EPERM`, `EROFS`, `EOPNOTSUPP` or `ENOSYS` — an immutable root, a foreign-owned root, or a mount without chmod support — reads stay available under the existing permissions, so owner-only traversal is **not** guaranteed. Fix ownership, mount support or permissions outside the plugin when that guarantee is required.
23
+ 2. The modes do not revoke handles that are already open, and they do not protect copies or hard links made outside the private root.
24
+ 3. On Windows the plugin changes no ACLs; privacy there depends entirely on the directory's existing ACL.
25
+
26
+ A store root that is itself a symlink is refused; configure its real directory instead. Ancestors outside the store are left as they are.
@@ -0,0 +1,22 @@
1
+ # Troubleshooting, full list
2
+
3
+ The README keeps the problems people actually run into. This file holds the
4
+ rarer ones, and repeats the common ones so one search finds the whole list.
5
+
6
+ ## Rarer problems
7
+
8
+ | Problem | Fix |
9
+ | --- | --- |
10
+ | 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`. |
11
+ | Stray `*.logfmt.lock` or `*.tmp` in the store | Write bookkeeping left by an older release; safe to delete while nothing is writing. Current releases leave `.store-lock.<file>.sqlite` beside each store file and `.store-batch.<name>.sqlite`: coordination state, holding no rows, one file per lock, safe to delete while nothing is writing. |
12
+ | `/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. |
13
+ | `memory_init` rejects a call naming `mode` | The code-graph integration was removed (#231) and the tool schema refuses unknown arguments — drop `mode` from the call. Stamps written by older versions (their text carries `graph=`/`mode=`) still read fine; no re-init is forced. |
14
+ | `Error: Plugin is not configured` right after `plugin add` | An opencode bug ([#54654](https://github.com/anomalyco/opencode/issues/54654)), not a config problem: the first `plugin list/check/update` against a cold background service reads the plugin inventory before activation finishes. The plugin is installed and loading — just run the command again. |
15
+ | Reset all memories | Stop any running opencode session first, then delete `~/.config/opencode/memory/`. On Windows the delete fails with `EBUSY` while a session is live: the store lock is an open SQLite connection, and Windows will not delete a directory that contains one. |
16
+
17
+ ## Common problems
18
+
19
+ Kept in [README → Troubleshooting](../README.md#troubleshooting): tools not
20
+ available, a blocked `memory_remember`, an argument-schema rejection,
21
+ `memory store is busy`, a store on a network share, a stale plugin after an
22
+ update, and auto-capture doing nothing.
@@ -0,0 +1,50 @@
1
+ # The use ledger
2
+
3
+ A due-date card for every row: who looked at it, when, and how it reached them.
4
+ It answers one question you cannot answer any other way — is this memory
5
+ earning its place, or has nothing touched it in six months?
6
+
7
+ The ledger is `<memory-root>/hits.logfmt`: append-only, rotated at 2 MB, never
8
+ ingested as a memory, and reported in `memory_status` and the `/memory` panel.
9
+
10
+ ## What counts as use
11
+
12
+ Credit comes from three distinct sources, because "the model asked" and "the
13
+ harness offered" are different facts:
14
+
15
+ 1. the row rode the injected block;
16
+ 2. `memory_recall` returned it;
17
+ 3. a grep/read pull appended it.
18
+
19
+ Credit requires ≥2 shared terms with the query and is throttled to one line per
20
+ memory per session per source per hour, so one busy session cannot inflate a
21
+ row's standing.
22
+
23
+ **No prompt content is stored.** The ledger keeps a scan-truncated string from
24
+ the *memory* side, never your message.
25
+
26
+ ## What use is allowed to do
27
+
28
+ Reinforcement is a tie-break only (`useBoost ≤ 1.0`): a recently used row wins a
29
+ tie and can never outrank a real score gap. In consolidation, the most recently
30
+ used member of a cluster is never the merge loser.
31
+
32
+ `never retrieved` is stated, not acted on. Pruning is your decision, and retired
33
+ rows cannot inherit reinforcement: ledger rows are verified against the store on
34
+ read.
35
+
36
+ ## Whose numbers these are
37
+
38
+ Aggregate STORE counts are machine-wide by decision (#213 B): they count every
39
+ repository's rows in the shared store on this machine, never just the reading
40
+ session's repository. The numbers describe the store, not your slice of it.
41
+
42
+ Privacy applies to the content surfaces instead. `memory_evidence` and the
43
+ recent-blocked-writes list in `memory_status` and `/memory` follow each reader's
44
+ repository visibility (#306).
45
+
46
+ ## Capture lag
47
+
48
+ Capture lag is how stale the newest message was when auto-capture fired. The
49
+ line prints only when at least one `capture_lag` sample exists, which needs
50
+ auto-capture to have fired.
@@ -1,6 +1,21 @@
1
1
  # Write gates and promotion evidence
2
2
 
3
- What promotion evidence samples, and how the four gates order their audit
4
- lines. The gate list and the undo contract stay in the README.
3
+ A memory is a claim about your code, so it is checked the way a pull request
4
+ is: does the reference resolve, is something already on file stale, is it a
5
+ duplicate, and does it land or come back with a reason. The four gates and the
6
+ undo contract stay in the README. This file is what the audit trail keeps, and
7
+ what an update carries with it.
8
+
9
+ ## What promotion evidence samples
5
10
 
6
11
  Promotion evidence keeps a bounded sample of call IDs: the ten most recent code-engagement calls, plus the latest gate check, the latest recorded gate FAIL/fix/PASS recovery, and the latest recorded tool FAIL/PASS retry (at most 16 distinct IDs). `evidence_refs_count` is the total number of recorded session calls before sampling, including non-code tools; the sampled IDs are audit pointers, not a complete history. Grounding and memory attribution still use the full in-memory ledger. Existing evidence day-files are left unchanged: this upgrade does not backfill, compact, or delete historical audit records.
12
+
13
+ ## What an update carries forward
14
+
15
+ `memory_update` picks its row by `query`: the row's id, a clock fragment such as `00:11:22.123`, or a unique substring of its text. Omit it and the newest entry of that scope and type is the target. A query that matches nothing, or that matches several rows, writes nothing and says so — an ambiguous selector is never resolved by picking one.
16
+
17
+ A prose edit carries the previous row's ordinary tags, issue link, retrieval keywords, open/settled standing and repository forward to the new row, so updating a `global` row from one machine keeps it global for every other. Capture-only guidance provenance is stripped by the replacement: an ordinary edit cannot re-mint a `user-guided` tag or a contradiction verdict.
18
+
19
+ Naming a row that an earlier update already superseded reports the duplicate when the live successor already holds exactly that content. When only the metadata you named differs, the update runs against the successor instead of dead-ending.
20
+
21
+ If a failure happens after the new row is already durable, the reply says `PARTIAL`. The message names what failed, the replacement stands on disk, and `memory_undo` (merge or force) brings the old row back.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.30.5",
3
+ "version": "0.31.0",
4
4
  "description": "Durable memory for opencode: remember facts, decisions, and commands across sessions, plus a one-command per-repo setup (/repo-init).",
5
5
  "main": "index.ts",
6
6
  "exports": {
@@ -1,5 +1,5 @@
1
1
  // candidates — split from src/capture.ts. Declaration bodies are unchanged.
2
- // Opt-in auto-capture parsing, prompt, and lag helpers. Host access and model
2
+ // Auto-capture parsing, prompt, and lag helpers. Host access and model
3
3
  // calls live in src/index.ts. Every candidate that leaves this module flows
4
4
  // through runWriteGate in index.ts: capture NEVER writes memories directly,
5
5
  // so dupes/stale/canonical rules keep the moat (same as model-authored writes).
@@ -1,5 +1,5 @@
1
1
  // prompt — split from src/capture.ts. Declaration bodies are unchanged.
2
- // Opt-in auto-capture parsing, prompt, and lag helpers. Host access and model
2
+ // Auto-capture parsing, prompt, and lag helpers. Host access and model
3
3
  // calls live in src/index.ts. Every candidate that leaves this module flows
4
4
  // through runWriteGate in index.ts: capture NEVER writes memories directly,
5
5
  // so dupes/stale/canonical rules keep the moat (same as model-authored writes).
@@ -190,28 +190,29 @@ export function configureAutoCapture(
190
190
  ) {
191
191
  let onCompactCapture: ((sid: string, messages: unknown) => void) | undefined;
192
192
  let captureCleanup: Cleanup | undefined;
193
- if (ctx.options?.autoCapture === true) {
194
- const captureModelOpt = ctx.options.captureModel;
195
- // an OMITTED captureModel no longer disables the subscription. It
193
+ const options = ctx.options ?? {};
194
+ if (options.autoCapture !== false) {
195
+ const captureModelOpt = options.captureModel;
196
+ // an OMITTED captureModel does not disable the subscription. It
196
197
  // resolves per capture — the per-session ref last seen on session.context,
197
198
  // else the host default — and only when both are missing does the pass
198
- // skip. autoCapture:true is already the explicit opt-in; a second required
199
- // config string was a syntax tax whose failure mode was a console.warn
200
- // nobody reads. An explicit but INVALID captureModel keeps today's
201
- // fail-closed setup behaviour: silently substituting another model than
202
- // the one the user typed is worse than the tax it replaces.
199
+ // skip. autoCapture is on by default, so the switch itself is the consent;
200
+ // requiring a second config string would be a syntax tax whose failure mode
201
+ // is a console.warn nobody reads. An explicit but INVALID captureModel
202
+ // keeps the fail-closed setup behaviour: silently substituting another
203
+ // model than the one the user typed is worse than the tax it replaces.
203
204
  const omitted = captureModelOpt === undefined;
204
- const captureMax = Number(ctx.options.captureMax) || 3;
205
+ const captureMax = Number(options.captureMax) || 3;
205
206
  // Deterministic guided-candidate pre-pass (POC): default OFF, the bench
206
207
  // picks the default-on arm (FINDINGS 2026-11-08 §4.4).
207
- const guidedRules = ctx.options?.captureGuidedRules === true;
208
- const captureOnCompact = ctx.options?.captureOnCompact !== false;
208
+ const guidedRules = options.captureGuidedRules === true;
209
+ const captureOnCompact = options.captureOnCompact !== false;
209
210
  // two cost levers, both OFF by default until the benchmark says which
210
211
  // way to set them. `captureOnSignal` skips a capture whose turn produced
211
212
  // nothing durable; `captureDelta` mines only the turns since the last
212
213
  // capture instead of re-reading the whole session every time.
213
- const captureOnSignal = ctx.options?.captureOnSignal === true;
214
- const captureDelta = ctx.options?.captureDelta === true;
214
+ const captureOnSignal = options.captureOnSignal === true;
215
+ const captureDelta = options.captureDelta === true;
215
216
  const modelRef = omitted ? null : parseModelRef(captureModelOpt);
216
217
  if (!omitted && !modelRef) {
217
218
  // Invalid explicit model: skip registering the whole subscription
@@ -1180,10 +1181,11 @@ export function configureAutoCapture(
1180
1181
  };
1181
1182
  }
1182
1183
  }
1183
- } else if (ctx.options?.captureOnCompact === true) {
1184
- // autoCapture is the master switch (zero-token default preserved).
1184
+ } else if (options.captureOnCompact === true) {
1185
+ // autoCapture is the master switch, so an explicit false wins over a
1186
+ // compaction trigger that was never turned off.
1185
1187
  console.warn(
1186
- "[opencode-self-improvement] captureOnCompact is on but autoCapture is off; compaction capture stays disabled (autoCapture is the master switch).",
1188
+ "[opencode-self-improvement] captureOnCompact is on but autoCapture is false; compaction capture stays disabled (autoCapture is the master switch).",
1187
1189
  );
1188
1190
  }
1189
1191
  return { onCompactCapture, cleanup: captureCleanup };
package/src/index.ts CHANGED
@@ -227,9 +227,10 @@ const impl = {
227
227
  );
228
228
  // ---- hooks (all fail-closed) -------------------------------------------
229
229
  // Seam set by the auto-capture wiring below ONLY when the compaction
230
- // trigger is live (autoCapture on, captureOnCompact not false, valid
231
- // captureModel). The compaction hook calls it fire-and-forget; undefined
232
- // means "off". Declared here because the hook registers before capture.
230
+ // trigger is live (autoCapture not false, captureOnCompact not false, and a
231
+ // model that resolves — the option, the session, or the host default). The
232
+ // compaction hook calls it fire-and-forget; undefined means "off".
233
+ // Declared here because the hook registers before capture.
233
234
  let onCompactCapture:
234
235
  | ((sid: string, messages: unknown) => void)
235
236
  | undefined;
@@ -246,13 +247,13 @@ const impl = {
246
247
  flushStatus,
247
248
  getCompactCapture: () => onCompactCapture,
248
249
  });
249
- // ---- opt-in auto-capture (idle + compaction triggers) ------------------
250
- // Default OFF: capture never reads sessions and never calls a model. (The
251
- // measured-cache listener above does subscribe to the event stream by
252
- // default, but it is zero-model: pure bookkeeping of message usage.) When
253
- // enabled (options.autoCapture === true AND a valid captureModel), each
254
- // supported turn-end event — and, unless captureOnCompact === false, each
255
- // compaction hook call too — runs ONE cheap ctx.generate.text call whose
250
+ // ---- auto-capture (turn-end + compaction triggers) ---------------------
251
+ // Armed unless the config sets `autoCapture: false`. (The measured-cache
252
+ // listener above also subscribes to the event stream, and it is
253
+ // zero-model: pure bookkeeping of message usage.) While armed — the switch
254
+ // not false, and a parseable `captureModel` whenever one is given — each
255
+ // supported turn-end event, and unless `captureOnCompact` is false each
256
+ // compaction hook call too, runs ONE cheap ctx.generate.text call whose
256
257
  // reply is parsed into candidates that go through the SAME runWriteGate as
257
258
  // model-authored writes — capture can never bypass the moat, and it only
258
259
  // ever writes through the gate. A per-session, per-trigger cooldown bounds
@@ -293,7 +294,9 @@ const impl = {
293
294
  } catch {
294
295
  // a heartbeat with an unknown version still beats no heartbeat
295
296
  }
296
- const wantCapture = ctx.options?.autoCapture === true;
297
+ // Auto-capture is armed unless the config opts it out: an absent key
298
+ // means on, so the switch is read as a negative opt-out.
299
+ const wantCapture = ctx.options?.autoCapture !== false;
297
300
  // an omitted captureModel is a valid arm — the capture inherits
298
301
  // the session's model (session.context) or the host default. Only an
299
302
  // explicit but malformed string is invalid_model.
@@ -158,18 +158,18 @@ export function attributionLines(p: StatusPayload): string[] {
158
158
  export function captureLines(c: CaptureHealth): string[] {
159
159
  switch (c.state) {
160
160
  case "off":
161
- return [" auto-capture: off (default)"];
161
+ return [" auto-capture: off (autoCapture: false)"];
162
162
  case "invalid_model":
163
163
  return [
164
- " auto-capture: invalid_model — autoCapture is on but captureModel is malformed; nothing fires",
164
+ ' auto-capture: invalid_model — captureModel is malformed, so auto-capture is disabled; expected "provider/id"',
165
165
  ];
166
166
  case "no_capabilities":
167
167
  return [
168
- " auto-capture: no_capabilities — autoCapture is on but the host lacks event.subscribe/generate.text/session.context",
168
+ " auto-capture: no_capabilities — the host lacks event.subscribe/generate.text/session.context, so auto-capture is disabled",
169
169
  ];
170
170
  case "switch_mismatch":
171
171
  return [
172
- " auto-capture: switch_mismatch — captureOnCompact is on but autoCapture is off; nothing fires",
172
+ " auto-capture: switch_mismatch — captureOnCompact is on but autoCapture is false; nothing fires",
173
173
  ];
174
174
  case "on": {
175
175
  // Inert means NO execution evidence at all: no candidate line and no