opencode-self-improvement 0.14.14 → 0.14.15

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
@@ -198,12 +198,12 @@ Limits worth knowing:
198
198
 
199
199
  ## Export and move between machines
200
200
 
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.
201
+ `memory_export` writes the live store **as its caller can read it** as JSONL: from a plugin session that means its own repository plus global rows; full-store breadth belongs to a session-less caller outside the plugin (the library route — the viewer has no export route). The format is 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>-<unique>.jsonl` — a unique name created exclusively, so two exports in the same second never replace each other's artifact; `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
202
 
203
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:
204
204
 
205
205
  ```
206
- Export my memories # -> <memory-root>/exports/<stamp>.jsonl
206
+ Export my memories # -> <memory-root>/exports/<timestamp>-<unique>.jsonl
207
207
  # …copy that file to the other machine's <memory-root>/…
208
208
  Import <memory-root>/memories.jsonl # memory_import
209
209
  ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.14.14",
3
+ "version": "0.14.15",
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/index.ts CHANGED
@@ -707,21 +707,28 @@ const impl = {
707
707
  editor.add(validated(UndoArgs, {
708
708
  name: "memory_undo",
709
709
  description:
710
- "List memory snapshots, or restore one (rollback). Only snapshots inside this store's snapshots directory are accepted: pass a bare name from the list or its full path. Non-standard files in snapshots/ are not listed or restorable. SAFE BY DEFAULT: restore refuses if the current file has rows added or edited since the snapshot, and audited human/tool deletions stay deleted. Re-run with merge=true to restore AND keep divergent rows, or force=true for an explicit exact rollback. Blocklisted rows remain inactive in every mode.",
710
+ "List memory snapshots, or restore one (rollback). Only snapshots inside this store's snapshots directory are accepted: pass a bare name from the list or its full path. Non-standard files in snapshots/ are not listed or restorable. SAFE BY DEFAULT: restore refuses if the current file has rows added or edited since the snapshot, and audited human/tool deletions stay deleted. Re-run with merge=true to restore AND keep divergent rows, or force=true for an explicit exact rollback. Blocklisted rows remain inactive in every mode. Rows belonging to other repositories are never restored, rewound, or dropped in any mode — their lines survive verbatim, though a restore may place them later in the shared file. Global rows are visible to every repository, so they are in every repository's rollback scope.",
711
711
  options: direct,
712
- async execute(args): Promise<{ content: string }> {
712
+ async execute(args, context): Promise<{ content: string }> {
713
713
  if (args.snapshot) {
714
714
  const mode = args.force ? "force" : args.merge ? "merge" : "check";
715
- const res = await restoreSnapshot(args.snapshot, memoryRoot(), mode);
715
+ // Day files are shared across repositories (#153): the rollback
716
+ // carries the CALLER's reader, so rows another repo owns survive
717
+ // untouched in every mode instead of riding the snapshot wholesale.
718
+ const { sid } = toolIds(context);
719
+ const res = await restoreSnapshot(args.snapshot, memoryRoot(), mode, readerFromSid(sid));
716
720
  if (!res.restored) {
717
721
  const parts = [...res.concurrentAdded, ...res.concurrentChanged];
718
722
  return {
719
723
  content:
720
724
  `Undo refused: ${res.concurrentAdded.length} row(s) added and ` +
721
- `${res.concurrentChanged.length} changed since this snapshot — restoring it ` +
722
- `would clobber them. Divergent rows (ts): ${parts.join(", ")}. ` +
725
+ `${res.concurrentChanged.length} changed since this snapshot — the shared file ` +
726
+ `moved after it. Divergent rows (ts): ${parts.join(", ")}. ` +
723
727
  `If those belong to another session, re-run with merge=true (restore the file ` +
724
- `AND keep them); if they are the writes you are undoing, use force=true.`,
728
+ `AND keep them); if they are the writes you are undoing, use force=true. ` +
729
+ (res.foreignPreserved
730
+ ? `${res.foreignPreserved} row(s) in this file belong to other repositories; they survive in every mode.`
731
+ : "Rows belonging to other repositories survive in every mode."),
725
732
  };
726
733
  }
727
734
  const kept = res.mode === "merge" && (res.concurrentAdded.length || res.concurrentChanged.length)
@@ -731,7 +738,10 @@ const impl = {
731
738
  const omitted = res.deletedOmitted.length
732
739
  ? ` Omitted ${res.deletedOmitted.length} deliberately deleted row(s); use force=true to recover them.`
733
740
  : "";
734
- return { content: `Restored ${basename(res.target)} from ${res.mode} snapshot -> ${res.target}.${kept}${safety}${omitted}` };
741
+ const foreign = res.foreignPreserved
742
+ ? ` Left ${res.foreignPreserved} row(s) belonging to other repositories untouched.`
743
+ : "";
744
+ return { content: `Restored ${basename(res.target)} from ${res.mode} snapshot -> ${res.target}.${kept}${safety}${omitted}${foreign}` };
735
745
  }
736
746
  const snaps = await listSnapshots();
737
747
  if (!snaps.length) return { content: "No snapshots" };
@@ -904,11 +914,12 @@ const impl = {
904
914
  editor.add(validated(ExportArgs, {
905
915
  name: "memory_export",
906
916
  description:
907
- "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).",
917
+ "Export active memories as a JSONL file for backup or transfer to another machine — scoped to what this session can read: its own repository plus global rows (full-store breadth belongs to a session-less call made outside the plugin, the library route; the viewer has no export route). 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 a unique <memory-root>/exports/<timestamp>-<unique>.jsonl (each default export gets its own file; two exports in the same second never share a path); `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).",
908
918
  options: direct,
