opencode-self-improvement 0.14.9 → 0.14.11
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 +10 -4
- package/package.json +1 -1
- package/src/config.ts +17 -0
- package/src/containment.ts +208 -0
- package/src/index.ts +102 -6
- package/src/portable.ts +98 -7
- package/src/schema.ts +7 -2
- package/src/undo.ts +4 -6
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`). |
|
|
@@ -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`;
|
|
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
|
|
204
|
-
# …copy
|
|
205
|
-
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 |
|
|
@@ -293,5 +298,6 @@ bun run gate:hooks # once per clone: run the gate on `git push`
|
|
|
293
298
|
| `/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. |
|
|
294
299
|
| 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. |
|
|
295
300
|
| Stale plugin after an update | `opencode plugin update opencode-self-improvement` (or bump the pinned `@version` in the `plugins` entry) and restart opencode. |
|
|
301
|
+
| `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. |
|
|
296
302
|
| Auto-capture does nothing | `autoCapture` needs a valid `captureModel` in `provider/id` form; a bad one disables capture with a startup warning. `captureOnCompact` alone does nothing. Rejected candidates are logged as evidence, not errors — check `memory_evidence`. |
|
|
297
303
|
| Reset all memories | Delete `~/.config/opencode/memory/`. |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-self-improvement",
|
|
3
|
-
"version": "0.14.
|
|
3
|
+
"version": "0.14.11",
|
|
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/index.ts
CHANGED
|
@@ -225,6 +225,48 @@ export function resetCaptureCooldowns(): void {
|
|
|
225
225
|
lastCaptureRun.clear();
|
|
226
226
|
}
|
|
227
227
|
|
|
228
|
+
// ---- capture trigger vocabulary (#136) -------------------------------------
|
|
229
|
+
// opencode 2.x has no `session.idle`. The subscription used to wait for exactly
|
|
230
|
+
// that string, so auto-capture was dead on every 2.x host with no warning
|
|
231
|
+
// anywhere: live proof is in the issue (45 s of the running service's own SSE
|
|
232
|
+
// stream over a complete turn, and zero `capture_lag` lines in the whole
|
|
233
|
+
// evidence history). What the host really publishes when a turn ends is the
|
|
234
|
+
// `session.execution.*` family; `session.status` is the ephemeral variant whose
|
|
235
|
+
// `status.type` says "idle".
|
|
236
|
+
//
|
|
237
|
+
// These lists are the single source of truth for what the capture subscription
|
|
238
|
+
// reacts to, and test/event-fidelity.test.ts asserts every name here appears in
|
|
239
|
+
// the installed @opencode/schema event manifest. Invented event names are the
|
|
240
|
+
// bug class that caused #78 and then survived a review, a merge and 480 green
|
|
241
|
+
// tests, because the tests fabricated the same invented payload.
|
|
242
|
+
// Recorded live, not guessed: `succeeded` and `interrupted` were both observed
|
|
243
|
+
// on a running desktop service (test/fixtures/host-events.jsonl).
|
|
244
|
+
export const TURN_END_EVENTS = ["session.execution.succeeded", "session.execution.interrupted"] as const;
|
|
245
|
+
|
|
246
|
+
/** Every event type the capture subscription reacts to (fidelity-tested). */
|
|
247
|
+
export const CAPTURE_EVENT_TYPES: readonly string[] = [...TURN_END_EVENTS];
|
|
248
|
+
|
|
249
|
+
// Deliberately NOT triggers, because a live host was never observed sending
|
|
250
|
+
// them, and dead branches are what caused #136 in the first place:
|
|
251
|
+
// • `session.idle` - declared, never emitted (the original bug).
|
|
252
|
+
// • `session.status` - declared, never emitted; would also need
|
|
253
|
+
// `data.status.type === "idle"` filtering.
|
|
254
|
+
// • `session.execution.failed` - declared, not reproduced here. A failed turn
|
|
255
|
+
// simply does not capture, which costs nothing; adding it
|
|
256
|
+
// later is allowed the moment a recording shows it.
|
|
257
|
+
// test/event-fidelity.test.ts enforces that nothing enters TURN_END_EVENTS
|
|
258
|
+
// without appearing in the recording.
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* True when a host event means "this session just went quiet". The internal
|
|
262
|
+
* trigger name stays "idle" (cooldown keys, `auto_capture_*` evidence lines and
|
|
263
|
+
* the historical idle-vs-compaction bench all use it).
|
|
264
|
+
*/
|
|
265
|
+
export function captureTriggerFor(event: unknown): boolean {
|
|
266
|
+
const type = (event as { type?: unknown } | null)?.type;
|
|
267
|
+
return typeof type === "string" && (TURN_END_EVENTS as readonly string[]).includes(type);
|
|
268
|
+
}
|
|
269
|
+
|
|
228
270
|
// The real setup implementation, written against the loose local PluginCtx
|
|
229
271
|
// (the only members of the V2 context this plugin actually touches).
|
|
230
272
|
const impl = {
|
|
@@ -674,18 +716,24 @@ const impl = {
|
|
|
674
716
|
editor.add(validated(ExportArgs, {
|
|
675
717
|
name: "memory_export",
|
|
676
718
|
description:
|
|
677
|
-
"Export active memories as a JSONL file for backup or transfer to another machine. The first line is a metadata header ({_export,version,exportedAt,count}); each later line is one JSON object {ts,type,scope,content,status,tags,issue}. The header is what lets memory_import keep repo-scoped status:\"open\" frontier rows — a hand-written file without it imports such rows as settled, as does an imported open row claiming repo:\"global\". Defaults to <memory-root>/exports/<timestamp>.jsonl;
|
|
719
|
+
"Export active memories as a JSONL file for backup or transfer to another machine. The first line is a metadata header ({_export,version,exportedAt,count}); each later line is one JSON object {ts,type,scope,content,status,tags,issue}. The header is what lets memory_import keep repo-scoped status:\"open\" frontier rows — a hand-written file without it imports such rows as settled, as does an imported open row claiming repo:\"global\". Defaults to <memory-root>/exports/<timestamp>.jsonl; `file` must name a path inside <memory-root>/exports (a relative path resolves against it), `scope` exports one scope. Superseded rows are not exported (history stays in the store).",
|
|
678
720
|
options: direct,
|
|
679
721
|
async execute(args): Promise<{ content: string }> {
|
|
680
|
-
|
|
681
|
-
|
|
722
|
+
try {
|
|
723
|
+
const res = await exportMemories({ scope: args.scope, file: args.file });
|
|
724
|
+
return { content: `Exported ${res.count} memories -> ${res.path}` };
|
|
725
|
+
} catch (err) {
|
|
726
|
+
return {
|
|
727
|
+
content: `memory_export failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
728
|
+
};
|
|
729
|
+
}
|
|
682
730
|
},
|
|
683
731
|
}));
|
|
684
732
|
|
|
685
733
|
editor.add(validated(ImportArgs, {
|
|
686
734
|
name: "memory_import",
|
|
687
735
|
description:
|
|
688
|
-
"Import memories from a JSONL export (see memory_export). Every row goes through the same 4-gate write pipeline as memory_remember (tagged `import`, original tags preserved), so duplicates collapse and ungrounded rows are blocked exactly as usual — those are normal tallied outcomes, not errors. Malformed lines are skipped and counted. Frontier policy: status:\"open\" exempts a row from ref grounding, so it requires a memory_export header and cannot claim global scope; imported repo stamps are kept only when they match the importing session's repo, otherwise the importing repo is stamped. A stamped open row is downgraded when there is no current repo scope to verify it. Imported content is unverified by construction: injected rows surface a `[via import]` provenance marker.",
|
|
736
|
+
"Import memories from a JSONL export (see memory_export). Every row goes through the same 4-gate write pipeline as memory_remember (tagged `import`, original tags preserved), so duplicates collapse and ungrounded rows are blocked exactly as usual — those are normal tallied outcomes, not errors. Malformed lines are skipped and counted. `file` must be inside the memory root — copy the export there first. Frontier policy: status:\"open\" exempts a row from ref grounding, so it requires a memory_export header and cannot claim global scope; imported repo stamps are kept only when they match the importing session's repo, otherwise the importing repo is stamped. A stamped open row is downgraded when there is no current repo scope to verify it. Imported content is unverified by construction: injected rows surface a `[via import]` provenance marker.",
|
|
689
737
|
options: direct,
|
|
690
738
|
async execute(args): Promise<{ content: string }> {
|
|
691
739
|
try {
|
|
@@ -1238,8 +1286,10 @@ const impl = {
|
|
|
1238
1286
|
try {
|
|
1239
1287
|
for await (const raw of eventApi.subscribe({ signal: controller.signal })) {
|
|
1240
1288
|
const event = raw as Record<string, any>;
|
|
1241
|
-
if (event
|
|
1242
|
-
|
|
1289
|
+
if (!captureTriggerFor(event)) continue;
|
|
1290
|
+
// 2.x carries the session inside `data`; the other two shapes are
|
|
1291
|
+
// kept because the measured listener sees both across host modes.
|
|
1292
|
+
const sid = event.data?.sessionID ?? event.sessionID ?? event.properties?.sessionID;
|
|
1243
1293
|
if (typeof sid !== "string") continue;
|
|
1244
1294
|
setCurrent({ sessionID: sid });
|
|
1245
1295
|
const now = Date.now();
|
|
@@ -1279,6 +1329,52 @@ const impl = {
|
|
|
1279
1329
|
"[opencode-self-improvement] captureOnCompact is on but autoCapture is off; compaction capture stays disabled (autoCapture is the master switch).",
|
|
1280
1330
|
);
|
|
1281
1331
|
}
|
|
1332
|
+
// ---- startup heartbeat (#138) ------------------------------------------
|
|
1333
|
+
// Every other evidence line is written BY something that already worked,
|
|
1334
|
+
// so "capture is off", "capture is misconfigured" and "capture is armed and
|
|
1335
|
+
// inert" were indistinguishable from anything a user could read - which is
|
|
1336
|
+
// exactly how a pipeline that had never run in ten days survived a review
|
|
1337
|
+
// and a merge. This one line makes the ABSENCE of capture activity
|
|
1338
|
+
// interpretable: `capture=` names why, `subscribed=` lists the event types
|
|
1339
|
+
// the subscription actually reacts to. Guarded like every other hook: a
|
|
1340
|
+
// broken store must not turn plugin load into a throw.
|
|
1341
|
+
await guarded("plugin_load heartbeat", async () => {
|
|
1342
|
+
let pluginVersion = "unknown";
|
|
1343
|
+
try {
|
|
1344
|
+
const pkg = await Bun.file(new URL("../package.json", import.meta.url)).json();
|
|
1345
|
+
if (typeof pkg?.version === "string") pluginVersion = pkg.version;
|
|
1346
|
+
} catch {
|
|
1347
|
+
// a heartbeat with an unknown version still beats no heartbeat
|
|
1348
|
+
}
|
|
1349
|
+
const wantCapture = ctx.options?.autoCapture === true;
|
|
1350
|
+
const modelOk = !!parseModelRef(
|
|
1351
|
+
typeof ctx.options?.captureModel === "string" ? ctx.options.captureModel : "",
|
|
1352
|
+
);
|
|
1353
|
+
const capabilities = ["event.subscribe", "generate.text", "session.context"].filter((name) => {
|
|
1354
|
+
const [domain, method] = name.split(".");
|
|
1355
|
+
return typeof (ctx as unknown as Record<string, any>)?.[domain]?.[method] === "function";
|
|
1356
|
+
});
|
|
1357
|
+
const captureState = !wantCapture
|
|
1358
|
+
? "off"
|
|
1359
|
+
: !modelOk
|
|
1360
|
+
? "invalid_model"
|
|
1361
|
+
: capabilities.length < 3
|
|
1362
|
+
? "no_capabilities"
|
|
1363
|
+
: "on";
|
|
1364
|
+
await record(
|
|
1365
|
+
"plugin_load",
|
|
1366
|
+
{
|
|
1367
|
+
version: pluginVersion,
|
|
1368
|
+
capture: captureState,
|
|
1369
|
+
capture_on_compact: ctx.options?.captureOnCompact !== false,
|
|
1370
|
+
capabilities: `[${capabilities.join(",")}]`,
|
|
1371
|
+
subscribed: `[${CAPTURE_EVENT_TYPES.join(",")}]`,
|
|
1372
|
+
inject_budget: injectBudget(),
|
|
1373
|
+
store_rows: (await loadAll()).length,
|
|
1374
|
+
},
|
|
1375
|
+
false,
|
|
1376
|
+
);
|
|
1377
|
+
});
|
|
1282
1378
|
// Single cleanup returned by setup: tears down the measured listener and,
|
|
1283
1379
|
// when enabled, the capture subscription. Future teardowns merge in here.
|
|
1284
1380
|
return () => {
|
package/src/portable.ts
CHANGED
|
@@ -3,8 +3,11 @@
|
|
|
3
3
|
// row flows through the caller-provided gate callback (index.ts wires it to
|
|
4
4
|
// runWriteGate), so moving memories between machines cannot bypass the 4-gate
|
|
5
5
|
// moat. Decay is supersede-not-delete and snapshot-first, mirroring prune.
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
6
|
+
import { constants } from "node:fs";
|
|
7
|
+
import { mkdir, open } from "node:fs/promises";
|
|
8
|
+
import { dirname, join } from "node:path";
|
|
9
|
+
import { allowOutsideStorePaths, exportsDir, memoryRoot } from "./config.ts";
|
|
10
|
+
import { resolveContained } from "./containment.ts";
|
|
8
11
|
import { isActive, isVisibleHere, loadAll, type Memory } from "./memory.ts";
|
|
9
12
|
import { repoScopeFor } from "./repokey.ts";
|
|
10
13
|
import { getCurrent } from "./state.ts";
|
|
@@ -27,7 +30,10 @@ export const EXPORT_VERSION = 1;
|
|
|
27
30
|
export interface ExportOptions {
|
|
28
31
|
/** Only export rows from this exact scope. */
|
|
29
32
|
scope?: string;
|
|
30
|
-
/**
|
|
33
|
+
/**
|
|
34
|
+
* Destination, confined to <memory-root>/exports/ (see containment.ts).
|
|
35
|
+
* Defaults to <memory-root>/exports/<stamp>.jsonl.
|
|
36
|
+
*/
|
|
31
37
|
file?: string;
|
|
32
38
|
}
|
|
33
39
|
|
|
@@ -41,15 +47,73 @@ function stamp(d: Date = new Date()): string {
|
|
|
41
47
|
return d.toISOString().slice(0, 19).replace(/:/g, "");
|
|
42
48
|
}
|
|
43
49
|
|
|
50
|
+
// An export is a full copy of the live store, so it may only be written inside
|
|
51
|
+
// the store's own exports/ directory: ~/.gitconfig, a relative path landing in
|
|
52
|
+
// the host process's cwd, ../.., and links out of the root are all rejected.
|
|
53
|
+
// Only an absent `file` means the default — an empty or whitespace-only one is
|
|
54
|
+
// a caller bug and fails rather than silently redirecting.
|
|
55
|
+
async function resolveExportTarget(file: string | undefined): Promise<string> {
|
|
56
|
+
const allowOutside = allowOutsideStorePaths();
|
|
57
|
+
const opts = {
|
|
58
|
+
label: "memory_export file",
|
|
59
|
+
hint: `omit file for the default, or name a path under ${exportsDir()}`,
|
|
60
|
+
// An exports/ that is itself a symlink must not move the write out of the
|
|
61
|
+
// store either — same two-level check undo.ts's restore makes.
|
|
62
|
+
outerRoot: memoryRoot(),
|
|
63
|
+
allowOutside,
|
|
64
|
+
};
|
|
65
|
+
// A default destination is still a destination. Routing it through the same
|
|
66
|
+
// check is what stops an exports/ that is a link from writing the whole store
|
|
67
|
+
// copy outside the store on the argument-free call — the one a model reaches
|
|
68
|
+
// without knowing anything about the layout. Under the operator escape hatch
|
|
69
|
+
// there is nothing to check, so the plain join is what remains.
|
|
70
|
+
if (file === undefined && allowOutside) return join(exportsDir(), `${stamp()}.jsonl`);
|
|
71
|
+
return resolveContained(file ?? `${stamp()}.jsonl`, exportsDir(), opts);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// An export is a plaintext copy of the whole store, so it is written 0600 and
|
|
75
|
+
// opened O_NOFOLLOW. The flag matters: the containment check and this open are
|
|
76
|
+
// separate syscalls, and the gap is the entire store read — single-digit to tens
|
|
77
|
+
// of milliseconds on a 5 000-row store depending on the machine, which is long
|
|
78
|
+
// enough for anything that can create a link inside exports/.
|
|
79
|
+
//
|
|
80
|
+
// Both are POSIX guarantees. libuv does not implement O_NOFOLLOW on Windows
|
|
81
|
+
// (verified on the CI windows leg: the open follows the link) and Windows
|
|
82
|
+
// reports every writable file as 0666, so there the containment check that ran
|
|
83
|
+
// before this call is the only protection.
|
|
84
|
+
//
|
|
85
|
+
// Exported so the flag itself can be pinned: the containment layer refuses an
|
|
86
|
+
// existing link long before this runs, so the only way to test O_NOFOLLOW
|
|
87
|
+
// without racing is to call the writer directly.
|
|
88
|
+
export async function writeExport(path: string, text: string): Promise<void> {
|
|
89
|
+
await mkdir(dirname(path), { recursive: true });
|
|
90
|
+
const flags =
|
|
91
|
+
constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | (constants.O_NOFOLLOW ?? 0);
|
|
92
|
+
const handle = await open(path, flags, 0o600);
|
|
93
|
+
try {
|
|
94
|
+
await handle.writeFile(text, "utf8");
|
|
95
|
+
// open()'s mode applies only when the file is created, so re-exporting over
|
|
96
|
+
// a file that already existed (a 0644 one, say) would otherwise leave it
|
|
97
|
+
// world-readable and make the 0600 above a claim rather than a guarantee.
|
|
98
|
+
await handle.chmod(0o600);
|
|
99
|
+
} finally {
|
|
100
|
+
await handle.close();
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
44
104
|
// Write the ACTIVE store as JSONL — a header line followed by one JSON object
|
|
45
105
|
// per line carrying {ts,type,scope,content,status,tags,issue}. Superseded rows
|
|
46
106
|
// are not exported: the export is the live store, and history stays auditable
|
|
47
107
|
// where it lives (the original logfmt files + snapshots). The header is always
|
|
48
108
|
// written, even for an empty store, so "has header" is a format invariant.
|
|
109
|
+
//
|
|
110
|
+
// The destination is model-supplied, so it is resolved and confined BEFORE the
|
|
111
|
+
// store is read: a rejected export must not leave a file behind, and must not
|
|
112
|
+
// be a way to learn how many rows matched either.
|
|
49
113
|
export async function exportMemories(opts: ExportOptions = {}): Promise<ExportResult> {
|
|
114
|
+
const path = await resolveExportTarget(opts.file);
|
|
50
115
|
let mems = (await loadAll()).filter(isActive);
|
|
51
116
|
if (opts.scope) mems = mems.filter((m) => m.scope === opts.scope);
|
|
52
|
-
const path = opts.file ?? join(memoryRoot(), "exports", `${stamp()}.jsonl`);
|
|
53
117
|
const header = JSON.stringify({
|
|
54
118
|
_export: EXPORT_HEADER,
|
|
55
119
|
version: EXPORT_VERSION,
|
|
@@ -72,7 +136,16 @@ export async function exportMemories(opts: ExportOptions = {}): Promise<ExportRe
|
|
|
72
136
|
repoPath: m.repoPath,
|
|
73
137
|
}),
|
|
74
138
|
);
|
|
75
|
-
|
|
139
|
+
try {
|
|
140
|
+
await writeExport(path, `${[header, ...lines].join("\n")}\n`);
|
|
141
|
+
} catch (err) {
|
|
142
|
+
// Past containment, so this is not an existence oracle: `path` is one the
|
|
143
|
+
// plugin chose or already validated. The errno stays, because it is the
|
|
144
|
+
// operator's only diagnostic — but in our sentence rather than the runtime's,
|
|
145
|
+
// so a model-facing tool result never carries a raw stack-adjacent string.
|
|
146
|
+
const code = err instanceof Error && "code" in err ? String(err.code) : "unknown error";
|
|
147
|
+
throw new Error(`memory_export could not write ${path} (${code})`);
|
|
148
|
+
}
|
|
76
149
|
return { path, count: mems.length };
|
|
77
150
|
}
|
|
78
151
|
|
|
@@ -159,12 +232,30 @@ function parseRow(line: string): WriteCandidate | null {
|
|
|
159
232
|
// instead. With no current scope, stamps are kept (removing them would widen
|
|
160
233
|
// the row to global) and a stamped open row is downgraded, since its stamp
|
|
161
234
|
// cannot be verified. Only a missing file throws.
|
|
235
|
+
//
|
|
236
|
+
// The path is a model-supplied READ primitive, so it is confined to the memory
|
|
237
|
+
// root BEFORE the filesystem is touched, and containment's error never says
|
|
238
|
+
// whether the path exists — otherwise a rejection is an existence oracle for
|
|
239
|
+
// files outside the store. The .jsonl requirement closes the rest of that door:
|
|
240
|
+
// without it, the tally ("N malformed lines skipped") would leak line counts of
|
|
241
|
+
// day files, snapshots and the blocklist, none of which are import formats.
|
|
162
242
|
export async function importMemories(
|
|
163
243
|
path: string,
|
|
164
244
|
gate: (c: WriteCandidate) => Promise<{ action: string }>,
|
|
165
245
|
): Promise<ImportTally> {
|
|
166
|
-
const
|
|
167
|
-
|
|
246
|
+
const target = await resolveContained(path, memoryRoot(), {
|
|
247
|
+
label: "memory_import file",
|
|
248
|
+
// Deliberately no mention of the operator escape hatch: this string goes
|
|
249
|
+
// back to the model, and naming the variable there is an instruction it can
|
|
250
|
+
// relay. The hatch lives in the README.
|
|
251
|
+
hint: `copy the export under ${memoryRoot()} first`,
|
|
252
|
+
allowOutside: allowOutsideStorePaths(),
|
|
253
|
+
});
|
|
254
|
+
if (!target.toLowerCase().endsWith(".jsonl")) {
|
|
255
|
+
throw new Error(`memory_import file must be a .jsonl export (got "${path}")`);
|
|
256
|
+
}
|
|
257
|
+
const file = Bun.file(target);
|
|
258
|
+
if (!(await file.exists())) throw new Error(`import file not found: ${target}`);
|
|
168
259
|
const tally: ImportTally = { promoted: 0, collapsed: 0, blocked: 0, skipped: 0, downgraded: 0 };
|
|
169
260
|
const currentScope = repoScopeFor(getCurrent().sid);
|
|
170
261
|
let allowFrontier = false;
|
package/src/schema.ts
CHANGED
|
@@ -147,11 +147,16 @@ export const ConsolidateArgs = z.object({
|
|
|
147
147
|
|
|
148
148
|
export const ExportArgs = z.object({
|
|
149
149
|
scope: z.string().describe("Only export memories in this exact scope").optional(),
|
|
150
|
-
file: z
|
|
150
|
+
file: z
|
|
151
|
+
.string()
|
|
152
|
+
.describe(
|
|
153
|
+
"Destination inside <memory-root>/exports/ (a relative path resolves against it). Default: <memory-root>/exports/<timestamp>.jsonl",
|
|
154
|
+
)
|
|
155
|
+
.optional(),
|
|
151
156
|
});
|
|
152
157
|
|
|
153
158
|
export const ImportArgs = z.object({
|
|
154
|
-
file: z.string().describe("Path to a .jsonl export file"),
|
|
159
|
+
file: z.string().describe("Path to a .jsonl export file, inside the memory root"),
|
|
155
160
|
});
|
|
156
161
|
|
|
157
162
|
export const DecayArgs = z.object({
|
package/src/undo.ts
CHANGED
|
@@ -11,8 +11,9 @@
|
|
|
11
11
|
// and additionally snapshots the file it replaces, so the state it drops stays
|
|
12
12
|
// undoable (result.safety).
|
|
13
13
|
import { lstat, realpath, stat } from "node:fs/promises";
|
|
14
|
-
import { basename, isAbsolute, join, relative, resolve
|
|
14
|
+
import { basename, isAbsolute, join, relative, resolve } from "node:path";
|
|
15
15
|
import { deletionsFile, snapshotDir } from "./config.ts";
|
|
16
|
+
import { isWithin } from "./containment.ts";
|
|
16
17
|
import { ensureDir, fileIdentity, parseLine, readLines, writeAtomic } from "./logfmt.ts";
|
|
17
18
|
import { withStoreLock, LOCK_RESTORE } from "./lock.ts";
|
|
18
19
|
import { snapshotFiles } from "./memory.ts";
|
|
@@ -90,11 +91,8 @@ function rows(text: string): string[] {
|
|
|
90
91
|
return text.split("\n").filter((l) => l.trim());
|
|
91
92
|
}
|
|
92
93
|
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
return rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
|
|
96
|
-
}
|
|
97
|
-
|
|
94
|
+
// isWithin comes from src/containment.ts: the snapshot restore below and the
|
|
95
|
+
// export/import destinations are the same boundary and must not drift.
|
|
98
96
|
async function resolveSnapshot(
|
|
99
97
|
snapshot: string,
|
|
100
98
|
memoryRootDir: string,
|