opencode-self-improvement 0.22.1 → 0.23.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 +3 -18
- package/command/repo-init.md +4 -5
- package/package.json +1 -4
- package/src/capture/candidates.ts +14 -0
- package/src/capture/checked.ts +128 -0
- package/src/capture/policy.ts +52 -0
- package/src/capture/prompt.ts +39 -0
- package/src/capture/runtime.ts +120 -1
- package/src/capture/triggers.ts +14 -0
- package/src/core/config/paths.ts +0 -25
- package/src/core/tags.ts +7 -0
- package/src/gate/gate.ts +49 -0
- package/src/gate/resolver.ts +1 -2
- package/src/gate/value-conflict.ts +300 -0
- package/src/init/detect.ts +8 -77
- package/src/init/format.ts +2 -9
- package/src/init/run.ts +8 -48
- package/src/inject/format.ts +9 -1
- package/src/store/model/provenance.ts +79 -0
- package/src/tools/init.ts +1 -2
- package/src/tools/schema.ts +0 -4
package/README.md
CHANGED
|
@@ -19,7 +19,7 @@ Every figure in this README carries a provenance marker: **measured** (read off
|
|
|
19
19
|
|
|
20
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.
|
|
21
21
|
|
|
22
|
-
**3. Run `/repo-init`** in each repo you work in. It stores the test / build / lint / typecheck commands as memories and writes an init stamp tied to the current git head. Rerun `/repo-init force` after a refactor.
|
|
22
|
+
**3. Run `/repo-init`** in each repo you work in. It stores the test / build / lint / typecheck commands as memories and writes an init stamp tied to the current git head. Rerun `/repo-init force` after a refactor.
|
|
23
23
|
|
|
24
24
|
Needs Bun 1.3.0 or newer in the opencode build (the tested floor); older Bun reports a startup warning.
|
|
25
25
|
|
|
@@ -35,7 +35,7 @@ After that, memory is just conversation: ask the agent to remember something and
|
|
|
35
35
|
## What you get
|
|
36
36
|
|
|
37
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.
|
|
38
|
+
- **`/repo-init`** — per-repo setup: build/test commands as memories, keyed to the git head.
|
|
39
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
40
|
- **Memory-aware compaction** — durable memories are handed to the compaction summarizer, so a long session keeps its facts.
|
|
41
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).
|
|
@@ -84,8 +84,6 @@ Zero configuration is the default. To tune, use the object form of the plugin en
|
|
|
84
84
|
| `OPENCODE_MEMORY_INJECT_BUDGET` | Fallback for `injectBudget`. |
|
|
85
85
|
| `OPENCODE_MEMORY_FRONTIER_BUDGET` | Fallback for `frontierBudget`. |
|
|
86
86
|
| `OPENCODE_COMMANDS_DIR` | Where the plugin mirrors its slash commands (default `~/.config/opencode/commands`). |
|
|
87
|
-
| `OPENCODE_MEMORY_GRAPH` | Set to `1` to have `/repo-init` build the code graph. Off by default — nothing reads the index. See [Code graph](#code-graph-optional). |
|
|
88
|
-
| `OPENCODE_CBM_BIN` | Path to a `codebase-memory-mcp` binary, used only when `OPENCODE_MEMORY_GRAPH=1`. See [Code graph](#code-graph-optional). |
|
|
89
87
|
| `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). |
|
|
90
88
|
| `OPENCODE_VIEWER_PORT` | Admin editor port (default `8787`). |
|
|
91
89
|
| `OPENCODE_VIEWER_ALLOWED_HOSTS` | Comma-separated hosts beyond loopback. See [Surfaces](#surfaces). |
|
|
@@ -304,18 +302,6 @@ Same data behind each one (`memory_status`; no model call).
|
|
|
304
302
|
|
|
305
303
|
**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.
|
|
306
304
|
|
|
307
|
-
## Code graph (optional)
|
|
308
|
-
|
|
309
|
-
Code-graph indexing is **off by default** (`/repo-init` reports `Graph: disabled`). Measured cost vs. benefit: the one-shot index spawn took 11–26s per init, failed in 29 of 32 real runs, and no read or gate path consumes the index — retrieval and the write gates resolve code references against the live file tree, and gate evidence is identical with the graph present or absent. So the default build never spawns it.
|
|
310
|
-
|
|
311
|
-
To opt in, set `OPENCODE_MEMORY_GRAPH=1`. `/repo-init` then indexes the repo via [`codebase-memory-mcp`](https://github.com/DeusData/codebase-memory-mcp), pinned to `0.11.0` as an optional dependency. A copy already on your `PATH` is used instead; override with `OPENCODE_CBM_BIN=/path/to/codebase-memory-mcp`. Install the pinned binary globally if you prefer:
|
|
312
|
-
|
|
313
|
-
```sh
|
|
314
|
-
curl -fsSL https://raw.githubusercontent.com/DeusData/codebase-memory-mcp/main/install.sh | bash
|
|
315
|
-
```
|
|
316
|
-
|
|
317
|
-
Whether or not the graph runs, `/repo-init` records scripts and the init stamp, and memory behaves the same.
|
|
318
|
-
|
|
319
305
|
## Installing a specific version
|
|
320
306
|
|
|
321
307
|
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.
|
|
@@ -390,8 +376,7 @@ Run it when you want to know whether the suite still has teeth — after changin
|
|
|
390
376
|
| `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 lock left by a killed process is taken over after 10s. |
|
|
391
377
|
| Stray `*.logfmt.lock` or `*.tmp` in the store | Write bookkeeping; safe to delete while nothing is writing. |
|
|
392
378
|
| `/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. |
|
|
393
|
-
|
|
|
394
|
-
| Init says `Graph: unavailable` | You opted in (`OPENCODE_MEMORY_GRAPH=1`) but `codebase-memory-mcp` couldn't start. Install pinned `0.11.0` or point `OPENCODE_CBM_BIN` at the binary. Scripts are still remembered without it. |
|
|
379
|
+
| `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. |
|
|
395
380
|
| 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. |
|
|
396
381
|
| `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. |
|
|
397
382
|
| 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`. |
|
package/command/repo-init.md
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
---
|
|
2
|
-
description: Initialize build/test memories for this repo
|
|
2
|
+
description: Initialize build/test memories for this repo
|
|
3
3
|
---
|
|
4
4
|
Initialize this repository for durable memory.
|
|
5
5
|
|
|
@@ -8,12 +8,11 @@ Initialize this repository for durable memory.
|
|
|
8
8
|
2. Store an init stamp keyed on git HEAD so future sessions can cheaply tell
|
|
9
9
|
whether the repo has drifted.
|
|
10
10
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
`OPENCODE_MEMORY_GRAPH=1` before the call.
|
|
11
|
+
Everything is local: manifests are parsed in place and no external indexer is
|
|
12
|
+
spawned (the codebase-memory graph integration was removed, #231).
|
|
14
13
|
|
|
15
14
|
Call the `memory_init` tool to do this. If the user typed arguments (e.g.
|
|
16
15
|
"force"), pass them through: set `force: true` when $ARGUMENTS mentions force,
|
|
17
16
|
otherwise run a fresh idempotent init.
|
|
18
17
|
|
|
19
|
-
Then report concisely:
|
|
18
|
+
Then report concisely: scripts recorded and the stamp head.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-self-improvement",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.23.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": {
|
|
@@ -39,9 +39,6 @@
|
|
|
39
39
|
"README.md",
|
|
40
40
|
"LICENSE"
|
|
41
41
|
],
|
|
42
|
-
"optionalDependencies": {
|
|
43
|
-
"codebase-memory-mcp": "0.11.0"
|
|
44
|
-
},
|
|
45
42
|
"devDependencies": {
|
|
46
43
|
"@biomejs/biome": "2.6.2",
|
|
47
44
|
"@opencode/plugin": "2.0.32",
|
|
@@ -128,6 +128,19 @@ export function parseCandidates(raw: string, max: number): CaptureCandidate[] {
|
|
|
128
128
|
: undefined;
|
|
129
129
|
})()
|
|
130
130
|
: undefined;
|
|
131
|
+
// Lesson citation (S1, learn-from-failure): shape-checked here, verified
|
|
132
|
+
// against the tool ledger by the runtime. Only a `blocker` may carry one.
|
|
133
|
+
// A newline would break the logfmt row, so flattenMemoryText must be a
|
|
134
|
+
// fixed point — the same discipline as `original` above.
|
|
135
|
+
const failure =
|
|
136
|
+
type === "blocker" && typeof o.failure === "string"
|
|
137
|
+
? (() => {
|
|
138
|
+
const s = o.failure.trim();
|
|
139
|
+
return s && s.length <= 200 && flattenMemoryText(s) === s
|
|
140
|
+
? s
|
|
141
|
+
: undefined;
|
|
142
|
+
})()
|
|
143
|
+
: undefined;
|
|
131
144
|
out.push({
|
|
132
145
|
...(status
|
|
133
146
|
? { type, scope, content, status }
|
|
@@ -135,6 +148,7 @@ export function parseCandidates(raw: string, max: number): CaptureCandidate[] {
|
|
|
135
148
|
...(kw ? { kw } : {}),
|
|
136
149
|
...(guided ? { guided: true, ...conflict } : {}),
|
|
137
150
|
...(original ? { original } : {}),
|
|
151
|
+
...(failure ? { failure } : {}),
|
|
138
152
|
});
|
|
139
153
|
}
|
|
140
154
|
return out;
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// #393 AC 2: check an inferred claim against the working tree BEFORE storing it.
|
|
2
|
+
//
|
|
3
|
+
// The scope is deliberately narrow, and the measurement is why it is narrow.
|
|
4
|
+
// R4's poison rows claimed a fallback VAT rate for a fixture whose config leaves
|
|
5
|
+
// that rate UNSET: `findConstant(base4, "fallbackVatBps")` returns null. The tree
|
|
6
|
+
// does not contradict the poison — it is silent, and silence is exactly where a
|
|
7
|
+
// confident wrong row fits.
|
|
8
|
+
//
|
|
9
|
+
// - refusing when the tree CONTRADICTS a claim refuses nothing in R4;
|
|
10
|
+
// - refusing when the tree is SILENT also refuses the transport fact
|
|
11
|
+
// (empty store 0/5, seeded 5/5), which is the one measured benefit memory has.
|
|
12
|
+
//
|
|
13
|
+
// So this module answers three ways and only one of them refuses. "Undecidable"
|
|
14
|
+
// keeps the row — that is the transport case — and the row then rides injection
|
|
15
|
+
// labelled `[unverified]` (see store/model/provenance.ts), which is the part of
|
|
16
|
+
// #393 the evidence actually supports.
|
|
17
|
+
|
|
18
|
+
import { findConstant, valuesAgree } from "../recall/conflicts.ts";
|
|
19
|
+
|
|
20
|
+
export type ClaimVerdict = "agrees" | "contradicts" | "undecidable";
|
|
21
|
+
|
|
22
|
+
export interface ClaimHit {
|
|
23
|
+
verdict: ClaimVerdict;
|
|
24
|
+
/** The symbol the check resolved in the tree, when one resolved. */
|
|
25
|
+
ref?: string;
|
|
26
|
+
/** The number compared, when one was compared. */
|
|
27
|
+
claim?: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// A constant the row names, in the two shapes source uses: SCREAMING_CASE and a
|
|
31
|
+
// dotted camelCase member. Deliberately narrow — prose that merely mentions
|
|
32
|
+
// "rate" must not be resolved against a symbol.
|
|
33
|
+
//
|
|
34
|
+
// Built per call, NOT shared at module scope. A `g` regex carries `lastIndex`
|
|
35
|
+
// between calls, so a shared one starts the next row's scan wherever the last
|
|
36
|
+
// one stopped and silently returns "undecidable" for a claim it would have
|
|
37
|
+
// caught. That is a check whose result depends on the order of previous rows —
|
|
38
|
+
// the worst shape a gate can have, because it looks deterministic.
|
|
39
|
+
function symbols(): RegExp {
|
|
40
|
+
return /\b([A-Z][A-Z0-9_]{2,}|[A-Za-z_$][A-Za-z0-9_$]*\.[a-z][A-Za-z0-9_$]*)\b/g;
|
|
41
|
+
}
|
|
42
|
+
// How far after the symbol a number may sit and still count as THAT symbol's
|
|
43
|
+
// value. "VAT_BPS is 2150" yes; "VAT_BPS was added in 2024, the rate is 2150"
|
|
44
|
+
// compares 2024 and refuses on a coincidence, which is worse than not checking.
|
|
45
|
+
const WINDOW = 48;
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Check an inferred row's numeric claim against the working tree by reading the
|
|
49
|
+
* claim OUT of its own prose.
|
|
50
|
+
*
|
|
51
|
+
* Capture's structured `ref`/`claim` fields ride user-guided rows only (see
|
|
52
|
+
* `capture/candidates.ts`), and the guided rows are exactly the ones this check
|
|
53
|
+
* must not touch — a user correcting a stale tree is the case where the tree is
|
|
54
|
+
* wrong. So an inferred row is checked on what it says, not on what it declared.
|
|
55
|
+
*
|
|
56
|
+
* Agrees when one resolvable symbol's value matches a nearby number; contradicts
|
|
57
|
+
* only when a resolvable symbol's value disagrees with EVERY number the row
|
|
58
|
+
* states near it; undecidable otherwise, which is the transport case and keeps
|
|
59
|
+
* the row.
|
|
60
|
+
*/
|
|
61
|
+
export function claimVerdictFromContent(
|
|
62
|
+
repoDir: string | undefined,
|
|
63
|
+
content: string,
|
|
64
|
+
): ClaimHit {
|
|
65
|
+
if (!repoDir || !content) return { verdict: "undecidable" };
|
|
66
|
+
const cache = new Map<string, string | undefined>();
|
|
67
|
+
let sawResolvable = false;
|
|
68
|
+
const SYMBOL = symbols();
|
|
69
|
+
let match: RegExpExecArray | null = SYMBOL.exec(content);
|
|
70
|
+
while (match) {
|
|
71
|
+
const ref = match[1] ?? "";
|
|
72
|
+
// Step past the whole match, not just the captured name: the `` lookahead
|
|
73
|
+
// means a name-length advance would re-find the same symbol forever.
|
|
74
|
+
SYMBOL.lastIndex = match.index + match[0].length;
|
|
75
|
+
if (!cache.has(ref)) {
|
|
76
|
+
const fact = findConstant(repoDir, ref);
|
|
77
|
+
cache.set(ref, fact ? String(fact.value) : undefined);
|
|
78
|
+
}
|
|
79
|
+
const code = cache.get(ref);
|
|
80
|
+
if (code !== undefined) {
|
|
81
|
+
sawResolvable = true;
|
|
82
|
+
const tail = content.slice(
|
|
83
|
+
match.index + ref.length,
|
|
84
|
+
match.index + ref.length + WINDOW,
|
|
85
|
+
);
|
|
86
|
+
// Compare against every number near the symbol: a row may state the value
|
|
87
|
+
// in two units and any one of them agreeing is enough to keep it.
|
|
88
|
+
// The sign is part of the number (review #399): "-2150" extracted as
|
|
89
|
+
// "2150" agreed with a tree declaring 2150 and shipped the row labelled
|
|
90
|
+
// [code-checked] — an opposite-signed value positively vouched for by a
|
|
91
|
+
// check. `valuesAgree` parses leading [+-] itself, so the extractor must
|
|
92
|
+
// not drop it. A hyphen separated by spaces stays a separator, not a
|
|
93
|
+
// sign: "2150 - 300 discount" still compares 2150.
|
|
94
|
+
const near = tail.match(/[-+]?\d+(?:\.\d+)?/g) ?? [];
|
|
95
|
+
let agreed = false;
|
|
96
|
+
for (const n of near) {
|
|
97
|
+
if (valuesAgree(n, code) === true) {
|
|
98
|
+
agreed = true;
|
|
99
|
+
return { verdict: "agrees", ref, claim: n };
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if (!agreed && near.length) {
|
|
103
|
+
return { verdict: "contradicts", ref, claim: near[0] };
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
match = SYMBOL.exec(content);
|
|
107
|
+
}
|
|
108
|
+
void sawResolvable;
|
|
109
|
+
return { verdict: "undecidable" };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* The declared-ref form, kept for callers that already carry a ref (the guided
|
|
114
|
+
* contradiction surface). Any uncertainty is `undecidable`, never `contradicts`.
|
|
115
|
+
*/
|
|
116
|
+
export function claimVerdict(
|
|
117
|
+
repoDir: string | undefined,
|
|
118
|
+
ref: string,
|
|
119
|
+
claim: string,
|
|
120
|
+
): ClaimVerdict {
|
|
121
|
+
if (!repoDir || !ref || !claim) return "undecidable";
|
|
122
|
+
const fact = findConstant(repoDir, ref);
|
|
123
|
+
if (!fact) return "undecidable";
|
|
124
|
+
const agree = valuesAgree(claim, String(fact.value));
|
|
125
|
+
if (agree === true) return "agrees";
|
|
126
|
+
if (agree === false) return "contradicts";
|
|
127
|
+
return "undecidable";
|
|
128
|
+
}
|
package/src/capture/policy.ts
CHANGED
|
@@ -252,3 +252,55 @@ export function captureSignalSince(
|
|
|
252
252
|
// signal-bearing turn still mines this one too.
|
|
253
253
|
return { ok: false, why: "no-signal" };
|
|
254
254
|
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Gate commands that ran in this window, FAILED, and were never followed by a
|
|
258
|
+
* PASS of the same family. This is the only thing a failure lesson may be about.
|
|
259
|
+
*
|
|
260
|
+
* The point is that a lesson must rest on the repo's own verdict, not on the
|
|
261
|
+
* model's impression of what went wrong. ReMe (Findings ACL 2026) found
|
|
262
|
+
* selective addition BEATS full addition, because one failed trajectory rarely
|
|
263
|
+
* carries enough context for a correct analysis and yields misguided
|
|
264
|
+
* experiences. So this store's failure mode is writing a wrong lesson, not
|
|
265
|
+
* missing a right one. An unattested lesson is a rumour, and the runtime drops
|
|
266
|
+
* the row.
|
|
267
|
+
*
|
|
268
|
+
* A recovered failure is excluded on purpose: FAIL then PASS means the agent
|
|
269
|
+
* fixed it, and "do not do what I just did" is only a lesson while the thing is
|
|
270
|
+
* still broken. `captureSignalSince` reads the same ledger for the opposite
|
|
271
|
+
* purpose — a recovery is the best REASON to capture, an unrecovered failure is
|
|
272
|
+
* the best thing to capture.
|
|
273
|
+
*
|
|
274
|
+
* One family's recovery does not attest away another family's failure: a
|
|
275
|
+
* session that got its tests green and its lint red still has an open lint
|
|
276
|
+
* failure.
|
|
277
|
+
*
|
|
278
|
+
* First-failure order, deduped by family, bounded — the block is prompt bytes on
|
|
279
|
+
* every capture, and a session with more than a handful of failing gates is not
|
|
280
|
+
* choosing between eight of them.
|
|
281
|
+
*/
|
|
282
|
+
export function attestedGateFailures(
|
|
283
|
+
s: SessionState,
|
|
284
|
+
sinceTurn: number,
|
|
285
|
+
): { cmd: string; arg?: string }[] {
|
|
286
|
+
// Same reasoning as captureSignalSince: with no turn tracking the window is
|
|
287
|
+
// meaningless rather than empty, and a policy that quietly stops reporting
|
|
288
|
+
// failures is the failure mode this file exists to avoid.
|
|
289
|
+
const tracked = s.turns > 0;
|
|
290
|
+
const out: { cmd: string; arg?: string }[] = [];
|
|
291
|
+
// Ledger order, not timestamps: `calls` is append-only, which is what
|
|
292
|
+
// captureSignalSince relies on for the same FAIL-then-PASS question, and it
|
|
293
|
+
// cannot be undone by two calls sharing a millisecond.
|
|
294
|
+
s.calls.forEach((c, i) => {
|
|
295
|
+
if (!c.gateCheck || c.status !== "FAIL" || !c.cmd) return;
|
|
296
|
+
if (tracked && (c.turn ?? 0) <= sinceTurn) return;
|
|
297
|
+
if (out.some((f) => f.cmd === c.cmd)) return;
|
|
298
|
+
if (out.length >= 8) return;
|
|
299
|
+
const recovered = s.calls
|
|
300
|
+
.slice(i + 1)
|
|
301
|
+
.some((l) => l.gateCheck && l.cmd === c.cmd && l.status === "PASS");
|
|
302
|
+
if (recovered) return;
|
|
303
|
+
out.push({ cmd: c.cmd, ...(c.arg ? { arg: c.arg } : {}) });
|
|
304
|
+
});
|
|
305
|
+
return out;
|
|
306
|
+
}
|
package/src/capture/prompt.ts
CHANGED
|
@@ -29,6 +29,17 @@ export interface CaptureCandidate {
|
|
|
29
29
|
* so a stored original is the user's own words.
|
|
30
30
|
*/
|
|
31
31
|
original?: string;
|
|
32
|
+
/**
|
|
33
|
+
* Lesson citation (S1, learn-from-failure): the failing command this
|
|
34
|
+
* `blocker` row is about. Present only on a lesson, and only ever copied from
|
|
35
|
+
* the ATTESTED FAILURES block the prompt was given — the runtime re-checks it
|
|
36
|
+
* against the tool ledger and drops the ROW when it does not appear there.
|
|
37
|
+
* Unlike a guided `original`, a failed check cannot keep the row and drop the
|
|
38
|
+
* field: an uncited lesson is not a lesson with a missing annotation, it is a
|
|
39
|
+
* guess about what is broken. Not stored — it is a write-time gate, so no row
|
|
40
|
+
* format changes.
|
|
41
|
+
*/
|
|
42
|
+
failure?: string;
|
|
32
43
|
}
|
|
33
44
|
|
|
34
45
|
// Keywords are the vocabulary bridge for the strict-paraphrase wall, mined from
|
|
@@ -52,6 +63,7 @@ export function buildCapturePrompt(
|
|
|
52
63
|
max = 3,
|
|
53
64
|
userProse = "",
|
|
54
65
|
known = "",
|
|
66
|
+
attested?: string[],
|
|
55
67
|
): string {
|
|
56
68
|
const prose = redactSecrets(userProse).trim();
|
|
57
69
|
const knownList = redactSecrets(known).trim();
|
|
@@ -94,6 +106,33 @@ export function buildCapturePrompt(
|
|
|
94
106
|
'- The REQUESTS block is what the user asked for in THIS session. Most of it scopes the current job and expires with it. Mine a `preference` from it ONLY when it names a tool, package, format or convention that outlives the task ("we use bun here", "no semicolons"); never from wording that scopes this job ("only touch src/", "do not create tests").',
|
|
95
107
|
]
|
|
96
108
|
: []),
|
|
109
|
+
// S1 (learn-from-failure). Measured on the bench: a session that failed
|
|
110
|
+
// after 574 s and 33,287 tokens wrote ONE row, and it was a paraphrase of
|
|
111
|
+
// the task brief. The prompt asked for "blockers hit" in a list of seven
|
|
112
|
+
// words and never mentioned failure, so there was nothing to answer. What
|
|
113
|
+
// makes this safe rather than noisy is that the failure list is not the
|
|
114
|
+
// model's recollection — it is read from the tool ledger, and a lesson
|
|
115
|
+
// whose citation is not in it is dropped before the write gate.
|
|
116
|
+
...(attested
|
|
117
|
+
? attested.length
|
|
118
|
+
? [
|
|
119
|
+
"ATTESTED FAILURES (commands that ran in this session and FAILED, with no later pass. This is measured from the tool ledger, not your impression — it is the ONLY evidence of failure you have, and the only thing a lesson may be about):",
|
|
120
|
+
...attested.map((f) => ` - ${f}`),
|
|
121
|
+
"",
|
|
122
|
+
'- The most valuable thing a session that did not finish can teach a future one is what does not work. For each failure above worth a lesson, emit one row with type "blocker" whose content is a rule in the form: when <condition>, avoid <action>. Name a file or symbol, so the rule can be checked against the code later.',
|
|
123
|
+
'- Every such row MUST carry "failure": the failing command, copied ONLY from the list above and EXACTLY as written there. A citation taken from anywhere else, or no citation at all, means the row is refused and dropped — never invent a failure, never cite one that later passed.',
|
|
124
|
+
"- Say what was attempted and what the evidence showed. Do not state a cause you did not prove, and do not store the fix you did not verify: an unverified fix riding a later session is worse than no memory at all.",
|
|
125
|
+
"- Emit no `blocker` for anything that did not fail here — not a style opinion, not a step that merely took a while, not the task brief.",
|
|
126
|
+
"",
|
|
127
|
+
]
|
|
128
|
+
: [
|
|
129
|
+
// Explicit, because silence here reads as "no lesson-worthy failure
|
|
130
|
+
// occurred", which is a different claim: this session ran no gate at
|
|
131
|
+
// all, or every gate it ran passed.
|
|
132
|
+
"No command failed in this session: emit no `blocker` lesson row.",
|
|
133
|
+
"",
|
|
134
|
+
]
|
|
135
|
+
: []),
|
|
97
136
|
// Permission to emit fewer rows is what bounds deliberation. On the
|
|
98
137
|
// reproducing fixture the same seat went 1,095 -> 3,084 completion tokens
|
|
99
138
|
// and 19.7s -> 63.2s with this line removed, and the same rows out. It
|
package/src/capture/runtime.ts
CHANGED
|
@@ -3,7 +3,11 @@
|
|
|
3
3
|
import type { Cleanup } from "@opencode/plugin/promise/plugin";
|
|
4
4
|
import { cmpTs } from "../core/cmp-ts.ts";
|
|
5
5
|
import { session, setCurrent } from "../core/state.ts";
|
|
6
|
-
import {
|
|
6
|
+
import {
|
|
7
|
+
AUTO_CAPTURE_TAG,
|
|
8
|
+
CODE_CHECKED_TAG,
|
|
9
|
+
USER_GUIDED_TAG,
|
|
10
|
+
} from "../core/tags.ts";
|
|
7
11
|
import { record, recordCaptureLag } from "../evidence/record.ts";
|
|
8
12
|
import { type GateContext, runWriteGate } from "../gate/gate.ts";
|
|
9
13
|
import { captureSessionID } from "../identity/host-events.ts";
|
|
@@ -19,6 +23,7 @@ import { quarantineCandidate } from "../store/quarantine/quarantine.ts";
|
|
|
19
23
|
import { flattenMemoryText } from "../store/sanitize.ts";
|
|
20
24
|
import { redactSecrets } from "../store/secrets.ts";
|
|
21
25
|
import { parseCandidates, parseModelRef } from "./candidates.ts";
|
|
26
|
+
import { claimVerdictFromContent } from "./checked.ts";
|
|
22
27
|
import {
|
|
23
28
|
findGuidedQuotes,
|
|
24
29
|
mergeGuidedCandidates,
|
|
@@ -28,6 +33,7 @@ import {
|
|
|
28
33
|
import { lagSince } from "./lag.ts";
|
|
29
34
|
import {
|
|
30
35
|
advanceCaptureCursor,
|
|
36
|
+
attestedGateFailures,
|
|
31
37
|
captureCursor,
|
|
32
38
|
captureSignalSince,
|
|
33
39
|
deltaMessages,
|
|
@@ -481,6 +487,40 @@ export function configureAutoCapture(
|
|
|
481
487
|
// into a teardown (#211).
|
|
482
488
|
const knownRows = await knownRowsFor(captureReader);
|
|
483
489
|
if (controller.signal.aborted) return;
|
|
490
|
+
// S1: the ledger's unrecovered gate failures, in the same window the
|
|
491
|
+
// signal policy just approved. Rendered into the prompt so the model
|
|
492
|
+
// can cite one, and kept here so the citation can be checked against
|
|
493
|
+
// the ledger rather than against the model's retelling. `undefined`,
|
|
494
|
+
// not `[]`, means "this caller does not know about lessons" and leaves
|
|
495
|
+
// the prompt byte-identical to before; an empty array is a statement
|
|
496
|
+
// that nothing failed, and the prompt says so.
|
|
497
|
+
const attested = attestedGateFailures(session(sid), cursor.turn).map(
|
|
498
|
+
(f) =>
|
|
499
|
+
// Review #384 finding 1: ledger args are raw tool input. A failing
|
|
500
|
+
// `bun test --token=sk-...` put the credential verbatim into the
|
|
501
|
+
// ATTESTED FAILURES block — the transcript scrub does not cover
|
|
502
|
+
// this input. Redact at construction, so the prompt renders the
|
|
503
|
+
// safe string AND the citation check compares against the same
|
|
504
|
+
// representation the model was shown.
|
|
505
|
+
redactSecrets(f.arg ? `${f.cmd} — ${f.arg}` : f.cmd),
|
|
506
|
+
);
|
|
507
|
+
// Review #384 finding 2: `lessonHay.includes(cite)` accepted a lesson
|
|
508
|
+
// citing `tsc` when the only failure was `bun test
|
|
509
|
+
// --test-name-pattern tsc` — substring presence cannot establish that
|
|
510
|
+
// the cited command ran. The list renders `cmd — arg`; a faithful
|
|
511
|
+
// citation copies a COMPLETE displayed field, so membership is tested
|
|
512
|
+
// against each whole entry, its cmd, and its arg — never a fragment.
|
|
513
|
+
// `tsc` is none of those for that failure and is refused; the cmd-only
|
|
514
|
+
// citation the prompt's own example uses still passes.
|
|
515
|
+
const lessonSet = new Set<string>();
|
|
516
|
+
for (const f of attested) {
|
|
517
|
+
lessonSet.add(normWs(f).toLowerCase());
|
|
518
|
+
const sep = f.lastIndexOf(" — ");
|
|
519
|
+
if (sep > 0) {
|
|
520
|
+
lessonSet.add(normWs(f.slice(0, sep)).toLowerCase());
|
|
521
|
+
lessonSet.add(normWs(f.slice(sep + 3)).toLowerCase());
|
|
522
|
+
}
|
|
523
|
+
}
|
|
484
524
|
const out = await generateApi.text({
|
|
485
525
|
model,
|
|
486
526
|
// Redact the COMPLETE transcript, THEN apply the character budget
|
|
@@ -493,6 +533,7 @@ export function configureAutoCapture(
|
|
|
493
533
|
captureMax,
|
|
494
534
|
redactSecrets(userProse).slice(-1500),
|
|
495
535
|
knownRows,
|
|
536
|
+
attested,
|
|
496
537
|
),
|
|
497
538
|
});
|
|
498
539
|
const text = typeof out === "string" ? out : (out?.text ?? "");
|
|
@@ -586,10 +627,83 @@ export function configureAutoCapture(
|
|
|
586
627
|
c.original = undefined;
|
|
587
628
|
}
|
|
588
629
|
}
|
|
630
|
+
// S1 (learn-from-failure): a row that CITES a failing command is
|
|
631
|
+
// claiming to be a lesson, and the claim is checked against the ledger,
|
|
632
|
+
// not against the model's retelling. ReMe (Findings ACL 2026) found
|
|
633
|
+
// selective addition beats full addition because one failed trajectory
|
|
634
|
+
// rarely carries enough context for a correct analysis — so the way
|
|
635
|
+
// this feature fails is by storing a wrong rule, and a rule about a
|
|
636
|
+
// failure that never happened (or that the agent already fixed) is the
|
|
637
|
+
// worst version of it: it rides every later session as an instruction.
|
|
638
|
+
//
|
|
639
|
+
// The gate is monotone. Only a row carrying `failure` makes the claim,
|
|
640
|
+
// so an ordinary `blocker` note — a type this capture path has always
|
|
641
|
+
// written — is untouched. Refusing every uncited blocker would delete
|
|
642
|
+
// rows the store has always kept, and a provenance fix does not buy a
|
|
643
|
+
// recall loss here.
|
|
644
|
+
let lessonsKept = 0;
|
|
645
|
+
let lessonsRefused = 0;
|
|
646
|
+
candidates = candidates.filter((c) => {
|
|
647
|
+
if (c.failure === undefined) return true;
|
|
648
|
+
const cite = normWs(c.failure).toLowerCase();
|
|
649
|
+
if (cite && lessonSet.has(cite)) {
|
|
650
|
+
lessonsKept++;
|
|
651
|
+
return true;
|
|
652
|
+
}
|
|
653
|
+
lessonsRefused++;
|
|
654
|
+
return false;
|
|
655
|
+
});
|
|
656
|
+
if (lessonsKept || lessonsRefused)
|
|
657
|
+
await record(
|
|
658
|
+
"auto_capture_lessons",
|
|
659
|
+
{
|
|
660
|
+
session: sid,
|
|
661
|
+
trigger,
|
|
662
|
+
kept: lessonsKept,
|
|
663
|
+
refused: lessonsRefused,
|
|
664
|
+
attested: attested.length,
|
|
665
|
+
...(modelTag ? { model: modelTag } : {}),
|
|
666
|
+
},
|
|
667
|
+
false,
|
|
668
|
+
sid,
|
|
669
|
+
captureGate.evidenceContext,
|
|
670
|
+
);
|
|
589
671
|
for (const c of candidates) {
|
|
590
672
|
// Between candidates, never inside a gate run: a supersession that
|
|
591
673
|
// half-applied is a store the next session cannot trust.
|
|
592
674
|
if (controller.signal.aborted) return;
|
|
675
|
+
// #393 AC 2: a numeric claim capture INFERRED (the user did not state
|
|
676
|
+
// it) that names a constant the tree also names is checked before it
|
|
677
|
+
// is stored. Only a contradiction refuses; "undecidable" is the
|
|
678
|
+
// transport case and keeps the row, labelled.
|
|
679
|
+
const claim = c.guided
|
|
680
|
+
? { verdict: "undecidable" as const }
|
|
681
|
+
: claimVerdictFromContent(
|
|
682
|
+
captureReader.kind === "repo"
|
|
683
|
+
? captureReader.scope.path
|
|
684
|
+
: undefined,
|
|
685
|
+
c.content,
|
|
686
|
+
);
|
|
687
|
+
const verdict = claim.verdict;
|
|
688
|
+
if (verdict === "contradicts") {
|
|
689
|
+
await record(
|
|
690
|
+
"auto_capture_contradiction",
|
|
691
|
+
{
|
|
692
|
+
session: sid,
|
|
693
|
+
trigger,
|
|
694
|
+
type: c.type,
|
|
695
|
+
scope: redactSecrets(c.scope),
|
|
696
|
+
reason: "claim_contradicts_tree",
|
|
697
|
+
where: claim.ref ?? "",
|
|
698
|
+
matched: claim.claim ?? "",
|
|
699
|
+
...(modelTag ? { model: modelTag } : {}),
|
|
700
|
+
},
|
|
701
|
+
false,
|
|
702
|
+
sid,
|
|
703
|
+
captureGate.evidenceContext,
|
|
704
|
+
);
|
|
705
|
+
continue;
|
|
706
|
+
}
|
|
593
707
|
const original = c.original;
|
|
594
708
|
const durable: string[] = [];
|
|
595
709
|
let outcome: Awaited<ReturnType<typeof runWriteGate>>;
|
|
@@ -610,6 +724,11 @@ export function configureAutoCapture(
|
|
|
610
724
|
...(original ? { original } : {}),
|
|
611
725
|
tags: [
|
|
612
726
|
AUTO_CAPTURE_TAG,
|
|
727
|
+
// #393: the ONE case that earns `[code-checked]` — an inferred
|
|
728
|
+
// numeric claim that agreed with the tree. Absent everywhere
|
|
729
|
+
// else, which is what makes `[unverified]` mean something
|
|
730
|
+
// instead of decorate everything.
|
|
731
|
+
...(verdict === "agrees" ? [CODE_CHECKED_TAG] : []),
|
|
613
732
|
...(trigger === "compaction" ? [CAPTURE_COMPACT_TAG] : []),
|
|
614
733
|
...(c.guided ? [USER_GUIDED_TAG] : []),
|
|
615
734
|
],
|
package/src/capture/triggers.ts
CHANGED
|
@@ -93,9 +93,23 @@ export function hasEngagement(sid: string): boolean {
|
|
|
93
93
|
return session(sid).sawEngagement;
|
|
94
94
|
}
|
|
95
95
|
|
|
96
|
+
// A gate is a command whose exit status is the repo's own verdict on the work:
|
|
97
|
+
// a test run, a typecheck, a lint, a build. `gateRecovered` (FAIL then PASS of
|
|
98
|
+
// the same family) is the strongest capture signal there is, and attested
|
|
99
|
+
// failure lessons are keyed on it.
|
|
100
|
+
//
|
|
101
|
+
// `test` was missing from this table, so `bun test`, `npm test` and `pytest`
|
|
102
|
+
// registered as no gate at all: a session could go red-green-red and the ledger
|
|
103
|
+
// would never see it. The matcher is anchored on the RUNNER rather than on the
|
|
104
|
+
// word, because the word appears everywhere in a repo that has a test directory
|
|
105
|
+
// — `ls src/test` and `cat test/fixtures/a.json` are not test runs.
|
|
96
106
|
const GATE_CMDS: [RegExp, string][] = [
|
|
97
107
|
[/vitest/, "vitest"],
|
|
98
108
|
[/playwright/, "playwright"],
|
|
109
|
+
[/(?:^|[\s;&|(])(?:bun|npm|pnpm|yarn|deno|npx)\s+(?:run\s+)?test\b/, "test"],
|
|
110
|
+
[/(?:^|[\s;&|(])(?:pytest|py\.test)\b/, "test"],
|
|
111
|
+
[/(?:^|[\s;&|(])go\s+test\b/, "test"],
|
|
112
|
+
[/(?:^|[\s;&|(])make\s+test\b/, "test"],
|
|
99
113
|
[/lint/, "lint"],
|
|
100
114
|
[/build:source|tsc\b/, "tsc"],
|
|
101
115
|
];
|
package/src/core/config/paths.ts
CHANGED
|
@@ -4,7 +4,6 @@
|
|
|
4
4
|
// under $OPENCODE_MEMORY_DIR when set (tests use this for hermetic runs).
|
|
5
5
|
import { homedir } from "node:os";
|
|
6
6
|
import { join } from "node:path";
|
|
7
|
-
import { fileURLToPath } from "node:url";
|
|
8
7
|
import { tightenDirectory } from "../permissions.ts";
|
|
9
8
|
|
|
10
9
|
export function memoryRoot(): string {
|
|
@@ -61,27 +60,3 @@ export const HITS_FILENAME = "hits.logfmt";
|
|
|
61
60
|
export function deletionsFile(): string {
|
|
62
61
|
return join(memoryRoot(), "deletions.logfmt");
|
|
63
62
|
}
|
|
64
|
-
|
|
65
|
-
// Optional live-graph binary, used ONLY by init's opt-in indexing (#323).
|
|
66
|
-
// No read or gate path consumes the graph: gate1 resolves code refs against
|
|
67
|
-
// the live file tree, and gate evidence is identical with the index present
|
|
68
|
-
// or absent (measured, #317). Indexing therefore defaults OFF; set
|
|
69
|
-
// OPENCODE_MEMORY_GRAPH=1 to have runInit build it.
|
|
70
|
-
// Discovery order: OPENCODE_CBM_BIN override, an already-installed global on
|
|
71
|
-
// PATH (matches a running MCP session's build), then the pinned npm copy
|
|
72
|
-
// (codebase-memory-mcp is an optionalDependency of this package).
|
|
73
|
-
export function graphEnabled(): boolean {
|
|
74
|
-
return process.env.OPENCODE_MEMORY_GRAPH === "1";
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
export function cbmBin(): string | undefined {
|
|
78
|
-
if (process.env.OPENCODE_CBM_BIN) return process.env.OPENCODE_CBM_BIN;
|
|
79
|
-
if (Bun.which("codebase-memory-mcp")) return undefined;
|
|
80
|
-
try {
|
|
81
|
-
const resolved = import.meta.resolve("codebase-memory-mcp/bin.js");
|
|
82
|
-
if (resolved.startsWith("file://")) return fileURLToPath(resolved);
|
|
83
|
-
} catch {
|
|
84
|
-
// optional graph dependency not installed; PATH lookup still applies
|
|
85
|
-
}
|
|
86
|
-
return undefined;
|
|
87
|
-
}
|
package/src/core/tags.ts
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
/** Auto-capture provenance, shared by capture and retrieval. */
|
|
2
2
|
export const AUTO_CAPTURE_TAG = "auto-capture";
|
|
3
3
|
|
|
4
|
+
/**
|
|
5
|
+
* #393: a capture candidate whose numeric claim was CHECKED against the working
|
|
6
|
+
* tree and agreed. Absent on every other row, which is what makes the injected
|
|
7
|
+
* `[unverified]` marker mean something rather than decorate everything.
|
|
8
|
+
*/
|
|
9
|
+
export const CODE_CHECKED_TAG = "code-checked";
|
|
10
|
+
|
|
4
11
|
// The public write boundaries reserve this same tag (#342/#355).
|
|
5
12
|
export { USER_GUIDED_TAG } from "./guidance.ts";
|