909
- async execute(args): Promise<{ content: string }> {
919
+ async execute(args, context): Promise<{ content: string }> {
910
920
  try {
911
- const res = await exportMemories({ scope: args.scope, file: args.file });
921
+ const { sid } = toolIds(context);
922
+ const res = await exportMemories({ scope: args.scope, file: args.file, sessionID: sid });
912
923
  return { content: `Exported ${res.count} memories -> ${res.path}` };
913
924
  } catch (err) {
914
925
  return {
package/src/memory.ts CHANGED
@@ -702,7 +702,7 @@ export function readerFromSid(sid?: unknown): Reader {
702
702
  // processes with no scope, e.g. the viewer), or was written in the reader's
703
703
  // repo. Keeping it one predicate is what stops the filtering from drifting
704
704
  // between entry points.
705
- export function isVisibleTo(m: Memory, reader: Reader): boolean {
705
+ export function isVisibleTo(m: Pick<Memory, "repo" | "repoPath">, reader: Reader): boolean {
706
706
  if (reader.kind === "admin") return true;
707
707
  if (!m.repo || m.repo === "global") return true;
708
708
  if (reader.kind === "global-only") return false;
@@ -713,6 +713,24 @@ export function visibleTo(mems: Memory[], reader: Reader): Memory[] {
713
713
  return mems.filter((m) => isVisibleTo(m, reader));
714
714
  }
715
715
 
716
+ // The day-file twin of isVisibleTo for whole-file paths (undo/restore) that
717
+ // work on raw logfmt lines instead of parsed rows: the SAME predicate, with the
718
+ // rows' rule that a line with no stamp is a legacy row, not a private one —
719
+ // which is exactly the rule the evidence lines do NOT share, and the reason
720
+ // these are not one function. An unparseable line has no stamp, so it reads
721
+ // legacy-global rather than silently vanishing under a restore.
722
+ export function lineVisibleTo(line: string, reader: Reader): boolean {
723
+ if (reader.kind === "admin") return true;
724
+ const fields = parseLine(line);
725
+ return isVisibleTo(
726
+ {
727
+ repo: typeof fields?.repo === "string" ? fields.repo : undefined,
728
+ repoPath: typeof fields?.repoPath === "string" ? fields.repoPath : undefined,
729
+ },
730
+ reader,
731
+ );
732
+ }
733
+
716
734
  // The evidence-line twin of isVisibleTo, plus the one rule rows do not need:
717
735
  // a missing stamp is NOT the same as a global marker. An explicitly
718
736
  // `repo=global` line is global, and a line with no stamp AND no named
package/src/portable.ts CHANGED
@@ -4,6 +4,7 @@
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
6
  import { constants } from "node:fs";
7
+ import { randomUUID } from "node:crypto";
7
8
  import { mkdir, open } from "node:fs/promises";
8
9
  import { dirname, join } from "node:path";
9
10
  import { allowOutsideStorePaths, exportsDir, memoryRoot } from "./config.ts";
@@ -39,9 +40,19 @@ export interface ExportOptions {
39
40
  scope?: string;
40
41
  /**
41
42
  * Destination, confined to <memory-root>/exports/ (see containment.ts).
42
- * Defaults to <memory-root>/exports/<stamp>.jsonl.
43
+ * Defaults to <memory-root>/exports/<stamp>-<unique>.jsonl: a UNIQUE name,
44
+ * created exclusively, so two exports in the same second can never replace
45
+ * each other's artifact (#143's review). An explicit `file` keeps the
46
+ * historical replace semantics backups rely on.
43
47
  */
44
48
  file?: string;
49
+ /**
50
+ * The calling session's identity (#143): an export carries exactly the rows
51
+ * its reader can read — own repo plus global. "?" or absent resolves the
52
+ * AMBIENT reader: out-of-plugin callers (viewer, CLI maintenance) keep the
53
+ * full-store breadth; breadth stays a property of the entry point.
54
+ */
55
+ sessionID?: string;
45
56
  }
46
57
 
47
58
  export interface ExportResult {
@@ -49,9 +60,14 @@ export interface ExportResult {
49
60
  count: number;
50
61
  }
51
62
 
52
- // Filesystem-safe YYYY-MM-DDTHHMMSS (no colons).
63
+ // Filesystem-safe YYYY-MM-DDTHHMMSS (no colons) plus a unique suffix for each
64
+ // default export. The timestamp alone was second-granular: two sessions
65
+ // exporting in the same second got the SAME path, and O_TRUNC let the later
66
+ // one destroy the earlier one's artifact AND its returned path (#143 review).
67
+ // Milliseconds would still collide; uniqueness comes from the name, not the
68
+ // clock.
53
69
  function stamp(d: Date = new Date()): string {
54
- return d.toISOString().slice(0, 19).replace(/:/g, "");
70
+ return `${d.toISOString().slice(0, 19).replace(/:/g, "")}-${randomUUID()}`;
55
71
  }
56
72
 
57
73
  // An export is a full copy of the live store, so it may only be written inside
@@ -92,10 +108,17 @@ async function resolveExportTarget(file: string | undefined): Promise<string> {
92
108
  // Exported so the flag itself can be pinned: the containment layer refuses an
93
109
  // existing link long before this runs, so the only way to test O_NOFOLLOW
94
110
  // without racing is to call the writer directly.
95
- export async function writeExport(path: string, text: string): Promise<void> {
111
+ export async function writeExport(path: string, text: string, exclusive = false): Promise<void> {
96
112
  await mkdir(dirname(path), { recursive: true });
113
+ // exclusive = a default destination WE chose: create it or fail, never
114
+ // silently replace another export's file. An explicit caller-supplied
115
+ // `file` keeps the historical O_TRUNC replace (backup workflows rewrite
116
+ // the same path on purpose).
97
117
  const flags =
98
- constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | (constants.O_NOFOLLOW ?? 0);
118
+ constants.O_WRONLY |
119
+ constants.O_CREAT |
120
+ (exclusive ? constants.O_EXCL : constants.O_TRUNC) |
121
+ (constants.O_NOFOLLOW ?? 0);
99
122
  const handle = await open(path, flags, 0o600);
100
123
  try {
101
124
  await handle.writeFile(text, "utf8");
@@ -114,12 +137,18 @@ export async function writeExport(path: string, text: string): Promise<void> {
114
137
  // where it lives (the original logfmt files + snapshots). The header is always
115
138
  // written, even for an empty store, so "has header" is a format invariant.
116
139
  //
140
+ // "the live store" means the store AS THE CALLER CAN READ IT (#143): rows are
141
+ // filtered through the caller's Reader, exactly as recall and injection do.
142
+ // Full breadth remains the ambient/admin entry point's, never a missing
143
+ // session's.
144
+ //
117
145
  // The destination is model-supplied, so it is resolved and confined BEFORE the
118
146
  // store is read: a rejected export must not leave a file behind, and must not
119
147
  // be a way to learn how many rows matched either.
120
148
  export async function exportMemories(opts: ExportOptions = {}): Promise<ExportResult> {
121
149
  const path = await resolveExportTarget(opts.file);
122
- let mems = (await loadAll()).filter(isActive);
150
+ const reader = readerFromSid(opts.sessionID);
151
+ let mems = (await loadAll()).filter(isActive).filter((m) => isVisibleTo(m, reader));
123
152
  if (opts.scope) mems = mems.filter((m) => m.scope === opts.scope);
124
153
  const header = JSON.stringify({
125
154
  _export: EXPORT_HEADER,
@@ -144,7 +173,7 @@ export async function exportMemories(opts: ExportOptions = {}): Promise<ExportRe
144
173
  }),
145
174
  );
146
175
  try {
147
- await writeExport(path, `${[header, ...lines].join("\n")}\n`);
176
+ await writeExport(path, `${[header, ...lines].join("\n")}\n`, opts.file === undefined);
148
177
  } catch (err) {
149
178
  // Past containment, so this is not an existence oracle: `path` is one the
150
179
  // plugin chose or already validated. The errno stays, because it is the
package/src/schema.ts CHANGED
@@ -153,7 +153,7 @@ export const ExportArgs = z.object({
153
153
  file: z
154
154
  .string()
155
155
  .describe(
156
- "Destination inside <memory-root>/exports/ (a relative path resolves against it). Default: <memory-root>/exports/<timestamp>.jsonl",
156
+ "Destination inside <memory-root>/exports/ (a relative path resolves against it). Default: <memory-root>/exports/<timestamp>-<unique>.jsonl, unique per export",
157
157
  )
158
158
  .optional(),
159
159
  });
package/src/undo.ts CHANGED
@@ -10,13 +10,27 @@
10
10
  // MERGE replays them on top of the snapshot; FORCE is the old exact rollback,
11
11
  // and additionally snapshots the file it replaces, so the state it drops stays
12
12
  // undoable (result.safety).
13
+ //
14
+ // A day file is shared across REPOSITORIES too, and foreign rows are outside
15
+ // a caller's reach in every sense (#153): no mode revives them from the
16
+ // snapshot, rewinds them to a stale copy, or drops them. Foreign live lines
17
+ // are carried over verbatim in every mode, appended at the end — line content
18
+ // preserved, position in the shared file not — and only the caller's own rows
19
+ // take part in the audited-deletion and divergence logic. ONE exception is
20
+ // visibility, not ownership: GLOBAL rows (repo=global, or legacy unstamped)
21
+ // are visible to every reader, so every repository's rollback treats them as
22
+ // its own — a force restore may drop a global line appended after the
23
+ // snapshot (pinned in test/undo-ownership). That is #131's "act on exactly
24
+ // what you may read", the same rule memory_forget applies to global scope.
25
+ // Admin readers (the viewer, out-of-plugin maintenance) keep the whole-file
26
+ // restore exactly as it was.
13
27
  import { lstat, realpath, stat } from "node:fs/promises";
14
28
  import { basename, isAbsolute, join, relative, resolve } from "node:path";
15
29
  import { deletionsFile, snapshotDir } from "./config.ts";
16
30
  import { isWithin } from "./containment.ts";
17
31
  import { ensureDir, fileIdentity, parseLine, readLines, writeAtomic } from "./logfmt.ts";
18
32
  import { withStoreLock, LOCK_RESTORE } from "./lock.ts";
19
- import { snapshotFiles } from "./memory.ts";
33
+ import { ADMIN_READER, lineVisibleTo, snapshotFiles, type Reader } from "./memory.ts";
20
34
 
21
35
  const SNAPSHOT_NAME = /^(\d+)-(\d{4}-\d{2}-\d{2}\.logfmt)$/;
22
36
 
@@ -80,6 +94,10 @@ export interface RestoreResult {
80
94
  // ts of rows intentionally deleted after this snapshot. CHECK and MERGE
81
95
  // leave them deleted; FORCE is the explicit recovery path.
82
96
  deletedOmitted: string[];
97
+ // Live rows owned by other repositories, whose lines are carried over
98
+ // verbatim (appended at the end) in every mode (#153). Admin restores
99
+ // report 0 — there is no foreign reader.
100
+ foreignPreserved: number;
83
101
  }
84
102
 
85
103
  // Rows are keyed by their ts= field; unparseable lines key on the whole line.
@@ -168,6 +186,7 @@ export async function restoreSnapshot(
168
186
  snapshot: string,
169
187
  memoryRootDir: string,
170
188
  mode: RestoreMode = "check",
189
+ reader: Reader = ADMIN_READER,
171
190
  ): Promise<RestoreResult> {
172
191
  const snap = await resolveSnapshot(snapshot, memoryRootDir);
173
192
  const rootReal = await realpath(resolve(memoryRootDir));
@@ -212,9 +231,20 @@ export async function restoreSnapshot(
212
231
  // Deliberate deletions are read inside the lock too, so a forget that
213
232
  // finished just before this restore is honoured.
214
233
  const audited = mode !== "force" ? await auditedDeletions() : new Set<string>();
215
- const live = new Set(curLines.map(rowKey));
234
+ // Ownership before anything else (#153): rows a foreign repo owns are
235
+ // excluded from the snapshot side in EVERY mode (never revived, never
236
+ // rewound), excluded from the deletion audit and the divergence
237
+ // bookkeeping (not this caller's to reason about), and carried verbatim
238
+ // from the live file, appended at the end.
239
+ const snapOwn = rawSnapLines.filter((l) => lineVisibleTo(l, reader));
240
+ // One pass partitions the live lines (review N2): a whole-file restore
241
+ // has no business parsing every line three times.
242
+ const curOwn: string[] = [];
243
+ const curForeign: string[] = [];
244
+ for (const l of curLines) (lineVisibleTo(l, reader) ? curOwn : curForeign).push(l);
245
+ const live = new Set(curOwn.map(rowKey));
216
246
  const deletedOmitted: string[] = [];
217
- const snapLines = rawSnapLines.filter((line) => {
247
+ const snapLines = snapOwn.filter((line) => {
218
248
  const key = rowKey(line);
219
249
  if (!audited.has(key) || live.has(key)) return true;
220
250
  deletedOmitted.push(key);
@@ -225,7 +255,7 @@ export async function restoreSnapshot(
225
255
  const concurrentAdded: string[] = [];
226
256
  const concurrentChanged: string[] = [];
227
257
  const curByKey = new Map<string, string>();
228
- for (const l of curLines) {
258
+ for (const l of curOwn) {
229
259
  const k = rowKey(l);
230
260
  curByKey.set(k, l);
231
261
  const s = snapByKey.get(k);
@@ -233,8 +263,31 @@ export async function restoreSnapshot(
233
263
  else if (s !== l) concurrentChanged.push(k);
234
264
  }
235
265
 
266
+ // CHECK keeps its documented conservatism (#153 control): ANY divergence
267
+ // of the shared file — including other repositories' rows, which FORCE
268
+ // and MERGE now provably leave untouched — refuses until the caller picks
269
+ // a mode deliberately. The refusal is a "the file moved, say again on
270
+ // purpose" gate, not a clobber prediction.
271
+ if (mode === "check") {
272
+ const snapAll = new Map(rawSnapLines.map((l) => [rowKey(l), l]));
273
+ for (const l of curForeign) {
274
+ const k = rowKey(l);
275
+ const s = snapAll.get(k);
276
+ if (s === undefined) concurrentAdded.push(k);
277
+ else if (s !== l) concurrentChanged.push(k);
278
+ }
279
+ }
280
+
236
281
  if (mode === "check" && (concurrentAdded.length || concurrentChanged.length)) {
237
- return { target, restored: false, mode, concurrentAdded, concurrentChanged, deletedOmitted };
282
+ return {
283
+ target,
284
+ restored: false,
285
+ mode,
286
+ concurrentAdded,
287
+ concurrentChanged,
288
+ deletedOmitted,
289
+ foreignPreserved: curForeign.length,
290
+ };
238
291
  }
239
292
 
240
293
  // FORCE is the mode that drops rows, so the file it replaces is
@@ -251,12 +304,27 @@ export async function restoreSnapshot(
251
304
  // snapshotter wrote after the snapshot are NOT dropped here; choose FORCE
252
305
  // for that.
253
306
  out = snapLines.map((l) => curByKey.get(rowKey(l)) ?? l).concat(
254
- curLines.filter((l) => !snapByKey.has(rowKey(l))),
307
+ curOwn.filter((l) => !snapByKey.has(rowKey(l))),
255
308
  );
256
309
  }
310
+ // FORCE's "exact rollback" is exact FOR THE CALLER'S REPOSITORY, not
311
+ // beyond it: foreign live lines rejoin the file verbatim in every mode,
312
+ // appended at the end — line content preserved, position not (#153).
313
+ // Under the admin reader curForeign is empty and the write is the
314
+ // historical whole-file restore, byte for byte.
315
+ out = out.concat(curForeign);
257
316
  await ensureDir(memoryRootDir);
258
317
  await writeAtomic(target, out.length ? out.join("\n") + "\n" : "", since);
259
- return { target, restored: true, mode, safety, concurrentAdded, concurrentChanged, deletedOmitted };
318
+ return {
319
+ target,
320
+ restored: true,
321
+ mode,
322
+ safety,
323
+ concurrentAdded,
324
+ concurrentChanged,
325
+ deletedOmitted,
326
+ foreignPreserved: curForeign.length,
327
+ };
260
328
  },
261
329
  LOCK_RESTORE,
262
330
  );