opencode-self-improvement 0.14.14 → 0.14.16

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
@@ -99,20 +99,22 @@ Injection, recall, the frontier block, compaction, `memory_forget` and decay onl
99
99
 
100
100
  ## Token cost and caching
101
101
 
102
- - **Epoch-frozen injection.** The relevance block is computed once per epoch — first prompt of a session, a change to the store, or a compaction — and stays byte-identical in between, so the provider's prompt cache survives ordinary turns.
102
+ - **Section-frozen injection.** The whole memory section — standing digest, open-thread frontier, relevance block — is computed once per epoch and delivered byte-identically until something the model is actually shown changes. The epoch's authority is the **rendered bytes**, not the store fingerprint: a promoted row that changes nothing visible costs no cache bust, while a write that does change what you see costs exactly one.
103
103
  - **Two-concept threshold.** A free-text prompt must share at least two distinct concepts with a memory for it to be injected; keyword-length queries (one or two words) need only one. Silence on single-word coincidences is deliberate; `memory_recall` still reaches them on the pull path.
104
104
  - **Hard budgets.** Relevance block and each pull are capped at `injectBudget` characters, the frontier at `frontierBudget`, trimmed at whole-memory boundaries.
105
+ - **Nothing volatile on the cached prefix.** The standing digest carries no row count and no latest timestamp. Both used to ride the very front of the system prompt, so every saved memory rewrote the prefix and made the next request re-bill the whole conversation; the exact numbers now live where they are free — the footer badge, `/memory`, `memory_status`, the viewer.
105
106
  - **Evidence is never injected**, and the standing system digest is two lines.
106
107
  - **Measured, not claimed.** The plugin reads each turn's `tokens.cache` accounting and displays the actual hit rate next to the badge.
107
108
 
108
- Deterministic workload (50 memories, 20 prompts, 3 mid-session store writes) through the plugin's real injection code:
109
+ Deterministic workload (50 memories, 20 prompts, 3 mid-session store writes) through the plugin's real injection code. Every column is measured on the full memory section — the bytes a request actually sends — because prompt caching is a property of those bytes:
109
110
 
110
- | Policy | Recomputes | Injected chars (20 turns) | Avg/turn | Worst block |
111
- | --- | ---: | ---: | ---: | ---: |
112
- | A — recompute per prompt, uncapped | 20 | 25742 | 1287.1 | 1838 |
113
- | B — epoch freeze + 1200-char cap (shipped) | 4 | 19990 | 999.5 | 1139 |
111
+ | Policy | Recomputes | Cache busts | Injected chars (20 turns) | Avg/turn | Worst section |
112
+ | --- | ---: | ---: | ---: | ---: | ---: |
113
+ | A — recompute per prompt, uncapped (naive) | 20 | 19 | 60996 | 3049.8 | 3404 |
114
+ | B — block frozen on store fingerprint, digest rebuilt per turn | 4 | 3 | 55478 | 2773.9 | 2867 |
115
+ | C — section frozen on rendered bytes (shipped) | 4 | 3 | 55258 | 2762.9 | 2856 |
114
116
 
115
- Policy B injects 22.3% fewer characters, and its block is byte-identical between store changes so the prompt cache stays warm. Reproduce (byte-identical output):
117
+ A "cache bust" is a turn whose memory-section bytes differ from the turn before — each one re-bills the entire conversation as fresh input. On this workload all three writes happen to be visible, so B and C agree; a write the session *cannot* see costs C nothing and cost B a full re-prefill (pinned by `test/epoch.test.ts`, which fails against B). C also injects 9.4% fewer characters than the naive policy — the denominator here is the whole section, not the relevance block alone, so it is not comparable with the block-only figure this README quoted before. Reproduce (byte-identical output):
116
118
 
117
119
  ```sh
118
120
  bun run bench
@@ -198,12 +200,12 @@ Limits worth knowing:
198
200
 
199
201
  ## Export and move between machines
200
202
 
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.
203
+ `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
204
 
203
205
  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
206
 
