opencode-self-improvement 0.15.38 → 0.16.1

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
@@ -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 indexes the code graph, stores the test / build / lint / typecheck commands as memories, and writes an init stamp tied to the current git head. Rerun `/repo-init force` after a refactor.
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. (Code-graph indexing is opt-in — see [Code graph](#code-graph-optional).)
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: code graph index plus build/test commands, keyed to the git head.
38
+ - **`/repo-init`** — per-repo setup: build/test commands as memories, keyed to the git head. Code-graph indexing is opt-in (`OPENCODE_MEMORY_GRAPH=1`), off by default.
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).
@@ -82,7 +82,8 @@ Zero configuration is the default. To tune, use the object form of the plugin en
82
82
  | `OPENCODE_MEMORY_INJECT_BUDGET` | Fallback for `injectBudget`. |
83
83
  | `OPENCODE_MEMORY_FRONTIER_BUDGET` | Fallback for `frontierBudget`. |
84
84
  | `OPENCODE_COMMANDS_DIR` | Where the plugin mirrors its slash commands (default `~/.config/opencode/commands`). |
85
- | `OPENCODE_CBM_BIN` | Path to a `codebase-memory-mcp` binary. See [Code graph](#code-graph-optional). |
85
+ | `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). |
86
+ | `OPENCODE_CBM_BIN` | Path to a `codebase-memory-mcp` binary, used only when `OPENCODE_MEMORY_GRAPH=1`. See [Code graph](#code-graph-optional). |
86
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). |
87
88
  | `OPENCODE_VIEWER_PORT` | Admin editor port (default `8787`). |
88
89
  | `OPENCODE_VIEWER_ALLOWED_HOSTS` | Comma-separated hosts beyond loopback. See [Surfaces](#surfaces). |
@@ -115,7 +116,7 @@ Four gates run before anything is stored, and each emits an ordered evidence lin
115
116
  3. **GATE-3 — no duplicates.** Near-duplicates collapse into the existing row; a contradiction with a superseded memory is rejected.
116
117
  4. **GATE-4 — promotion or block.** The row lands, or the call returns the reason.
117
118
 
118
- 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 changes only the prose: the row's tags, issue link, retrieval keywords, open/settled standing, and repository all carry over to the new row — 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.
119
+ 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.
119
120
 
120
121
  ## Repo scoping
121
122
 
@@ -261,6 +262,8 @@ Review the full row in the memory viewer's **quarantined** filter. **Release qua
261
262
 
262
263
  This is a heuristic review queue, not a complete prompt-injection detector: legitimate documentation or quoted code can match. Markdown-bold role headers and download-then-`&&`-execute forms are recognized, but alternate role delimiters such as `[INST]` / `<<SYS>>`, base64-to-shell pipelines, paraphrased instructions, and indirect execution can evade it. Direct `memory_remember` and human viewer edits are explicit writes and are not automatically scanned: a session with that tool still has a prose channel, mitigated by the existing framing and provenance rather than quarantine. Those defenses still apply to released rows.
263
264
 
265
+ Always-ride guidance priority is reserved to auto-capture provenance. `memory_remember`, `memory_update` replacements, and JSONL imports silently remove `user-guided` (including comma-delimited tag entries) before the write gate; their field allowlists also exclude `ref`, `claim`, and `klass`. Ordinary tags and prose can still promote normally, but a portable file, even with an export header, cannot attest that the local user stated it. The capture path owns guidance metadata; this boundary protection does not authenticate a directly edited store or guarantee that a capture model classified a statement correctly. This reservation is in place before the opt-in hint/contradiction channel lands (#342, #349).
266
+
264
267
  The viewer is a trusted admin editor: its edits and deleted-entry restores do not run the model-facing grounding or deduplication gates, but they honor the same exact and near-match value rejections. Rejected edits leave the original row, snapshots and edit audit unchanged; rejected restores append nothing. The refusal names the rejection hash so you can explicitly lift it under **Rejections → un-reject** before retrying. Corrected numeric values and polarity changes retain the rejection check's existing exceptions. This check does not change whole-snapshot rollback policy.
265
268
 
266
269
  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.
@@ -283,13 +286,15 @@ Same data behind each one (`memory_status`; no model call).
283
286
 
284
287
  ## Code graph (optional)
285
288
 
286
- `/repo-init` also indexes the repo into a queryable knowledge graph via [`codebase-memory-mcp`](https://github.com/DeusData/codebase-memory-mcp), pinned to `0.11.0` as an optional dependency. A copy already on your `PATH` is used instead; override with `OPENCODE_CBM_BIN=/path/to/codebase-memory-mcp`. Install the pinned binary globally if you prefer:
289
+ 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.
290
+
291
+ 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:
287
292
 
288
293
  ```sh
289
294
  curl -fsSL https://raw.githubusercontent.com/DeusData/codebase-memory-mcp/main/install.sh | bash
290
295
  ```
291
296
 
292
- When no graph binary is available, `/repo-init` still records scripts and the init stamp.
297
+ Whether or not the graph runs, `/repo-init` records scripts and the init stamp, and memory behaves the same.
293
298
 
294
299
  ## Installing a specific version
295
300
 
@@ -365,7 +370,8 @@ Run it when you want to know whether the suite still has teeth — after changin
365
370
  | `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. |
366
371
  | Stray `*.logfmt.lock` or `*.tmp` in the store | Write bookkeeping; safe to delete while nothing is writing. |
367
372
  | `/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. |
368
- | Init says `Graph: unavailable` | `codebase-memory-mcp` couldn't start. Install pinned `0.11.0` or point `OPENCODE_CBM_BIN` at the binary. Scripts are still remembered without it. |
373
+ | Init says `Graph: disabled` | Expected default — code-graph indexing is opt-in and nothing reads the index. Set `OPENCODE_MEMORY_GRAPH=1` to enable. Scripts are remembered either way. |
374
+ | 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. |
369
375
  | 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. |
370
376
  | `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. |
371
377
  | 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`. |
@@ -1,14 +1,17 @@
1
1
  ---
2
- description: Initialize the code graph and build/test memories for this repo
2
+ description: Initialize build/test memories for this repo (code graph is opt-in)
3
3
  ---
4
- Initialize this repository for durable memory and graph-backed work.
4
+ Initialize this repository for durable memory.
5
5
 
6
- 1. Ensure the codebase-memory graph is indexed for this repository.
7
- 2. Re-derive build/lint/test/typecheck commands and write them as pattern
6
+ 1. Re-derive build/lint/test/typecheck commands and write them as pattern
8
7
  memories (scope = this repo name).
9
- 3. Store an init stamp keyed on git HEAD so future sessions can cheaply tell
8
+ 2. Store an init stamp keyed on git HEAD so future sessions can cheaply tell
10
9
  whether the repo has drifted.
11
10
 
11
+ Code-graph indexing is opt-in and off by default (`Graph: disabled`); nothing
12
+ reads the index. Only build it if the user asked for it, by setting
13
+ `OPENCODE_MEMORY_GRAPH=1` before the call.
14
+
12
15
  Call the `memory_init` tool to do this. If the user typed arguments (e.g.
13
16
  "force"), pass them through: set `force: true` when $ARGUMENTS mentions force,
14
17
  otherwise run a fresh idempotent init.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.15.38",
3
+ "version": "0.16.1",
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": {
@@ -27,7 +27,18 @@ export const CAPTURE_KEYWORD_CHARS = 48;
27
27
 
28
28
  // Prompt for the cheap capture model. The output contract is a bare JSON
29
29
  // array so parseCandidates can trust it; anything else parses to [].
30
- export function buildCapturePrompt(transcript: string, max = 3): string {
30
+ //
31
+ // `userProse` keeps the session's brief OUT of the work block. Measured on the
32
+ // fixture that reproduces #329: brief mixed into one undifferentiated block,
33
+ // the model stores it back as a durable `preference`; work block alone, zero
34
+ // framing rows — but also zero real preferences, because "we use bun here, not
35
+ // npm" lives in the same prose. So the prose is kept, labelled for what it is.
36
+ export function buildCapturePrompt(
37
+ transcript: string,
38
+ max = 3,
39
+ userProse = "",
40
+ ): string {
41
+ const prose = redactSecrets(userProse).trim();
31
42
  return [
32
43
  "You mine one coding-agent session transcript for durable memories worth keeping across future sessions.",
33
44
  "",
@@ -42,9 +53,29 @@ export function buildCapturePrompt(transcript: string, max = 3): string {
42
53
  "- kw: 3-5 search keywords for how a DIFFERENT session would ask for this — synonyms and alternate names, other verb forms, the literal command or file name. They are indexed for retrieval and never shown to a model. Omit (or []) when the content already uses those words.",
43
54
  "- Keep: decisions made, working commands, user preferences, blockers hit, durable context, conventions.",
44
55
  "- Skip: anything derivable from the code or git history, small talk, and details that only mattered inside this conversation.",
56
+ ...(prose
57
+ ? [
58
+ // The brief is its own block, so the rule about it is its own too.
59
+ '- 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").',
60
+ ]
61
+ : []),
62
+ // Permission to emit fewer rows is what bounds deliberation. On the
63
+ // reproducing fixture the same seat went 1,095 -> 3,084 completion tokens
64
+ // and 19.7s -> 63.2s with this line removed, and the same rows out. It
65
+ // also stops one instruction arriving as the same fact under three scope
66
+ // names, which the store's 0.9 overlap floor does not see once the
67
+ // wording differs.
68
+ "- Few is better than full. If two candidates say the same thing about the same area, keep the one carrying the specific number, path, or command and drop the other. Never emit the same fact twice under different scope names.",
45
69
  "- If nothing is worth remembering, output [ ].",
46
70
  "",
47
- "Transcript:",
48
- redactSecrets(transcript),
71
+ ...(prose
72
+ ? [
73
+ "Session work (what the agent did — this is the evidence):",
74
+ redactSecrets(transcript),
75
+ "",
76
+ "REQUESTS (the user's brief for this session; constraints of THIS task, mostly not durable):",
77
+ prose,
78
+ ]
79
+ : ["Transcript:", redactSecrets(transcript)]),
49
80
  ].join("\n");
50
81
  }
@@ -1,18 +1,18 @@
1
1
  // Opt-in capture configuration and dispatch (#168). Cooldowns remain process-wide;
2
2
  // subscriptions and dispatch closures belong to one setup instance.
3
3
  import type { Cleanup } from "@opencode/plugin/promise/plugin";
4
- import { runWriteGate, type GateContext } from "../gate/gate.ts";
5
- import { record, recordCaptureLag } from "../evidence/record.ts";
6
4
  import { setCurrent } from "../core/state.ts";
7
- import { bindSessionProvisional, writeTarget } from "../identity/repokey.ts";
5
+ import { record, recordCaptureLag } from "../evidence/record.ts";
6
+ import { type GateContext, runWriteGate } from "../gate/gate.ts";
8
7
  import { captureSessionID } from "../identity/host-events.ts";
8
+ import { bindSessionProvisional, writeTarget } from "../identity/repokey.ts";
9
9
  import { quarantineCandidate } from "../store/quarantine/quarantine.ts";
10
10
  import { redactSecrets } from "../store/secrets.ts";
11
11
  import { parseCandidates, parseModelRef } from "./candidates.ts";
12
- import { sessionModel, type SessionModelRef } from "./session-model.ts";
13
12
  import { lagSince } from "./lag.ts";
14
13
  import { buildCapturePrompt } from "./prompt.ts";
15
- import { flattenTranscript } from "./transcript.ts";
14
+ import { type SessionModelRef, sessionModel } from "./session-model.ts";
15
+ import { flattenTranscript, splitTranscript } from "./transcript.ts";
16
16
 
17
17
  interface CaptureHost {
18
18
  options?: Record<string, unknown>;
@@ -172,18 +172,16 @@ export function configureAutoCapture(
172
172
  return null;
173
173
  };
174
174
 
175
- // ONE capture pass, shared by both triggers. `seeded` is a transcript
176
- // already in hand — the compaction hook carries the PRE-compaction
177
- // messages, which is the whole point (Compaction Cliff: one round
178
- // retains 53% of exact-wording rules); when it is absent (older host
179
- // shapes) or too thin, the session context is read instead, the same
180
- // source the idle trigger mines.
181
- async function captureSession(
182
- sid: string,
183
- seeded: string,
184
- trigger: "idle" | "compaction",
185
- seededMsgs?: unknown,
186
- ): Promise<void> {
175
+ // Bind the capturing session and freeze its evidence context in ONE sync
176
+ // step, before the capture's first await. Binding is not enough on its
177
+ // own: record() resolves a session's repository at CALL time, so a
178
+ // `session.moved` delivered during the model call moves it, and every
179
+ // receipt appended after that await carries the NEW repository. The
180
+ // failure of repo A's capture would then be readable only from repo B
181
+ // and invisible to the session that actually failed. Callers freeze
182
+ // here and thread the result through, including into their own failure
183
+ // receipt.
184
+ function bindCapture(sid: string): GateContext {
187
185
  // Bind the capturing session for the synchronous stretches of this
188
186
  // path - but NOT as a promise: the awaits below let another session
189
187
  // move current, so the gate context and the persisted rows thread
@@ -196,7 +194,26 @@ export function configureAutoCapture(
196
194
  // no-op there). SYNC only: a lookup call here would break the
197
195
  // zero-token promise of the capture tests.
198
196
  bindSessionProvisional(sid, instanceDir);
199
- const captureGate = gateContext(sid);
197
+ return gateContext(sid);
198
+ }
199
+
200
+ // ONE capture pass, shared by both triggers. `seeded` is a transcript
201
+ // already in hand — the compaction hook carries the PRE-compaction
202
+ // messages, which is the whole point (Compaction Cliff: one round
203
+ // retains 53% of exact-wording rules); when it is absent (older host
204
+ // shapes) or too thin, the session context is read instead, the same
205
+ // source the idle trigger mines.
206
+ async function captureSession(
207
+ sid: string,
208
+ seeded: string,
209
+ trigger: "idle" | "compaction",
210
+ seededMsgs?: unknown,
211
+ // Frozen by the trigger before its first await, so a session move
212
+ // cannot re-stamp this operation's receipts. Optional for direct
213
+ // callers, which bind here instead.
214
+ gate?: GateContext,
215
+ ): Promise<void> {
216
+ const captureGate = gate ?? bindCapture(sid);
200
217
  // #139: resolve the model BEFORE any skip so every capture evidence
201
218
  // line below can carry model= (cost attributable to a named model —
202
219
  // the real answer to the cost-surprise concern that justified the
@@ -240,12 +257,41 @@ export function configureAutoCapture(
240
257
  msgs = await contextFn({ sessionID: sid });
241
258
  transcript = flattenTranscript(msgs);
242
259
  }
243
- if (transcript.length < 200) return; // too thin to mine reliably
260
+ if (transcript.length < 200) {
261
+ // This return used to be silent, and that silence is why a dead
262
+ // auto-capture looked like a working one: "the transcript was too
263
+ // thin to mine" and "the host never emitted the event" produced
264
+ // byte-identical stores. Record the skip with its size so the two
265
+ // are distinguishable from the evidence file alone.
266
+ await record(
267
+ "auto_capture_skipped",
268
+ {
269
+ session: sid,
270
+ trigger,
271
+ reason: "transcript_too_thin",
272
+ chars: transcript.length,
273
+ ...(modelTag ? { model: modelTag } : {}),
274
+ },
275
+ true,
276
+ sid,
277
+ captureGate.evidenceContext,
278
+ );
279
+ return; // too thin to mine reliably
280
+ }
244
281
  // #44: how stale is a capture? Distance from the newest message of
245
282
  // the mined transcript to this instant - measured on whatever the
246
283
  // trigger actually mined (the hook payload for compaction, the
247
284
  // session context for idle), so both triggers' lag is comparable.
248
285
  const lagMs = lagSince(msgs);
286
+ // #333: partition what was mined, so the user's brief is labelled as
287
+ // the brief instead of blending into the evidence. Falls back to the
288
+ // single un-partitioned block when the work lines alone are too thin
289
+ // (a seeded transcript with no message array behind it), which keeps
290
+ // the old prompt shape rather than silently dropping the prose.
291
+ const split = splitTranscript(msgs);
292
+ const partitioned = split.work.length >= 200;
293
+ const work = partitioned ? split.work : transcript;
294
+ const userProse = partitioned ? split.user : "";
249
295
  const out = await generateApi.text({
250
296
  model,
251
297
  // Redact the COMPLETE transcript, THEN apply the character budget
@@ -254,8 +300,9 @@ export function configureAutoCapture(
254
300
  // fell off, matches no pattern — buildCapturePrompt's own scrub
255
301
  // (kept, defense in depth) cannot recognize a fragment.
256
302
  prompt: buildCapturePrompt(
257
- redactSecrets(transcript).slice(-8000),
303
+ redactSecrets(work).slice(-7000),
258
304
  captureMax,
305
+ redactSecrets(userProse).slice(-1500),
259
306
  ),
260
307
  });
261
308
  const text = typeof out === "string" ? out : (out?.text ?? "");
@@ -336,10 +383,33 @@ export function configureAutoCapture(
336
383
  setCurrent({ sessionID: sid });
337
384
  const now = Date.now();
338
385
  if (!captureCooldownPasses("idle", sid, now)) continue; // 5-min cooldown, shared across setups
386
+ // Freeze the operation's evidence context before its first await.
387
+ // The catch below runs after the model call, where a
388
+ // `session.moved` may already have re-pointed this session at
389
+ // another repository; resolving it there would stamp the failure
390
+ // receipt of repo A's capture as repo B's evidence.
391
+ let opGate: GateContext | undefined;
339
392
  try {
340
- await captureSession(sid, "", "idle");
341
- } catch {
342
- // fail-closed: a broken capture attempt is invisible to the session
393
+ opGate = bindCapture(sid);
394
+ await captureSession(sid, "", "idle", undefined, opGate);
395
+ } catch (err) {
396
+ // Fail-closed for the SESSION, never silent in the store: the
397
+ // same silence that hid the 2.2.5 shape break would make a
398
+ // throwing capture indistinguishable from one that never ran.
399
+ await record(
400
+ "auto_capture_refused",
401
+ {
402
+ session: sid,
403
+ trigger: "idle",
404
+ reason: "capture_threw",
405
+ error: redactSecrets(
406
+ String((err as Error)?.message ?? err),
407
+ ).slice(0, 200),
408
+ },
409
+ true,
410
+ sid,
411
+ opGate?.evidenceContext,
412
+ );
343
413
  }
344
414
  }
345
415
  } catch {
@@ -359,12 +429,16 @@ export function configureAutoCapture(
359
429
  if (controller.signal.aborted) return;
360
430
  const now = Date.now();
361
431
  if (!captureCooldownPasses("compaction", sid, now)) return; // 5-min cooldown
432
+ // Same freeze as the idle trigger, and for the same reason: sync,
433
+ // before guarded() starts awaiting.
434
+ const opGate = bindCapture(sid);
362
435
  void guarded("session.compaction (auto-capture)", () =>
363
436
  captureSession(
364
437
  sid,
365
438
  flattenTranscript(messages),
366
439
  "compaction",
367
440
  messages,
441
+ opGate,
368
442
  ),
369
443
  );
370
444
  };
@@ -3,14 +3,45 @@
3
3
  // Render an array of session-context messages of unknown shape into
4
4
  // "role: text" lines. Defensive by construction (the API shape varies and is
5
5
  // not ours to trust): non-arrays and junk entries are skipped; role comes
6
- // from info.role | role, text from parts[].text | text | content (strings
7
- // only); capped at 40 user turns. Never throws.
6
+ // from info.role | role | type, text from parts[].text | content[].text |
7
+ // text | content (strings only); capped at 40 user turns. Never throws.
8
+ //
9
+ // The `type` role source and the `content[]` part array are the 2.2.5 host
10
+ // shape, recorded live: `session.context()` returns
11
+ // `{id, time, type:"user", text}` and `{id, time, type:"assistant", content:
12
+ // [{type:"reasoning"|"tool"|"text", ...}]}` — no `role`, no `parts`. Reading
13
+ // only the old keys rendered EVERY 2.2.5 session as a 0-character transcript,
14
+ // which the 200-character floor then skipped in silence: auto-capture never
15
+ // fired on a live host, and nothing said so.
8
16
  const TRANSCRIPT_USER_TURN_CAP = 40;
9
17
 
10
- export function flattenTranscript(msgs: unknown): string {
18
+ // 2.2.5 also puts NON-conversation records in the same array (`type:"idle"`),
19
+ // so only these values are accepted as a role. Anything else renders nothing.
20
+ const CONVERSATION_ROLES: readonly string[] = ["user", "assistant"];
21
+
22
+ function roleOf(
23
+ m: Record<string, unknown>,
24
+ info: Record<string, unknown> | undefined,
25
+ ): string {
26
+ for (const v of [info?.role, m.role, m.type])
27
+ if (typeof v === "string" && CONVERSATION_ROLES.includes(v)) return v;
28
+ return "";
29
+ }
30
+
31
+ interface ParsedTurn {
32
+ role: string;
33
+ text: string;
34
+ }
35
+
36
+ /**
37
+ * Parse session-context messages into ordered conversation turns. Shared by
38
+ * `flattenTranscript` and `splitTranscript` so the two can never disagree
39
+ * about what a message contained. Total: junk yields [], never a throw.
40
+ */
41
+ function parseTurns(msgs: unknown): ParsedTurn[] {
11
42
  try {
12
- if (!Array.isArray(msgs)) return "";
13
- const lines: string[] = [];
43
+ if (!Array.isArray(msgs)) return [];
44
+ const out: ParsedTurn[] = [];
14
45
  let userTurns = 0;
15
46
  for (const msg of msgs) {
16
47
  if (!msg || typeof msg !== "object") continue;
@@ -19,16 +50,17 @@ export function flattenTranscript(msgs: unknown): string {
19
50
  m.info && typeof m.info === "object"
20
51
  ? (m.info as Record<string, unknown>)
21
52
  : undefined;
22
- const role =
23
- typeof info?.role === "string"
24
- ? info.role
25
- : typeof m.role === "string"
26
- ? m.role
27
- : "";
53
+ const role = roleOf(m, info);
28
54
  let text = "";
29
55
  let hadPrivatePart = false;
30
- if (Array.isArray(m.parts)) {
31
- text = m.parts
56
+ // V1 carried parts under `parts`; 2.2.5 carries them under `content`.
57
+ const partList = Array.isArray(m.parts)
58
+ ? m.parts
59
+ : Array.isArray(m.content)
60
+ ? m.content
61
+ : null;
62
+ if (partList) {
63
+ text = partList
32
64
  .map((p) => {
33
65
  if (!p || typeof p !== "object") return undefined;
34
66
  const part = p as Record<string, unknown>;
@@ -56,10 +88,43 @@ export function flattenTranscript(msgs: unknown): string {
56
88
  userTurns++;
57
89
  if (userTurns > TRANSCRIPT_USER_TURN_CAP) break;
58
90
  }
59
- lines.push(`${role}: ${text.trim()}`);
91
+ out.push({ role, text: text.trim() });
60
92
  }
61
- return lines.join("\n");
93
+ return out;
62
94
  } catch {
63
- return "";
95
+ return [];
96
+ }
97
+ }
98
+
99
+ export function flattenTranscript(msgs: unknown): string {
100
+ return parseTurns(msgs)
101
+ .map(({ role, text }) => `${role}: ${text}`)
102
+ .join("\n");
103
+ }
104
+
105
+ /**
106
+ * The same turns, partitioned (#333).
107
+ *
108
+ * `work` — every turn that is NOT the user's: what the agent said and what the
109
+ * tools returned. This is the evidence.
110
+ * `user` — the user turns, i.e. the task's brief.
111
+ *
112
+ * Why partition rather than concatenate: measured on the fixture that
113
+ * reproduces #329, an undifferentiated block makes the model store the brief
114
+ * back as a durable `preference`. Work alone stores zero framing rows — and
115
+ * zero real preferences, because "we use bun here, not npm" lives in the same
116
+ * prose. So the prose is kept, labelled, in its own block: `buildCapturePrompt`.
117
+ */
118
+ export interface TranscriptSplit {
119
+ work: string;
120
+ user: string;
121
+ }
122
+
123
+ export function splitTranscript(msgs: unknown): TranscriptSplit {
124
+ const work: string[] = [];
125
+ const user: string[] = [];
126
+ for (const { role, text } of parseTurns(msgs)) {
127
+ (role === "user" ? user : work).push(`${role}: ${text}`);
64
128
  }
129
+ return { work: work.join("\n"), user: user.join("\n") };
65
130
  }
@@ -62,12 +62,18 @@ export function deletionsFile(): string {
62
62
  return join(memoryRoot(), "deletions.logfmt");
63
63
  }
64
64
 
65
- // Optional live-graph binary. When present the resolver cross-checks the local
66
- // source scan against the codebase-memory-mcp file graph; when absent the local
67
- // scan alone is authoritative (install-from-scratch requirement).
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.
68
70
  // Discovery order: OPENCODE_CBM_BIN override, an already-installed global on
69
71
  // PATH (matches a running MCP session's build), then the pinned npm copy
70
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
+
71
77
  export function cbmBin(): string | undefined {
72
78
  if (process.env.OPENCODE_CBM_BIN) return process.env.OPENCODE_CBM_BIN;
73
79
  if (Bun.which("codebase-memory-mcp")) return undefined;
@@ -0,0 +1,13 @@
1
+ /** Capture-only provenance: grants always-ride priority in the hint channel. */
2
+ export const USER_GUIDED_TAG = "user-guided";
3
+
4
+ /**
5
+ * Tool/import input cannot grant capture provenance. Split the storage
6
+ * delimiter first: ["ordinary,user-guided"] reads back as two tags too.
7
+ * Silently drop the reserved tag; ordinary prose still faces the write gate.
8
+ */
9
+ export function nonCaptureTags(tags?: string[]): string[] | undefined {
10
+ return tags
11
+ ?.flatMap((tag) => tag.split(","))
12
+ .filter((tag) => tag !== USER_GUIDED_TAG);
13
+ }
@@ -18,7 +18,10 @@ export interface ScriptRecord {
18
18
  }
19
19
 
20
20
  export interface GraphStatus {
21
- action: "indexed" | "unavailable" | "index-failed";
21
+ // "disabled": graph indexing is opt-in (OPENCODE_MEMORY_GRAPH=1) and was
22
+ // not requested — the default. No spawn occurs and nothing is lost: no
23
+ // read or gate path consumes the index (see #323).
24
+ action: "disabled" | "indexed" | "unavailable" | "index-failed";
22
25
  name?: string;
23
26
  mode: string;
24
27
  }
package/src/init/run.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  // run — split from src/init.ts (#168 domain restructure). Declaration bodies are unchanged.
2
- // Repository init: ensure the codebase-memory graph exists for this repo and
3
- // re-derive build/test command memories through the write gate. Deterministic
2
+ // Repository init: re-derive build/test command memories through the write
3
+ // gate, and — only when opted in via OPENCODE_MEMORY_GRAPH=1 (#323) — ensure
4
+ // the codebase-memory graph exists for this repo. Deterministic
4
5
  // (no model calls): the graph binary is spawned one-shot via `cli`, manifests
5
6
  // are parsed locally, and every write goes through the 4-gate pipeline with the
6
7
  // `trusted` flag (plugin-authored bookkeeping, not model claims). Degrades
@@ -18,6 +19,7 @@ import { runWriteGate, type GateContext } from "../gate/gate.ts";
18
19
  import { captureEvidenceContext, record } from "../evidence/record.ts";
19
20
  import { writeEvidence, hasGateCheck } from "../capture/triggers.ts";
20
21
  import { writeTarget } from "../identity/repokey.ts";
22
+ import { graphEnabled } from "../core/config/paths.ts";
21
23
  import { getCurrent } from "../core/state.ts";
22
24
  import {
23
25
  type GraphStatus,
@@ -133,7 +135,11 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
133
135
  scope,
134
136
  root,
135
137
  head,
136
- graph: { action: "indexed", mode },
138
+ // A skipped init reports what THIS build would do, not what the prior
139
+ // stamp's build did: on a disabled build nothing is indexed (#323).
140
+ graph: graphEnabled()
141
+ ? { action: "indexed", mode }
142
+ : { action: "disabled", mode },
137
143
  scripts: [],
138
144
  stampTs: prior.ts,
139
145
  skipped: true,
@@ -151,7 +157,13 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
151
157
  evidenceContext,
152
158
  );
153
159
 
154
- const graph = await ensureGraph(root, mode, force);
160
+ // Graph indexing is opt-in (#323). Measured on the benchmark: 11.5-26s per
161
+ // init on the first-write critical path, it failed in 29 of 32 real inits,
162
+ // and no read or gate path consumes the index (gate evidence is identical
163
+ // with it present or absent). Skip the spawn unless explicitly requested.
164
+ const graph: GraphStatus = graphEnabled()
165
+ ? await ensureGraph(root, mode, force)
166
+ : { action: "disabled", mode };
155
167
  const scripts = await detectScripts(root);
156
168
 
157
169
  let written = 0;
@@ -12,6 +12,7 @@ import { getCurrent } from "../core/state.ts";
12
12
  import { TYPES } from "../core/types.ts";
13
13
  import type { WriteCandidate } from "../gate/gate.ts";
14
14
  import { flattenMemoryText } from "../store/sanitize.ts";
15
+ import { nonCaptureTags } from "../core/guidance.ts";
15
16
  import { EXPORT_VERSION, exportHeader, stamp } from "./export.ts";
16
17
 
17
18
  // --- import -------------------------------------------------------------------
@@ -75,7 +76,9 @@ function parseRow(line: string): WriteCandidate | null {
75
76
  };
76
77
  if (r.status === "open" || r.status === "settled") c.status = r.status;
77
78
  if (Array.isArray(r.tags) && r.tags.every((t) => typeof t === "string"))
78
- c.tags = r.tags;
79
+ c.tags = nonCaptureTags(r.tags);
80
+ // ref/claim/klass are deliberately absent from this allowlist: a file
81
+ // (including one carrying our export header) cannot attest user guidance.
79
82
  if (kw?.length) c.kw = kw;
80
83
  if (typeof r.issue === "string" && r.issue) c.issue = r.issue;
81
84
  // Origin stamps survive an export/import hop (repokey.ts): a row written
package/src/tools/init.ts CHANGED
@@ -19,7 +19,7 @@ export const register: ToolRegister = (editor, deps) => {
19
19
  validated(InitArgs, {
20
20
  name: "memory_init",
21
21
  description:
22
- "Initialize repository memory and knowledge graph. Ensures the codebase-memory graph for this repo is indexed (one-shot `cli` spawn; no session MCP needed) and re-derives build/lint/test/typecheck command memories through the write gate, then stores an init stamp keyed on git HEAD. Idempotent: a no-op when the stamp matches HEAD, unless force=true (refresh after a refactor).",
22
+ "Initialize repository memory: re-derives build/lint/test/typecheck command memories through the write gate and stores an init stamp keyed on git HEAD. Idempotent: a no-op when the stamp matches HEAD, unless force=true (refresh after a refactor). Codebase-memory graph indexing is OPT-IN (set OPENCODE_MEMORY_GRAPH=1) and off by default: no read or gate path consumes the index, and the spawn cost 11-26s per init when it ran. Memory works without it.",
23
23
  options: direct,
24
24
  async execute(args, context): Promise<{ content: string }> {
25
25
  const { sid } = toolIds(context);
@@ -5,6 +5,7 @@ import type { ToolRegister } from "./deps.ts";
5
5
  import { auditCaveat, runWriteGate } from "../gate/gate.ts";
6
6
  import type { WriteCandidate } from "../gate/gate.ts";
7
7
  import { RememberArgs, validated } from "./schema.ts";
8
+ import { nonCaptureTags } from "../core/guidance.ts";
8
9
 
9
10
  export const register: ToolRegister = (editor, deps) => {
10
11
  const {
@@ -28,7 +29,7 @@ export const register: ToolRegister = (editor, deps) => {
28
29
  scope: args.scope,
29
30
  content: args.content,
30
31
  issue: args.issue,
31
- tags: args.tags,
32
+ tags: nonCaptureTags(args.tags),
32
33
  kw: args.kw,
33
34
  status: args.status,
34
35
  repo: args.global ? "global" : undefined,
@@ -15,6 +15,7 @@ import type { Memory } from "../store/model/memory.ts";
15
15
  import { UpdateArgs, validated } from "./schema.ts";
16
16
  import { redactSecrets } from "../store/secrets.ts";
17
17
  import { join } from "node:path";
18
+ import { nonCaptureTags } from "../core/guidance.ts";
18
19
 
19
20
  export const register: ToolRegister = (editor, deps) => {
20
21
  const {
@@ -29,7 +30,7 @@ export const register: ToolRegister = (editor, deps) => {
29
30
  validated(UpdateArgs, {
30
31
  name: "memory_update",
31
32
  description:
32
- "Update an existing memory (gated like remember; the prior entry is superseded, not erased). `query` selects which row to update: its exact id (ts), a clock fragment (e.g. HH:MM:SS.mmm), or a unique substring of its content. Omitting `query` targets the most recent active row of scope+type. An unmatched or ambiguous `query` fails closed and writes nothing. A prose edit carries over everything the call does not name — tags, issue, keywords, status, and the row's repository. Naming a row that was already updated to exactly this content (metadata included) reports the duplicate; if its live successor holds the prose and only the metadata you name differs, the successor is updated. A failure after the write is reported as PARTIAL: the replacement is durable and memory_undo merge/force restores the old row.",
33
+ "Update an existing memory (gated like remember; the prior entry is superseded, not erased). `query` selects which row to update: its exact id (ts), a clock fragment (e.g. HH:MM:SS.mmm), or a unique substring of its content. Omitting `query` targets the most recent active row of scope+type. An unmatched or ambiguous `query` fails closed and writes nothing. A prose edit carries over everything the call does not name — ordinary tags, issue, keywords, status, and the row's repository. Capture-only guidance provenance is removed from replacements. Naming a row that was already updated to exactly this content (metadata included) reports the duplicate; if its live successor holds the prose and only the metadata you name differs, the successor is updated. A failure after the write is reported as PARTIAL: the replacement is durable and memory_undo merge/force restores the old row.",
33
34
  options: direct,
34
35
  async execute(args, context): Promise<{ content: string }> {
35
36
  const { sid } = toolIds(context);
@@ -183,7 +184,9 @@ export const register: ToolRegister = (editor, deps) => {
183
184
  // "already standing" on a row holding ["old-alias"].
184
185
  const requested = {
185
186
  kw: args.kw ?? target.kw,
186
- tags: target.tags,
187
+ // A model-authored successor cannot attest that the user
188
+ // stated its prose, even when it replaces a captured row.
189
+ tags: nonCaptureTags(target.tags),
187
190
  issue: target.issue,
188
191
  status: args.status ?? target.status ?? "settled",
189
192
  repo: target.repo ?? "global",