opencode-self-improvement 0.14.10 → 0.14.12

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
@@ -72,6 +72,7 @@ Zero configuration is the default. To tune, use the object form of the plugin en
72
72
  | Variable | Purpose |
73
73
  | --- | --- |
74
74
  | `OPENCODE_MEMORY_DIR` | Store location (default `~/.config/opencode/memory`). |
75
+ | `OPENCODE_MEMORY_ALLOW_OUTSIDE_PATHS` | Operator-only. When truthy, `memory_export`/`memory_import` accept paths anywhere on disk instead of confining themselves to the store. Off by default. See [Export and move between machines](#export-and-move-between-machines). |
75
76
  | `OPENCODE_MEMORY_INJECT_BUDGET` | Fallback for `injectBudget`. |
76
77
  | `OPENCODE_MEMORY_FRONTIER_BUDGET` | Fallback for `frontierBudget`. |
77
78
  | `OPENCODE_COMMANDS_DIR` | Where the plugin mirrors its slash commands (default `~/.config/opencode/commands`). |
@@ -94,7 +95,7 @@ Nothing is deleted: `memory_update` supersedes the previous row, `memory_forget`
94
95
 
95
96
  Rows are stamped with your git origin (an id that survives re-clones and moves between machines) or, without an origin, a hash of the normalized directory path. `repoPath` keeps the human-readable path, so rows written before hashing keep matching.
96
97
 
97
- Injection, recall, the frontier block, compaction, `memory_forget` and decay only see the current repo plus global rows. Preferences that should follow you everywhere go in with `memory_remember global: true`. Rows written before scoping existed, and rows restored through the viewer, are global — upgrading changes nothing.
98
+ Injection, recall, the frontier block, compaction, `memory_forget` and decay only see the current repo plus global rows, resolved from the calling session's identity at flow entry. A session that reaches a plugin instance is bound to that instance's own workspace on first contact — in a process hosting several workspaces, one session never borrows the repository some other workspace's setup left behind. A session whose repository cannot be resolved at all sees global rows only; "unknown" is never "everything". Evidence lines carry the same stamp, so `memory_evidence` answers from the caller's repo plus global lines; a line a named session wrote while its repository was unresolvable is private to that session, and only an explicitly global (or predating-stamps) line reads as global. Preferences that should follow you everywhere go in with `memory_remember global: true`. Rows written before scoping existed are global, and the viewer (an admin surface over every repo) edits and restores a row with its own repo stamp — the viewer's missing session scope never decides a row's visibility. Upgrading changes nothing.
98
99
 
99
100
  ## Token cost and caching
100
101
 
@@ -184,7 +185,7 @@ On the eval dataset the pass takes 200 rows to 52 with **R@3 52 → 53 and R@1 5
184
185
 
185
186
  ## Secret redaction
186
187
 
187
- One best-effort credential rule set (`src/secrets.ts`) runs over the auto-capture prompt before it leaves the plugin, at the write gate before content is hashed or analysed, and again in the final write choke point used by gated writes and the viewer's edit and restore paths.
188
+ One best-effort credential rule set (`src/secrets.ts`) runs over the auto-capture prompt before it leaves the plugin, at the write gate before content is hashed or analysed, again in the final write choke point used by gated writes and the viewer's edit and restore paths, and at the durable audit boundaries — every evidence line, every supersede field written into a retired row, and every deletion-audit reason — so a recognized credential cannot persist in `evidence/` or `deletions.logfmt` or a tombstoned row regardless of which path carried it.
188
189
 
189
190
  Covered: OpenAI `sk-`, GitHub `ghp_` / `gho_` / `github_pat_`, Slack `xoxb-` / `xoxp-`, AWS `AKIA`, Google `AIza`, bearer tokens containing digits, PEM private-key blocks, and high-entropy values assigned to names ending in `_KEY`, `_TOKEN`, `_SECRET` or `_PASSWORD` (plus `password`).
190
191
 
@@ -197,14 +198,18 @@ Limits worth knowing:
197
198
 
198
199
  ## Export and move between machines
199
200
 
200
- `memory_export` writes the live store as JSONL: a machine-readable header line (`{_export, version, exportedAt, count}`) followed by one JSON object per line (`{ts,type,scope,content,status,tags,issue}`), active rows only. `memory_import` reads such a file back. Default path is `<memory-root>/exports/<timestamp>.jsonl`; pass `file` to choose one and `scope` to export a single scope.
201
+ `memory_export` writes the live store as JSONL: a machine-readable header line (`{_export, version, exportedAt, count}`) followed by one JSON object per line (`{ts,type,scope,content,status,tags,issue}`), active rows only. `memory_import` reads such a file back. Default path is `<memory-root>/exports/<timestamp>.jsonl`; `file` must name a path **inside the store** — exports under `<memory-root>/exports` (a relative path resolves against it), imports anywhere under `<memory-root>` — and `scope` exports a single scope.
202
+
203
+ Both tools are model-facing, so a path is not a privilege: an export cannot write to `~/.gitconfig` or anywhere else outside the store, and an import cannot read outside it. Symbolic links are resolved before the check — including an `exports/` directory that is itself a link — so a link cannot carry a request out of the store. Exports are written `0600` and opened `O_NOFOLLOW` (both POSIX; on Windows the check before the write is the only guard). (Hardlinks are beyond any path check: a link planted inside `exports/` shares an inode with its target. That, and a narrow window on intermediate path components, are the boundary's known limits.) To move a store between machines, copy the file in:
201
204
 
202
205
  ```
203
- Export my memories to ~/memories.jsonl # memory_export
204
- # …copy the file to the other machine…
205
- Import ~/memories.jsonl # memory_import
206
+ Export my memories # -> <memory-root>/exports/<stamp>.jsonl
207
+ # …copy that file to the other machine's <memory-root>/…
208
+ Import <memory-root>/memories.jsonl # memory_import
206
209
  ```
207
210
 
211
+ An operator running a one-off migration can restore the old anywhere-on-disk behavior with `OPENCODE_MEMORY_ALLOW_OUTSIDE_PATHS=1`. It is read from the plugin process's own environment, so a model cannot grant it to itself through a tool argument.
212
+
208
213
  Every imported row re-enters through the same four gates as `memory_remember` (tagged `import`, original tags preserved), and the tool reports a tally:
209
214
 
210
215
  | Outcome | Meaning |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.14.10",
3
+ "version": "0.14.12",
4
4
  "description": "Durable memory for opencode: remember facts, decisions, and commands across sessions, plus a one-command per-repo setup (/repo-init).",
5
5
  "main": "index.ts",
6
6
  "exports": {
package/src/config.ts CHANGED
@@ -29,6 +29,23 @@ export function snapshotDir(): string {
29
29
  return join(memoryRoot(), "snapshots");
30
30
  }
31
31
 
32
+ // The only place memory_export may write (src/containment.ts). An export is a
33
+ // copy of the live store, so it is store data and lives inside the store.
34
+ export function exportsDir(): string {
35
+ return join(memoryRoot(), "exports");
36
+ }
37
+
38
+ // Escape hatch for out-of-band migrations only: when truthy, memory_export and
39
+ // memory_import accept paths anywhere on the filesystem instead of confining
40
+ // themselves to the store. Read from the plugin process's own environment at
41
+ // call time, so a model cannot grant it to itself through a tool argument; the
42
+ // default is closed. See src/containment.ts.
43
+ export function allowOutsideStorePaths(): boolean {
44
+ const raw = process.env.OPENCODE_MEMORY_ALLOW_OUTSIDE_PATHS;
45
+ if (!raw) return false;
46
+ return /^(1|true|yes|on)$/i.test(raw.trim());
47
+ }
48
+
32
49
  export function canonicalFile(): string {
33
50
  return join(memoryRoot(), "canonical.logfmt");
34
51
  }
@@ -0,0 +1,208 @@
1
+ // Containment for caller-supplied filesystem paths.
2
+ //
3
+ // Every path a model can name is attacker-selectable text: memory_export's
4
+ // `file` (an arbitrary WRITE) and memory_import's `file` (an arbitrary READ).
5
+ // The rule: resolve the request against a root the plugin chose, then re-check
6
+ // the REAL path so a symbolic link anywhere along the request cannot carry it
7
+ // outside. Both checks run before any read or write, and every rejection uses
8
+ // one neutral wording — an existence oracle for the filesystem around the store
9
+ // is still a leak.
10
+ //
11
+ // src/undo.ts's snapshot restore enforces the same two-level boundary (inside
12
+ // snapshots/, and inside the memory root) with its own name grammar; it is not
13
+ // the same code path as this one and does not share its ancestor walk.
14
+ //
15
+ // Residual limits, stated rather than papered over:
16
+ // - Checking and writing are separate syscalls. The FINAL component is
17
+ // protected at open time by O_NOFOLLOW (see writeExport in portable.ts),
18
+ // which closes the classic swap-a-link-over-redirect attack. An INTERMEDIATE
19
+ // component swapped for a link inside the window is not caught; closing that
20
+ // needs openat-relative traversal, which neither node:fs nor Bun exposes.
21
+ // - Hardlinks are invisible to path containment: a link someone else plants
22
+ // inside exports/ shares an inode with its target and a write through it
23
+ // truncates that target. Containment cannot see this; it needs an owner or
24
+ // device policy, not a path check.
25
+ import { lstat, realpath } from "node:fs/promises";
26
+ import { homedir } from "node:os";
27
+ import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";
28
+
29
+ // True when `child` is `parent` itself or lives beneath it. Both must already
30
+ // be absolute and lexically normalised (resolve()).
31
+ export function isWithin(parent: string, child: string): boolean {
32
+ const rel = relative(parent, child);
33
+ return rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
34
+ }
35
+
36
+ function isNotFound(err: unknown): boolean {
37
+ return err instanceof Error && "code" in err && err.code === "ENOENT";
38
+ }
39
+
40
+ // `~` is shell syntax, not path syntax: nothing expands it here, so
41
+ // `~/.gitconfig` is an ordinary RELATIVE component and lands in a directory
42
+ // literally named "~" wherever the host process happens to be running. Expand
43
+ // the two forms a caller plausibly means, so they are judged for what they
44
+ // point at (and rejected); any other leading `~` (a `~user` form we cannot
45
+ // resolve portably) is refused outright rather than creating junk.
46
+ export function expandHome(requested: string): string {
47
+ if (requested === "~") return resolve(homedir());
48
+ if (requested.startsWith("~/") || requested.startsWith(`~${sep}`)) {
49
+ return resolve(homedir(), requested.slice(2));
50
+ }
51
+ return requested;
52
+ }
53
+
54
+ // C0/C1 controls — including NUL, which truncates a path at the syscall layer.
55
+ // (src/sanitize.ts flattens a wider set, \p{Zl} and \p{Zp} included, because it
56
+ // guards rendered line structure; a path only has to be unrepresentable here.)
57
+ const CONTROL_CHARS = /\p{Cc}/u;
58
+
59
+ function normalize(requested: string, reject: (why: string) => string): string {
60
+ // Trim first, then look for control characters. The order matters twice over:
61
+ // a model that emits "x.jsonl\n" gets a working export rather than a refusal
62
+ // about control characters, and nothing dangerous is lost by trimming, because
63
+ // trim() removes only whitespace — NUL and the non-whitespace C1 controls that
64
+ // actually truncate or confuse a path survive it and are still caught here.
65
+ const trimmed = requested.trim();
66
+ if (!trimmed) throw new Error(reject("must not be empty"));
67
+ if (CONTROL_CHARS.test(trimmed)) throw new Error(reject("must not contain control characters"));
68
+ const expanded = expandHome(trimmed);
69
+ if (expanded === trimmed && expanded.split(/[/\\]/)[0]?.startsWith("~")) {
70
+ throw new Error(reject("must not use a `~` home path"));
71
+ }
72
+ return expanded;
73
+ }
74
+
75
+ // realpath() the nearest EXISTING ancestor and re-join the missing remainder:
76
+ // realpath() on the full path simply fails on an export destination that does
77
+ // not exist yet, and falling back to the lexical path there would skip the
78
+ // check for exactly the case an attacker picks.
79
+ //
80
+ // Every non-ENOENT filesystem failure (ENOTDIR, ELOOP, ENAMETOOLONG, EACCES)
81
+ // becomes the same neutral rejection. Letting them through verbatim is both an
82
+ // existence oracle — ENOTDIR on `<root>/status.json/x` proves status.json is
83
+ // there — and a raw Bun error in a model-facing tool result.
84
+ async function realAncestor(path: string, reject: (why: string) => string): Promise<string> {
85
+ const missing: string[] = [];
86
+ let cursor = path;
87
+ for (;;) {
88
+ try {
89
+ await lstat(cursor);
90
+ break;
91
+ } catch (err) {
92
+ if (!isNotFound(err)) throw new Error(reject("could not be resolved"));
93
+ const parent = dirname(cursor);
94
+ if (parent === cursor) throw new Error(reject("could not be resolved"));
95
+ missing.unshift(basename(cursor));
96
+ cursor = parent;
97
+ }
98
+ }
99
+ try {
100
+ return resolve(await realpath(cursor), ...missing);
101
+ } catch {
102
+ throw new Error(reject("could not be resolved"));
103
+ }
104
+ }
105
+
106
+ export interface ContainOptions {
107
+ /** Names the caller in the error ("memory_export file"). */
108
+ label: string;
109
+ /** Appended to every rejection: where the caller may go instead. */
110
+ hint?: string;
111
+ /**
112
+ * A second, wider root that `rootDir` itself must not reach through a link.
113
+ * Export passes the memory root: an `exports/` that is a symlink elsewhere
114
+ * would otherwise satisfy every check against its own realpath and still
115
+ * write outside the store.
116
+ */
117
+ outerRoot?: string;
118
+ /**
119
+ * Skip containment (the `OPENCODE_MEMORY_ALLOW_OUTSIDE_PATHS` escape hatch
120
+ * for out-of-band migrations). Input hygiene still applies.
121
+ */
122
+ allowOutside?: boolean;
123
+ }
124
+
125
+ /**
126
+ * Resolve `requested` inside `rootDir`.
127
+ *
128
+ * - A relative request resolves against `rootDir`, NOT the host process's cwd.
129
+ * - The lexical request must stay inside `rootDir`, and must not BE `rootDir`:
130
+ * accepting the root itself would let `.` create a regular file named
131
+ * `exports` and disable every later export.
132
+ * - Existing components are resolved for real, so a link inside the root cannot
133
+ * step outside it: the re-joined real path must stay inside the REAL root (the
134
+ * root itself may legitimately be reached through a link, e.g. macOS /tmp),
135
+ * and inside `outerRoot` when one is given.
136
+ * - The final component may not exist yet. If it exists it must be a regular
137
+ * file — never a symbolic link, never a directory.
138
+ *
139
+ * Returns the LEXICAL path (home-expanded), the convention undo.ts's restore
140
+ * already follows: checks run on real paths, the write goes through the path
141
+ * every other caller sees, so a store reached through a link keeps reporting
142
+ * the location its caller named.
143
+ */
144
+ export async function resolveContained(
145
+ requested: string,
146
+ rootDir: string,
147
+ opts: ContainOptions,
148
+ ): Promise<string> {
149
+ const { label } = opts;
150
+ const reject = (why: string) => `${label} ${why}${opts.hint ? ` — ${opts.hint}` : ""}`;
151
+ const clean = normalize(requested, reject);
152
+ // Escape hatch: still no control characters, no `~` smuggling, but the caller
153
+ // owns the destination and a relative path means what it always meant here —
154
+ // relative to the host process's cwd.
155
+ if (opts.allowOutside) return resolve(clean);
156
+
157
+ const rootAbs = resolve(rootDir);
158
+ const reqAbs = resolve(rootAbs, clean);
159
+ if (relative(rootAbs, reqAbs) === "") {
160
+ throw new Error(reject("must name a file inside the root, not the root itself"));
161
+ }
162
+ if (!isWithin(rootAbs, reqAbs)) {
163
+ throw new Error(reject(`must stay inside ${rootAbs} (got "${requested}")`));
164
+ }
165
+
166
+ // The root is resolved and validated FIRST, deliberately: with exports/ a
167
+ // regular file, realAncestor() on the REQUEST fails ENOTDIR, and collapsing
168
+ // that into the neutral wording would hide the one failure the caller can
169
+ // actually fix — and the hint would send them to a default that fails the
170
+ // same way. A root that exists as a non-directory is a broken store, not an
171
+ // attacker's choice, so it gets a named cause.
172
+ const realRoot = await realAncestor(rootAbs, reject);
173
+ let rootInfo: Awaited<ReturnType<typeof lstat>> | undefined;
174
+ try {
175
+ rootInfo = await lstat(realRoot);
176
+ } catch (err) {
177
+ if (!isNotFound(err)) throw new Error(reject("could not be resolved"));
178
+ }
179
+ if (rootInfo && !rootInfo.isDirectory()) {
180
+ throw new Error(reject(`is not a directory: ${realRoot}`));
181
+ }
182
+
183
+ const realReq = await realAncestor(reqAbs, reject);
184
+ if (!isWithin(realRoot, realReq)) {
185
+ throw new Error(reject(`escapes ${rootAbs} through a symbolic link (got "${requested}")`));
186
+ }
187
+ if (opts.outerRoot) {
188
+ const realOuter = await realAncestor(resolve(opts.outerRoot), reject);
189
+ if (!isWithin(realOuter, realReq)) {
190
+ throw new Error(reject(`escapes the store root ${realOuter} (got "${requested}")`));
191
+ }
192
+ }
193
+
194
+ // Checked on the LEXICAL path: realAncestor() already followed a
195
+ // final-component link, so only lstat() here can still see that it was one.
196
+ // (A stat() here would pass an in-root link to an in-root file.)
197
+ let finalInfo: Awaited<ReturnType<typeof lstat>> | undefined;
198
+ try {
199
+ finalInfo = await lstat(reqAbs);
200
+ } catch (err) {
201
+ if (!isNotFound(err)) throw new Error(reject("could not be resolved"));
202
+ }
203
+ if (finalInfo) {
204
+ if (finalInfo.isSymbolicLink()) throw new Error(reject("must not be a symbolic link"));
205
+ if (!finalInfo.isFile()) throw new Error(reject("is not a regular file"));
206
+ }
207
+ return reqAbs;
208
+ }
package/src/evidence.ts CHANGED
@@ -5,10 +5,25 @@ import { join } from "node:path";
5
5
  import { createHash } from "node:crypto";
6
6
  import { dateStr, evidenceDir } from "./config.ts";
7
7
  import { appendLog, formatLine } from "./logfmt.ts";
8
+ import { repoScope, sessionScope } from "./repokey.ts";
8
9
  import { getCurrent } from "./state.ts";
10
+ import { redactSecrets } from "./secrets.ts";
9
11
 
10
12
  export type EvidenceEvent = string;
11
13
 
14
+ // Credential scrub at the evidence WRITE boundary. Evidence fields routinely
15
+ // carry caller-authored prose (gate reasons, block reasons, review notes) and
16
+ // tool-derived summaries; a recognized credential must not persist in the
17
+ // durable log no matter which line carried it (#128). redactSecrets is a
18
+ // no-op on ordinary text (ids, hashes, paths, counts).
19
+ function scrubFields(fields: Record<string, unknown>): Record<string, unknown> {
20
+ const out: Record<string, unknown> = {};
21
+ for (const [key, value] of Object.entries(fields)) {
22
+ out[key] = typeof value === "string" ? redactSecrets(value) : value;
23
+ }
24
+ return out;
25
+ }
26
+
12
27
  export async function record(
13
28
  ev: EvidenceEvent,
14
29
  fields: Record<string, unknown> = {},
@@ -25,11 +40,26 @@ export async function record(
25
40
  // this is exactly the old ambient read.
26
41
  const sid = sessionID ?? cur.sid;
27
42
  const call = sessionID !== undefined && sessionID !== cur.sid ? undefined : cur.call;
43
+ // Read-side partitioning of the shared log (#131's rule, applied to
44
+ // evidence; the re-review closed the last two gaps in it). A NAMED session
45
+ // is stamped from its OWN resolved scope only — the module scope is never
46
+ // the fallback here: in a process that loaded several plugin instances it
47
+ // belongs to whoever set up LAST, and A's evidence must not live in B's
48
+ // repository. A named session whose repository is unresolvable writes an
49
+ // UNSTAMPED line that stays private to that session (memory.ts
50
+ // evidenceVisibleTo pairs with this choice): "unknown" is never
51
+ // "everything" (#127), and it is never somebody else's repo either. Only a
52
+ // genuinely session-less line — out-of-plugin maintenance, viewer, CLI —
53
+ // takes the process scope, and unstamped session-less lines (legacy, or a
54
+ // scope-less process) keep their historical global reading.
55
+ const named = typeof sid === "string" && sid !== "" && sid !== "?";
56
+ const scope = named ? sessionScope(sid) : repoScope();
28
57
  const line = formatLine({
29
58
  ev,
30
59
  ts: new Date().toISOString(),
31
60
  ...(includeContext ? { sid, call } : {}),
32
- ...fields,
61
+ ...(scope ? { repo: scope.key, repoPath: scope.path } : {}),
62
+ ...scrubFields(fields),
33
63
  });
34
64
  await appendLog(join(evidenceDir(), `${dateStr()}.logfmt`), line);
35
65
  }
package/src/gates.ts CHANGED
@@ -17,6 +17,7 @@ import {
17
17
  import { chainId, contentHash, record, recordWriteBlocked } from "./evidence.ts";
18
18
  import { flattenMemoryText } from "./sanitize.ts";
19
19
  import { containsSecret, redactSecrets } from "./secrets.ts";
20
+ import { readerForSession } from "./memory.ts";
20
21
  import {
21
22
  displayCall,
22
23
  extractCallForms,
@@ -328,7 +329,18 @@ export async function runWriteGate(
328
329
  ch,
329
330
  });
330
331
 
331
- const scopeMems = candidate.scope ? await loadScope(candidate.scope) : [];
332
+ const scopeMems = candidate.scope
333
+ ? await loadScope(
334
+ candidate.scope,
335
+ // Dedup/stale reads partition on the WRITE's session, captured at
336
+ // flow entry — not the ambient current after this await (#127). An
337
+ // unknown "?" (or absent) caller is the readerFromSid AMBIENT case,
338
+ // exactly as before: readerForSession is for named sessions only.
339
+ ctx.sessionID !== undefined && ctx.sessionID !== "?"
340
+ ? readerForSession(ctx.sessionID)
341
+ : undefined,
342
+ )
343
+ : [];
332
344
  // One tree index per write, shared by gate1 and every gate2 stale scan.
333
345
  const tree = memoTree(ctx.liveRoot);
334
346