205
207
  ```
206
- Export my memories # -> <memory-root>/exports/<stamp>.jsonl
208
+ Export my memories # -> <memory-root>/exports/<timestamp>-<unique>.jsonl
207
209
  # …copy that file to the other machine's <memory-root>/…
208
210
  Import <memory-root>/memories.jsonl # memory_import
209
211
  ```
@@ -229,7 +231,7 @@ Same data behind each one (`memory_status`; no model call).
229
231
  **Terminal (opencode CLI)** — the plugin ships a TUI half (`@opencode/plugin/tui`) that loads automatically:
230
232
 
231
233
  - **Footer badge** — `● mem 1157/1200c · cache 96%`: the injected block against its budget, plus the measured session prompt-cache hit rate. The dot is green (stable and warm), yellow (recent recompute, or 50–90% reads) or red (last turn served almost nothing from cache); `—` until the first assistant turn.
232
- - **`/memory`** — session panel: **CONTEXT** (chars and estimated tokens riding now, % of budget, requests this epoch has ridden, session totals, abstentions), **CACHE** (busts this session and the measured cache-served share of prompt tokens), **INJECTED BLOCK** (the verbatim block, or an explicit abstention), **RECENT BLOCKED WRITES** (with gate reasons), **STORE** (active / superseded / open / scopes, plus `malformed` when a row's `ts` is not a valid ISO instant — those rows are skipped by every reader). Keys: `r` refresh, `f` fullscreen.
234
+ - **`/memory`** — session panel: **CONTEXT** (chars and estimated tokens riding now, % of budget, the full memory section riding the prompt — digest + frontier + block — requests this epoch has ridden, session totals, abstentions), **CACHE** (busts this session and the measured cache-served share of prompt tokens), **INJECTED BLOCK** (the verbatim block, or an explicit abstention), **RECENT BLOCKED WRITES** (with gate reasons), **STORE** (active / superseded / open / scopes, plus `malformed` when a row's `ts` is not a valid ISO instant — those rows are skipped by every reader). Keys: `r` refresh, `f` fullscreen.
233
235
  - **Block toast** when a write is refused (`"notifyBlocked": false` to silence).
234
236
 
235
237
  **Desktop / web / IDE** — the terminal slots do not exist there, so use the self-installed **`/memory-report`** chat command: the same sections rendered in the conversation.
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.16",
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 {
@@ -1055,15 +1066,28 @@ const impl = {
1055
1066
  }));
1056
1067
  });
1057
1068
 
1058
- // Per-session frozen injection epochs: the relevance block plus the store
1059
- // fingerprint it was computed against. Recomputed on the first prompt of a
1060
- // tracked session, when injectable rows change, or after a compaction (see
1061
- // the prompt/context/compaction hooks) — so the system prefix, and with it
1062
- // the provider prompt cache, survives ordinary requests. The shared LRU
1063
- // below may evict the whole session state; a later prompt starts it fresh.
1069
+ // Per-session frozen injection epochs: the whole memory section (digest +
1070
+ // frontier + relevance) plus the store fingerprint it was rendered from.
1071
+ // Recomputed on the first prompt of a tracked session, when injectable rows
1072
+ // change, or after a compaction (see the prompt/context/compaction hooks).
1073
+ // The RENDERED BYTES, not the fingerprint, decide whether the epoch moved
1074
+ // (issue #162): a write that changes nothing the model is shown must not
1075
+ // cost the next request a full re-prefill. The shared LRU below may evict
1076
+ // the whole session state; a later prompt starts it fresh.
1064
1077
  const epoch = new Map<
1065
1078
  string,
1066
- { version: string; block: string; at: string; reason: "first" | "store_changed"; refs: MemoryRefs }
1079
+ {
1080
+ version: string;
1081
+ /** Frozen standing digest + frontier + convergence parts, in push order. */
1082
+ parts: string[];
1083
+ /** The budgeted relevance block the surfaces report against injectBudget. */
1084
+ block: string;
1085
+ /** Comparison key: every byte of the memory section, joined. */
1086
+ prefix: string;
1087
+ at: string;
1088
+ reason: "first" | "store_changed";
1089
+ refs: MemoryRefs;
1090
+ }
1067
1091
  >();
