opencode-self-improvement 0.22.0 → 0.22.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md 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. (Code-graph indexing is opt-in — see [Code graph](#code-graph-optional).)
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. Code-graph indexing is opt-in (`OPENCODE_MEMORY_GRAPH=1`), off by default.
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). |
@@ -250,7 +248,7 @@ Limits worth knowing:
250
248
  - It can miss hex-only secrets, low-diversity passwords, and credentials written in prose without an assignment.
251
249
  - Credential-shaped `scope`, `tags` or `issue` metadata is rejected rather than silently rewritten.
252
250
  - `memory_remember` still replies `Remembered` when content was redacted, so the stored text can differ from what was sent.
253
- - Redaction is forward-only: existing stores are not scrubbed, and `memory_export` writes what is already stored verbatim.
251
+ - 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.
254
252
 
255
253
  ## Export and move between machines
256
254
 
@@ -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
- | 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. |
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`. |
@@ -1,5 +1,5 @@
1
1
  ---
2
- description: Initialize build/test memories for this repo (code graph is opt-in)
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
- 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.
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: graph status, scripts recorded, and the stamp head.
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.22.0",
3
+ "version": "0.22.2",
4
4
  "description": "Durable memory for opencode: remember facts, decisions, and commands across sessions, plus a one-command per-repo setup (/repo-init).",
5
5
  "main": "index.ts",
6
6
  "exports": {
@@ -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",
@@ -1,6 +1,7 @@
1
1
  // render — split from src/consolidate.ts (#168 domain restructure). Declaration bodies are unchanged.
2
2
 
3
3
  import { type ProposalReport } from "./propose.ts";
4
+ import { flattenMemoryText } from "../store/sanitize.ts";
4
5
 
5
6
  /** Human-readable proposal list. Ends with the exact command to resolve one. */
6
7
  export function renderProposals(report: ProposalReport): string {
@@ -13,8 +14,13 @@ export function renderProposals(report: ProposalReport): string {
13
14
  out.push(
14
15
  `${p.id} ${p.type}/${p.scope} ${p.losers.length + 1} rows → 1`,
15
16
  ` keep ${p.survivor.ts}`,
16
- ` ${p.survivor.content.slice(0, 160)}`,
17
- ...p.losers.map((l) => ` absorb ${l.ts} ${l.content.slice(0, 120)}`),
17
+ // Row prose is multiline in the store and flattened only here (#299):
18
+ // one row is one output line, the same rule memory_recall follows.
19
+ ` ${flattenMemoryText(p.survivor.content.slice(0, 160))}`,
20
+ ...p.losers.map(
21
+ (l) =>
22
+ ` absorb ${l.ts} ${flattenMemoryText(l.content.slice(0, 120))}`,
23
+ ),
18
24
  ` reads ${p.reads.length} logged · best member alone ${p.bestMemberBefore} · merged ${p.readsAfter}`,
19
25
  ` budget ${p.bytesBefore}c → ${p.bytesAfter}c for this cluster`,
20
26
  ` resolve: memory_merge_review(loser="${p.losers[0]!.ts}", survivor="${p.survivor.ts}", reason="consolidate ${p.id}")`,
@@ -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/gate/gate.ts CHANGED
@@ -824,7 +824,8 @@ export async function runWriteGate(
824
824
  // on the read path (it covers every consumer, the viewer included), and this
825
825
  // is the seam where the value becomes a model-facing sentence.
826
826
  const why =
827
- redactSecrets(rejection.tombstone.reason) || "no reason recorded";
827
+ flattenMemoryText(redactSecrets(rejection.tombstone.reason)) ||
828
+ "no reason recorded";
828
829
  const tch = rejection.tombstone.ch;
829
830
  // The escape-hatch tail is shared by BOTH kinds. An earlier draft put it
830
831
  // only on the near-match branch, which left the COMMON case — a byte-exact
@@ -1,6 +1,5 @@
1
1
  // GATE-1 resolver. Extracts embedded path/symbol refs from a memory/evidence
2
- // candidate and re-resolves them against the live source tree (and, when
3
- // OPENCODE_CBM_BIN is set, the codebase-memory-mcp file graph). Deterministic:
2
+ // candidate and re-resolves them against the live source tree. Deterministic:
4
3
  // regex + balanced-paren scanning, no model involvement.
5
4
  import { join } from "node:path";
6
5
  import { opendir } from "node:fs/promises";
@@ -1,15 +1,14 @@
1
1
  // detect — 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
4
- // (no model calls): the graph binary is spawned one-shot via `cli`, manifests
5
- // are parsed locally, and every write goes through the 4-gate pipeline with the
6
- // `trusted` flag (plugin-authored bookkeeping, not model claims). Degrades
7
- // gracefully when the binary or git is absent, so install-from-scratch still
8
- // writes script memories.
2
+ // Repository init: re-derive build/test command memories through the write gate.
3
+ // Deterministic (no model calls): manifests are parsed locally and every write
4
+ // goes through the 4-gate pipeline with the `trusted` flag (plugin-authored
5
+ // bookkeeping, not model claims). Degrades gracefully when git is absent, so
6
+ // install-from-scratch still writes script memories.
7
+ // The codebase-memory graph integration was removed (#231): no read or gate
8
+ // path ever consumed the index, and spawning a pinned third-party binary in
9
+ // the user's repository was a supply-chain surface with no consumer.
9
10
  import { join } from "node:path";
10
11
  import { existsSync } from "node:fs";
11
- import { cbmBin } from "../core/config/paths.ts";
12
- import { run } from "./run.ts";
13
12
 
14
13
  export interface ScriptRecord {
15
14
  key: string;
@@ -17,15 +16,6 @@ export interface ScriptRecord {
17
16
  source: string;
18
17
  }
19
18
 
20
- export interface GraphStatus {
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";
25
- name?: string;
26
- mode: string;
27
- }
28
-
29
19
  const NOTABLE_KEYS = [
30
20
  "test",
31
21
  "e2e",
@@ -73,6 +63,15 @@ async function readText(root: string, file: string): Promise<string | null> {
73
63
  }
74
64
  }
75
65
 
66
+ // A script key becomes the command a later session is told to run, so it may
67
+ // only be an identifier: no whitespace and no shell metacharacter can survive
68
+ // into `npm run <key>`. `:` and `.` are allowed because `test:ci` and
69
+ // `lint.fix` are ordinary npm keys (this is wider than #301's literal
70
+ // `[A-Za-z0-9_-]+`, which would drop them; the rejection this ticket is about —
71
+ // `test && echo SYNTHETIC` — is rejected either way). Make/Just targets use the
72
+ // narrower class already, and a Make target cannot contain `:` in any case.
73
+ const SCRIPT_KEY = /^[A-Za-z0-9_.:-]+$/;
74
+
76
75
  async function detectPackageScripts(
77
76
  root: string,
78
77
  records: ScriptRecord[],
@@ -89,6 +88,7 @@ async function detectPackageScripts(
89
88
  const seen = new Set<string>();
90
89
  for (const name of Object.keys(pkg.scripts as Record<string, unknown>)) {
91
90
  if (seen.has(name) || !isNotable(name.toLowerCase())) continue;
91
+ if (!SCRIPT_KEY.test(name)) continue; // crafted key: skip the record
92
92
  seen.add(name);
93
93
  records.push({ key: name, cmd: `npm run ${name}`, source: "package.json" });
94
94
  }
@@ -136,62 +136,3 @@ export async function detectScripts(root: string): Promise<ScriptRecord[]> {
136
136
  await detectLangManifests(root, records);
137
137
  return records.slice(0, 8);
138
138
  }
139
-
140
- async function cbmProject(
141
- bin: string,
142
- root: string,
143
- ): Promise<{ name: string } | null> {
144
- const r = await run(
145
- [
146
- bin,
147
- "cli",
148
- "--quiet",
149
- "list_projects",
150
- "--format",
151
- "json",
152
- "--metadata-only",
153
- ],
154
- root,
155
- );
156
- if (!r.ok || !r.out) return null;
157
- try {
158
- const env = JSON.parse(r.out) as {
159
- projects?: { name: string; root_path: string }[];
160
- };
161
- const hit = env.projects?.find((p) => p.root_path === root);
162
- return hit ? { name: hit.name } : null;
163
- } catch {
164
- return null;
165
- }
166
- }
167
-
168
- export async function ensureGraph(
169
- root: string,
170
- mode: string,
171
- force: boolean,
172
- ): Promise<GraphStatus> {
173
- const bin = cbmBin() ?? "codebase-memory-mcp";
174
- const existing = await cbmProject(bin, root);
175
- if (existing && !force)
176
- return { action: "indexed", name: existing.name, mode };
177
- const r = await run(
178
- [
179
- bin,
180
- "cli",
181
- "--quiet",
182
- "index_repository",
183
- "--repo-path",
184
- root,
185
- "--mode",
186
- mode,
187
- ],
188
- root,
189
- );
190
- if (!r.ok) return { action: "unavailable", mode };
191
- const after = await cbmProject(bin, root);
192
- return {
193
- action: after ? "indexed" : "index-failed",
194
- name: after?.name,
195
- mode,
196
- };
197
- }
@@ -1,12 +1,6 @@
1
1
  // format — 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
4
- // (no model calls): the graph binary is spawned one-shot via `cli`, manifests
5
- // are parsed locally, and every write goes through the 4-gate pipeline with the
6
- // `trusted` flag (plugin-authored bookkeeping, not model claims). Degrades
7
- // gracefully when the binary or git is absent, so install-from-scratch still
8
- // writes script memories.
9
- import { join } from "node:path";
2
+ // Repository init: renders the runInit summary for the tool reply. The
3
+ // codebase-memory graph line is gone with the graph integration (#231).
10
4
  import { type InitSummary } from "./run.ts";
11
5
 
12
6
  export function formatInit(s: InitSummary): string {
@@ -16,7 +10,6 @@ export function formatInit(s: InitSummary): string {
16
10
  const scr = s.scripts.map((r) => `- ${r.source}: "${r.cmd}"`).join("\n");
17
11
  return [
18
12
  `Initialized ${s.scope} (root ${s.root}, head ${s.head}).`,
19
- `Graph: ${s.graph.action}${s.graph.name ? ` (${s.graph.name})` : ""} [mode=${s.graph.mode}]`,
20
13
  scr ? `Scripts (${s.scripts.length}):\n${scr}` : "Scripts: none detected",
21
14
  `Memories: written=${s.written}, collapsed=${s.collapsed}, blocked=${s.blocked}` +
22
15
  (s.unaudited ? `, ${s.unaudited} without an audit line` : "") +
package/src/init/run.ts CHANGED
@@ -1,12 +1,10 @@
1
1
  // run — split from src/init.ts (#168 domain restructure). Declaration bodies are unchanged.
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
5
- // (no model calls): the graph binary is spawned one-shot via `cli`, manifests
6
- // are parsed locally, and every write goes through the 4-gate pipeline with the
7
- // `trusted` flag (plugin-authored bookkeeping, not model claims). Degrades
8
- // gracefully when the binary or git is absent, so install-from-scratch still
9
- // writes script memories.
2
+ // Repository init: re-derive build/test command memories through the write gate
3
+ // and store an init stamp keyed on git HEAD. Deterministic (no model calls):
4
+ // manifests are parsed locally and every write goes through the 4-gate pipeline
5
+ // with the `trusted` flag (plugin-authored bookkeeping, not model claims).
6
+ // Degrades gracefully when git is absent, so install-from-scratch still writes
7
+ // script memories. The codebase-memory graph integration was removed (#231).
10
8
  import { basename } from "node:path";
11
9
  import { loadAll } from "../store/files/load.ts";
12
10
  import { markSuperseded } from "../store/files/supersede.ts";
@@ -19,13 +17,11 @@ import { runWriteGate, type GateContext } from "../gate/gate.ts";
19
17
  import { captureEvidenceContext, record } from "../evidence/record.ts";
20
18
  import { writeEvidence, hasGateCheck } from "../capture/triggers.ts";
21
19
  import { writeTarget } from "../identity/repokey.ts";
22
- import { graphEnabled } from "../core/config/paths.ts";
20
+ import { quarantineCandidate } from "../store/quarantine/quarantine.ts";
23
21
  import { getCurrent } from "../core/state.ts";
24
22
  import {
25
- type GraphStatus,
26
23
  type ScriptRecord,
27
24
  detectScripts,
28
- ensureGraph,
29
25
  gitHead,
30
26
  gitRootOf,
31
27
  } from "./detect.ts";
@@ -33,7 +29,6 @@ import {
33
29
  export interface InitArgs {
34
30
  liveRoot: string;
35
31
  force?: boolean;
36
- mode?: string;
37
32
  // The calling session (#127): rows this writes are stamped for the CALLER,
38
33
  // resolved after runInit's own awaits (git probing) rather than from the
39
34
  // ambient current, which a concurrent session may have moved.
@@ -44,7 +39,6 @@ export interface InitSummary {
44
39
  scope: string;
45
40
  root: string;
46
41
  head: string;
47
- graph: GraphStatus;
48
42
  scripts: ScriptRecord[];
49
43
  stampTs?: string;
50
44
  skipped: boolean;
@@ -55,23 +49,6 @@ export interface InitSummary {
55
49
  unaudited?: number;
56
50
  }
57
51
 
58
- export async function run(
59
- cmd: string[],
60
- cwd: string,
61
- ): Promise<{ ok: boolean; out: string }> {
62
- try {
63
- const p = Bun.spawn(cmd, { cwd, stdout: "pipe", stderr: "pipe" });
64
- const [so, se] = await Promise.all([
65
- new Response(p.stdout).text(),
66
- new Response(p.stderr).text(),
67
- ]);
68
- const code = await p.exited;
69
- return { ok: code === 0, out: (so || se || "").trim() };
70
- } catch {
71
- return { ok: false, out: "" };
72
- }
73
- }
74
-
75
52
  export interface InitStamp {
76
53
  ts: string;
77
54
  head: string;
@@ -107,7 +84,6 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
107
84
  const scope = basename(root) || basename(args.liveRoot);
108
85
  const head = await gitHead(root);
109
86
  const force = Boolean(args.force);
110
- const mode = args.mode ?? "moderate";
111
87
 
112
88
  const gateCtx: GateContext = {
113
89
  liveRoot: root,
@@ -135,11 +111,6 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
135
111
  scope,
136
112
  root,
137
113
  head,
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 },
143
114
  scripts: [],
144
115
  stampTs: prior.ts,
145
116
  skipped: true,
@@ -151,19 +122,12 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
151
122
 
152
123
  await record(
153
124
  "init_start",
154
- { scope, head, force, mode },
125
+ { scope, head, force },
155
126
  false,
156
127
  args.sessionID,
157
128
  evidenceContext,
158
129
  );
159
130
 
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 };
167
131
  const scripts = await detectScripts(root);
168
132
 
169
133
  let written = 0;
@@ -174,8 +138,18 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
174
138
  let unaudited = 0;
175
139
  for (const s of scripts) {
176
140
  const content = `${scope} ${s.key} command: run "${s.cmd}" from the repo root (${s.source}).`;
141
+ // Auto-capture and import both screen their candidate for injection-shaped
142
+ // text; init's rows are external text too — the scope is the checkout
143
+ // directory basename and the command comes from the manifest — so they get
144
+ // the same scan (#302). A match is still stored, tagged `quarantine`, and
145
+ // withheld from recall and injection.
177
146
  const outcome = await runWriteGate(
178
- { type: "pattern", scope, content, tags: ["init", s.source] },
147
+ quarantineCandidate({
148
+ type: "pattern",
149
+ scope,
150
+ content,
151
+ tags: ["init", s.source],
152
+ }),
179
153
  gateCtx,
180
154
  );
181
155
  if (outcome.action === "promoted") {
@@ -185,9 +159,17 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
185
159
  else blocked++;
186
160
  }
187
161
 
188
- const stampContent = `Init stamp: repo=${scope}, head=${head}, graph=${graph.action}, mode=${graph.mode}, scripts=${scripts.length}`;
162
+ const stampContent = `Init stamp: repo=${scope}, head=${head}, scripts=${scripts.length}`;
189
163
  const stampOutcome = await runWriteGate(
190
- { type: "context", scope, content: stampContent, tags: ["init-stamp"] },
164
+ // Same screen as the script rows: the stamp interpolates the directory
165
+ // basename, so an injection-shaped checkout name matches here too. Withheld
166
+ // from recall, still readable by initStamp(), so idempotency is unaffected.
167
+ quarantineCandidate({
168
+ type: "context",
169
+ scope,
170
+ content: stampContent,
171
+ tags: ["init-stamp"],
172
+ }),
191
173
  gateCtx,
192
174
  );
193
175
  const stampTs = stampOutcome.ts ?? prior?.ts;
@@ -209,8 +191,6 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
209
191
  scope,
210
192
  head,
211
193
  force,
212
- mode,
213
- graph: graph.action,
214
194
  scripts: scripts.length,
215
195
  written,
216
196
  collapsed,
@@ -227,7 +207,6 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
227
207
  scope,
228
208
  root,
229
209
  head,
230
- graph,
231
210
  scripts,
232
211
  stampTs,
233
212
  skipped: false,
@@ -166,15 +166,20 @@ export async function exportMemories(
166
166
  // stored before the write-side redaction existed (#74 slice 1). Redaction is
167
167
  // applied to the value being serialised, never to the row: export stays a
168
168
  // read path, and the store remains the byte-of-record for memory_undo.
169
+ // #300 extends the same rule to the metadata fields: `scope`, `tags` and `kw`
170
+ // are free prose a row can carry, and a legacy or hand-edited row can hold a
171
+ // credential in them even though new writes refuse it. `repo`/`repoPath` stay
172
+ // as stored — they are derived stamps, not prose, and rewriting them would
173
+ // break the import-side validation that keeps a portable file honest.
169
174
  const lines = mems.map((m) =>
170
175
  JSON.stringify({
171
176
  ts: m.ts,
172
177
  type: m.type,
173
- scope: m.scope,
178
+ scope: redactSecrets(m.scope),
174
179
  content: redactSecrets(m.content),
175
180
  status: m.status,
176
- tags: m.tags,
177
- kw: m.kw,
181
+ tags: m.tags?.map(redactSecrets),
182
+ kw: m.kw?.map(redactSecrets),
178
183
  issue: m.issue === undefined ? m.issue : redactSecrets(m.issue),
179
184
  // Origin stamps ride along so a same-repo machine hop can retain them.
180
185
  // Import validates them against its current repo before promotion.
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: 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.",
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).",
23
23
  options: direct,
24
24
  async execute(args, context): Promise<{ content: string }> {
25
25
  const { sid } = toolIds(context);
@@ -29,7 +29,6 @@ export const register: ToolRegister = (editor, deps) => {
29
29
  const summary = await runInit({
30
30
  liveRoot: gateContext(sid).liveRoot,
31
31
  force: args.force,
32
- mode: args.mode,
33
32
  sessionID: sid,
34
33
  });
35
34
  return { content: formatInit(summary) };
@@ -74,10 +74,6 @@ export const InitArgs = z.object({
74
74
  .boolean()
75
75
  .describe("Re-run even if initialized (refresh after drift)")
76
76
  .optional(),
77
- mode: z
78
- .enum(["fast", "moderate", "full"])
79
- .describe("codebase-memory index mode (default moderate)")
80
- .optional(),
81
77
  });
82
78
 
83
79
  export const RecallArgs = z.object({