1068
1092
  // Latest user prompt per tracked session. A changed store is re-scored
1069
1093
  // against it even when the change happened during a tool loop with no new
@@ -1110,6 +1134,7 @@ const impl = {
1110
1134
  recomputes: epochRecomputes,
1111
1135
  block: ep.block,
1112
1136
  blockChars: ep.block.length,
1137
+ sectionChars: ep.prefix.length,
1113
1138
  budget,
1114
1139
  store: {
1115
1140
  active: act.length,
@@ -1150,32 +1175,74 @@ const impl = {
1150
1175
  for (const m of rows) for (const t of sharedTerms(query, m)) if (!terms.includes(t)) terms.push(t);
1151
1176
  await recordHits(src, sid, rows, terms);
1152
1177
  };
1178
+ // Render the COMPLETE memory section for one request: the standing digest,
1179
+ // the open-thread frontier and the convergence line (all from systemDigest),
1180
+ // followed by this epoch's relevance block. The parts are exactly what gets
1181
+ // pushed onto `event.system`; their join is the byte key the epoch compares
1182
+ // against, so "did the cache-critical prefix change?" is answered by the
1183
+ // bytes the model would actually see and never by a proxy (issue #162).
1184
+ const buildMemorySection = async (
1185
+ sid: string | undefined,
1186
+ mems: Memory[],
1187
+ ): Promise<{ parts: string[]; block: string; prefix: string; rode: Memory[]; refs: MemoryRefs }> => {
1188
+ const parts: string[] = [];
1189
+ await systemDigest(
1190
+ { sessionID: sid },
1191
+ { system: parts },
1192
+ { rows: mems, frontierBudget: openBudget },
1193
+ );
1194
+ const prompt = sid === undefined ? "" : latestPrompt.get(sid) ?? "";
1195
+ // Widen the candidate pool, then cap: the budget decides what rides.
1196
+ const sel = await selectRelevant(prompt, 5, mems, await useSignals());
1197
+ const block = sel.block ? capToBudget(sel.block, budget) : "";
1198
+ // Refs the ACTUALLY-injected rows assert (paths + commands), the join key
1199
+ // for attribution. Derived from the budget-surviving rows, not the wider
1200
+ // candidate pool — crediting paths the model never saw would overclaim.
1201
+ const rode = injectedRows(block, sel.selected);
1202
+ const prefix = [...parts, block].join("\u0000");
1203
+ return { parts, block, prefix, rode, refs: deriveMemoryRefs(rode) };
1204
+ };
1153
1205
  const refreshEpoch = async (sid: string, rows?: Memory[]): Promise<void> => {
1154
1206
  if (!latestPrompt.has(sid)) return;
1155
1207
  const mems = rows ?? (await injectableRows(sid));
1156
1208
  const version = await storeVersion(mems);
1157
1209
  const cached = epoch.get(sid);
1210
+ // Cheap pre-check: no injectable row moved, so the frozen bytes still
1211
+ // stand. Skips re-scoring and the use-ledger write on ordinary turns.
1158
1212
  if (cached?.version === version) return;
1213
+ const built = await buildMemorySection(sid, mems);
1214
+ // The store moved. A write that changes nothing RENDERED — a row that is
1215
+ // not relevant to this prompt, supersession elsewhere, a scope the reader
1216
+ // never sees rendered identically — must not cost this session a prompt
1217
+ // cache. Adopt the new fingerprint, keep riding the same bytes, emit
1218
+ // nothing: an invalidation has to mean bytes actually moved.
1219
+ if (cached && cached.prefix === built.prefix) {
1220
+ epoch.set(sid, { ...cached, version });
1221
+ return;
1222
+ }
1159
1223
  const prompt = latestPrompt.get(sid) ?? "";
1160
- const sel = await selectRelevant(prompt, 5, mems, await useSignals()); // widen candidate pool
1161
- const block = sel.block ? capToBudget(sel.block, budget) : "";
1162
- // Refs the ACTUALLY-injected rows assert (paths + commands), the join key
1163
- // for attribution. Derived from the budget-surviving rows, not the wider
1164
- // candidate pool — crediting paths the model never saw would overclaim.
1165
- const rode = injectedRows(block, sel.selected);
1166
- const refs = deriveMemoryRefs(rode);
1167
1224
  // Use ledger (#42): the rows that actually rode the block, credited with
1168
1225
  // the terms the prompt and those rows shared (never the prompt itself).
1169
- await noteHits("inject", sid, rode, prompt);
1226
+ // Only once the build is ADOPTED — a discarded rebuild must not credit
1227
+ // rows that were already offered under the frozen epoch.
1228
+ await noteHits("inject", sid, built.rode, prompt);
1170
1229
  const at = new Date().toISOString();
1171
1230
  const reason: "first" | "store_changed" = cached ? "store_changed" : "first";
1172
- epoch.set(sid, { version, block, at, reason, refs });
1231
+ epoch.set(sid, {
1232
+ version,
1233
+ parts: built.parts,
1234
+ block: built.block,
1235
+ prefix: built.prefix,
1236
+ at,
1237
+ reason,
1238
+ refs: built.refs,
1239
+ });
1173
1240
  await record(
1174
1241
  "epoch_recompute",
1175
1242
  {
1176
1243
  session: sid,
1177
1244
  reason,
1178
- chars: block.length,
1245
+ chars: built.block.length,
1179
1246
  },
1180
1247
  false,
1181
1248
  );
@@ -1259,16 +1326,26 @@ const impl = {
1259
1326
  if (typeof sid === "string") bindSessionProvisional(sid, instanceDir);
1260
1327
  const mems = await injectableRows(sid);
1261
1328
  if (typeof sid === "string") await refreshEpoch(sid, mems);
1262
- const parts: string[] = [];
1263
- await systemDigest(
1264
- { sessionID: event?.sessionID },
1265
- { system: parts },
1266
- { rows: mems, frontierBudget: openBudget },
1267
- );
1268
- for (const text of parts) event?.system?.push?.({ type: "text", text });
1269
- // Deliver this epoch's relevance-ranked memory via the system channel.
1270
- // The UI never renders system parts, unlike appended prompt text.
1271
- const knowledge = typeof sid === "string" ? epoch.get(sid)?.block : undefined;
1329
+ // Deliver the FROZEN memory section. Every byte pushed onto the system
1330
+ // prompt comes from the epoch, so between busts the provider sees an
1331
+ // identical prefix and serves the conversation from cache (issue #162).
1332
+ // A session with no epoch yet (no prompt recorded, or evicted from the
1333
+ // LRU) still gets the standing digest, built fresh and uncached.
1334
+ const ep = typeof sid === "string" ? epoch.get(sid) : undefined;
1335
+ if (ep) {
1336
+ for (const text of ep.parts) event?.system?.push?.({ type: "text", text });
1337
+ } else {
1338
+ const parts: string[] = [];
1339
+ await systemDigest(
1340
+ { sessionID: event?.sessionID },
1341
+ { system: parts },
1342
+ { rows: mems, frontierBudget: openBudget },
1343
+ );
1344
+ for (const text of parts) event?.system?.push?.({ type: "text", text });
1345
+ }
1346
+ // This epoch's relevance-ranked memory, also on the system channel —
1347
+ // the UI never renders system parts, unlike appended prompt text.
1348
+ const knowledge = ep?.block;
1272
1349
  if (knowledge) event?.system?.push?.({ type: "text", text: knowledge });
1273
1350
  // Count AT THE INJECTION DECISION so badge/panel numbers match exactly
1274
1351
  // what rode this request (a later abort still rode the bytes — known
package/src/inject.ts CHANGED
@@ -291,11 +291,17 @@ export async function systemDigest(
291
291
  // after the loadAll await.
292
292
  const mems = opts.rows ?? visibleTo((await loadAll()).filter(isActive), readerFromSid(sid));
293
293
  if (!mems.length) return;
294
- const latest = flattenMemoryText(mems.map((m) => m.ts).sort().pop() ?? "?");
294
+ // CACHE-STABLE BY CONSTRUCTION (issue #162): this line carries no row count
295
+ // and no latest-ts. Both change on every promoted write, and the digest rides
296
+ // the FRONT of the system prompt, so one volatile byte invalidated the whole
297
+ // cached prefix — every memory write cost the next request a full re-prefill.
298
+ // The exact numbers belong on surfaces where they are free and never ride a
299
+ // prompt: the footer badge, /memory, memory_status, the viewer.
295
300
  output.system.push(
296
301
  "\n## Persistent memory (opencode-self-improvement)\n" +
297
- `${mems.length} durable memories; latest: ${latest}. ` +
298
- "Check memory_recall BEFORE grepping or reading, for build/test/lint commands, decisions, and conventions. Relevant memories are also auto-injected when your message matches.",
302
+ "Durable memories exist for this repository. Check memory_recall BEFORE grepping or " +
303
+ "reading, for build/test/lint commands, decisions, and conventions. Relevant memories " +
304
+ "are also auto-injected when your message matches.",
299
305
  );
300
306
 
301
307
  const open = mems
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/status.ts CHANGED
@@ -160,6 +160,12 @@ export interface StatusPayload {
160
160
  /** exact injected block ("" = abstained: no vocabulary overlap). */
161
161
  block: string;
162
162
  blockChars: number;
163
+ /**
164
+ * Every memory byte riding the system prompt: digest + frontier + block.
165
+ * Optional for backward-compatible reads of status files written before the
166
+ * distinction existed — the panel only prints it when present.
167
+ */
168
+ sectionChars?: number;
163
169
  budget: number;
164
170
  store: StoreCounts;
165
171
  /** optional for backward-compatible reads of pre-v2 files. */
@@ -350,6 +356,15 @@ export function contextLines(p: StatusPayload): string[] {
350
356
  const pct = p.budget > 0 ? Math.round((p.blockChars / p.budget) * 100) : 0;
351
357
  return [
352
358
  ` injected now ${p.blockChars}c ≈ ${estTok(p.blockChars)} tok · ${pct}% of ${p.budget}c budget`,
359
+ // The budget caps the RELEVANCE BLOCK; the standing digest and the frontier
360
+ // ride the system prompt too. Quoting only the budgeted slice would
361
+ // understate what the request actually carries.
362
+ ...(p.sectionChars === undefined
363
+ ? []
364
+ : [
365
+ ` memory section ${p.sectionChars}c ≈ ${estTok(p.sectionChars)} tok riding the prompt` +
366
+ ` (digest + frontier + the ${p.blockChars}c block above)`,
367
+ ]),
353
368
  ` this epoch ${p.reason} epoch since ${p.at} (${ago(p.at)}) · rode ${st.epochRequests} request(s)`,
354
369
  ` session ${st.requests} request(s) · ${fmtCount(st.cumChars)}c ≈ ${fmtCount(estTok(st.cumChars))} tok rode · abstained ${st.abstained}`,
355
370
  ];
@@ -367,8 +382,9 @@ export function cacheLines(p: StatusPayload): string[] {
367
382
  ` cache busts ${st.invalidations} this session · last ${
368
383
  st.lastInvalidation ? `${st.lastInvalidation.at.slice(11, 19)} (${st.lastInvalidation.reason})` : "-"
369
384
  }`,
370
- " each memory write between turns costs exactly one; the",
371
- " prefix re-warms on the following turn",
385
+ " each write that changes what you are shown costs exactly",
386
+ " one; a write that changes nothing rendered costs nothing,",
387
+ " and the prefix re-warms on the following turn",
372
388
  ];
373
389
  const rate = cacheRate(p.measured);
374
390
  const receipts = rate
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
  );