opencode-self-improvement 0.14.13 → 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 +3 -3
- package/package.json +1 -1
- package/src/index.ts +65 -11
- package/src/memory.ts +58 -6
- package/src/portable.ts +53 -10
- package/src/repokey.ts +28 -1
- package/src/schema.ts +1 -1
- package/src/undo.ts +75 -7
package/README.md
CHANGED
|
@@ -95,7 +95,7 @@ Nothing is deleted: `memory_update` supersedes the previous row, `memory_forget`
|
|
|
95
95
|
|
|
96
96
|
Rows are stamped with your git origin (an id that survives re-clones and moves between machines) or, without an origin, a hash of the normalized directory path. `repoPath` keeps the human-readable path, so rows written before hashing keep matching.
|
|
97
97
|
|
|
98
|
-
Injection, recall, the frontier block, compaction, `memory_forget` and decay only see the current repo plus global rows, resolved from the calling session's identity at flow entry. A session that reaches a plugin instance is bound to that instance's own workspace on first contact — in a process hosting several workspaces, one session never borrows the repository some other workspace's setup left behind. A session whose repository cannot be resolved at all sees global rows only; "unknown" is never "everything". Evidence lines carry the same stamp, so `memory_evidence` answers from the caller's repo plus global lines; a line a named session wrote while its repository was unresolvable is private to that session, and only an explicitly global (or predating-stamps) line reads as global. Preferences that should follow you everywhere go in with `memory_remember global: true`. Rows written before scoping existed are global, and the viewer (an admin surface over every repo) edits and restores a row with its own repo stamp — the viewer's missing session scope never decides a row's visibility. `memory_merge_review` applies the same rule to its inputs: a session may merge exactly the rows it may read — global rows plus its own repo's, from either seat — and a row id it merely knows is not authority to retire another repo's memory. Upgrading changes nothing.
|
|
98
|
+
Injection, recall, the frontier block, compaction, `memory_forget` and decay only see the current repo plus global rows, resolved from the calling session's identity at flow entry. A session that reaches a plugin instance is bound to that instance's own workspace on first contact — in a process hosting several workspaces, one session never borrows the repository some other workspace's setup left behind. A session whose repository cannot be resolved at all sees global rows only; "unknown" is never "everything". Writes follow that rule in the stricter direction: a named session with no resolved repository has **no write target**, so `memory_remember`, `memory_update`, `memory_import` and auto-capture refuse it (evidence `write_refused`) and store nothing — the alternatives were stamping your private content into whichever workspace's `setup()` ran last, or publishing it to every project as an unstamped row. A caller that names no session at all (the viewer process, a restore, a script) keeps the process scope, and an explicit `global: true` is a deliberate owner. Evidence lines carry the same stamp, so `memory_evidence` answers from the caller's repo plus global lines; a line a named session wrote while its repository was unresolvable is private to that session, and only an explicitly global (or predating-stamps) line reads as global. Preferences that should follow you everywhere go in with `memory_remember global: true`. Rows written before scoping existed are global, and the viewer (an admin surface over every repo) edits and restores a row with its own repo stamp — the viewer's missing session scope never decides a row's visibility. `memory_merge_review` applies the same rule to its inputs: a session may merge exactly the rows it may read — global rows plus its own repo's, from either seat — and a row id it merely knows is not authority to retire another repo's memory. Upgrading changes nothing.
|
|
99
99
|
|
|
100
100
|
## Token cost and caching
|
|
101
101
|
|
|
@@ -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
|
|
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/<
|
|
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.
|
|
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
|
@@ -27,6 +27,7 @@ import {
|
|
|
27
27
|
readerFromSid,
|
|
28
28
|
resolveMemoryTarget,
|
|
29
29
|
snapshotFiles,
|
|
30
|
+
unresolvedWriteMessage,
|
|
30
31
|
visibleTo,
|
|
31
32
|
type Memory,
|
|
32
33
|
} from "./memory.ts";
|
|
@@ -81,7 +82,7 @@ import {
|
|
|
81
82
|
onCompacting,
|
|
82
83
|
} from "./triggers.ts";
|
|
83
84
|
import { getCurrent, setCurrent } from "./state.ts";
|
|
84
|
-
import { resolveRepo, setRepoScope, rememberSessionDir, sessionDir, sessionDirFirm, bindSessionProvisional } from "./repokey.ts";
|
|
85
|
+
import { resolveRepo, setRepoScope, rememberSessionDir, sessionDir, sessionDirFirm, bindSessionProvisional, writeTarget } from "./repokey.ts";
|
|
85
86
|
import { parseLine, readLines } from "./logfmt.ts";
|
|
86
87
|
import { buildCapturePrompt, flattenTranscript, lagSince, parseCandidates, parseModelRef } from "./capture.ts";
|
|
87
88
|
import { redactSecrets } from "./secrets.ts";
|
|
@@ -343,6 +344,24 @@ const impl = {
|
|
|
343
344
|
};
|
|
344
345
|
};
|
|
345
346
|
|
|
347
|
+
// A durable write needs an OWNER (#152). Reads already fail closed for a
|
|
348
|
+
// session whose repository never resolved — it sees global rows and nothing
|
|
349
|
+
// else — so such a session may not write either: the alternatives were the
|
|
350
|
+
// last setup's repository or an unstamped (hence global) row. This answers
|
|
351
|
+
// at the entry, where the model can be told what to do, and records the
|
|
352
|
+
// refusal so "why is nothing stored" is answerable from memory_evidence.
|
|
353
|
+
// appendMemory throws the same rule at the choke point; the two share one
|
|
354
|
+
// message so they cannot drift.
|
|
355
|
+
const ownerlessWriter = (sid: string | undefined): string | null => {
|
|
356
|
+
const target = writeTarget(sid);
|
|
357
|
+
return target.ok ? null : target.sid;
|
|
358
|
+
};
|
|
359
|
+
|
|
360
|
+
const refuseOwnerlessWrite = async (sid: string, op: string): Promise<{ content: string }> => {
|
|
361
|
+
await record("write_refused", { op }, true, sid);
|
|
362
|
+
return { content: unresolvedWriteMessage(sid) };
|
|
363
|
+
};
|
|
364
|
+
|
|
346
365
|
// Identity of a tool call, captured SYNCHRONOUSLY at the tool's entry —
|
|
347
366
|
// the first await of the call comes after this. The V2 host hands every
|
|
348
367
|
// execute a per-call ToolContext carrying sessionID; the harness and any
|
|
@@ -457,6 +476,12 @@ const impl = {
|
|
|
457
476
|
repo: args.global ? "global" : undefined,
|
|
458
477
|
};
|
|
459
478
|
await bindSessionIdentity(sid);
|
|
479
|
+
// An explicit global write needs no repository owner; anything else
|
|
480
|
+
// does (#152).
|
|
481
|
+
if (!args.global) {
|
|
482
|
+
const ownerless = ownerlessWriter(sid);
|
|
483
|
+
if (ownerless) return await refuseOwnerlessWrite(ownerless, "remember");
|
|
484
|
+
}
|
|
460
485
|
const outcome = await runWriteGate(candidate, gateContext(sid));
|
|
461
486
|
if (outcome.action === "promoted") return { content: `Remembered: ${args.type} in ${args.scope}` };
|
|
462
487
|
if (outcome.action === "collapsed") return { content: `Duplicate ignored: ${args.type}/${args.scope}` };
|
|
@@ -503,6 +528,8 @@ const impl = {
|
|
|
503
528
|
async execute(args, context): Promise<{ content: string }> {
|
|
504
529
|
const { sid } = toolIds(context);
|
|
505
530
|
await bindSessionIdentity(sid);
|
|
531
|
+
const ownerless = ownerlessWriter(sid);
|
|
532
|
+
if (ownerless) return await refuseOwnerlessWrite(ownerless, "init");
|
|
506
533
|
const summary = await runInit({
|
|
507
534
|
liveRoot: gateContext(sid).liveRoot,
|
|
508
535
|
force: args.force,
|
|
@@ -563,6 +590,8 @@ const impl = {
|
|
|
563
590
|
async execute(args, context): Promise<{ content: string }> {
|
|
564
591
|
const { sid } = toolIds(context);
|
|
565
592
|
await bindSessionIdentity(sid);
|
|
593
|
+
const ownerless = ownerlessWriter(sid);
|
|
594
|
+
if (ownerless) return await refuseOwnerlessWrite(ownerless, "update");
|
|
566
595
|
const reader = readerFromSid(sid);
|
|
567
596
|
// The whole update — resolve, gate, supersede — runs under one
|
|
568
597
|
// UPDATE-ORDER lock. Without it, two concurrent updates that both
|
|
@@ -678,21 +707,28 @@ const impl = {
|
|
|
678
707
|
editor.add(validated(UndoArgs, {
|
|
679
708
|
name: "memory_undo",
|
|
680
709
|
description:
|
|
681
|
-
"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.",
|
|
682
711
|
options: direct,
|
|
683
|
-
async execute(args): Promise<{ content: string }> {
|
|
712
|
+
async execute(args, context): Promise<{ content: string }> {
|
|
684
713
|
if (args.snapshot) {
|
|
685
714
|
const mode = args.force ? "force" : args.merge ? "merge" : "check";
|
|
686
|
-
|
|
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));
|
|
687
720
|
if (!res.restored) {
|
|
688
721
|
const parts = [...res.concurrentAdded, ...res.concurrentChanged];
|
|
689
722
|
return {
|
|
690
723
|
content:
|
|
691
724
|
`Undo refused: ${res.concurrentAdded.length} row(s) added and ` +
|
|
692
|
-
`${res.concurrentChanged.length} changed since this snapshot —
|
|
693
|
-
`
|
|
725
|
+
`${res.concurrentChanged.length} changed since this snapshot — the shared file ` +
|
|
726
|
+
`moved after it. Divergent rows (ts): ${parts.join(", ")}. ` +
|
|
694
727
|
`If those belong to another session, re-run with merge=true (restore the file ` +
|
|
695
|
-
`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."),
|
|
696
732
|
};
|
|
697
733
|
}
|
|
698
734
|
const kept = res.mode === "merge" && (res.concurrentAdded.length || res.concurrentChanged.length)
|
|
@@ -702,7 +738,10 @@ const impl = {
|
|
|
702
738
|
const omitted = res.deletedOmitted.length
|
|
703
739
|
? ` Omitted ${res.deletedOmitted.length} deliberately deleted row(s); use force=true to recover them.`
|
|
704
740
|
: "";
|
|
705
|
-
|
|
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}` };
|
|
706
745
|
}
|
|
707
746
|
const snaps = await listSnapshots();
|
|
708
747
|
if (!snaps.length) return { content: "No snapshots" };
|
|
@@ -875,11 +914,12 @@ const impl = {
|
|
|
875
914
|
editor.add(validated(ExportArgs, {
|
|
876
915
|
name: "memory_export",
|
|
877
916
|
description:
|
|
878
|
-
"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).",
|
|
879
918
|
options: direct,
|
|
880
|
-
async execute(args): Promise<{ content: string }> {
|
|
919
|
+
async execute(args, context): Promise<{ content: string }> {
|
|
881
920
|
try {
|
|
882
|
-
const
|
|
921
|
+
const { sid } = toolIds(context);
|
|
922
|
+
const res = await exportMemories({ scope: args.scope, file: args.file, sessionID: sid });
|
|
883
923
|
return { content: `Exported ${res.count} memories -> ${res.path}` };
|
|
884
924
|
} catch (err) {
|
|
885
925
|
return {
|
|
@@ -896,6 +936,12 @@ const impl = {
|
|
|
896
936
|
options: direct,
|
|
897
937
|
async execute(args, context): Promise<{ content: string }> {
|
|
898
938
|
const { sid } = toolIds(context);
|
|
939
|
+
// Resolve before touching the file: every imported row is re-stamped
|
|
940
|
+
// with the IMPORTING session's repository, so an unresolved caller
|
|
941
|
+
// would move a whole export into whoever set up last (#152).
|
|
942
|
+
await bindSessionIdentity(sid);
|
|
943
|
+
const ownerless = ownerlessWriter(sid);
|
|
944
|
+
if (ownerless) return await refuseOwnerlessWrite(ownerless, "import");
|
|
899
945
|
try {
|
|
900
946
|
const t = await importMemories(
|
|
901
947
|
args.file,
|
|
@@ -1440,6 +1486,14 @@ const impl = {
|
|
|
1440
1486
|
// no-op there). SYNC only: a lookup call here would break the
|
|
1441
1487
|
// zero-token promise of the capture tests.
|
|
1442
1488
|
bindSessionProvisional(sid, instanceDir);
|
|
1489
|
+
// #152: an instance with no workspace cannot say which repository the
|
|
1490
|
+
// mined rows belong to, and rows with no owner are exactly what the
|
|
1491
|
+
// store refuses. Skip BEFORE the model call — no tokens spent on a
|
|
1492
|
+
// capture that cannot be stored — and leave the reason in evidence.
|
|
1493
|
+
if (!writeTarget(sid).ok) {
|
|
1494
|
+
await record("auto_capture_refused", { session: sid, trigger }, true, sid);
|
|
1495
|
+
return;
|
|
1496
|
+
}
|
|
1443
1497
|
let transcript = seeded;
|
|
1444
1498
|
let msgs = seededMsgs;
|
|
1445
1499
|
if (transcript.length < 200) {
|
package/src/memory.ts
CHANGED
|
@@ -6,7 +6,7 @@ import { existsSync } from "node:fs";
|
|
|
6
6
|
import { open } from "node:fs/promises";
|
|
7
7
|
import { join, basename } from "node:path";
|
|
8
8
|
import { dateStr, memoryRoot, deletionsFile, snapshotDir, HITS_FILENAME } from "./config.ts";
|
|
9
|
-
import { repoScopeFor, sessionScope, type RepoScope } from "./repokey.ts";
|
|
9
|
+
import { repoScopeFor, sessionScope, writeTarget, type RepoScope } from "./repokey.ts";
|
|
10
10
|
import { getCurrent } from "./state.ts";
|
|
11
11
|
import {
|
|
12
12
|
appendLog,
|
|
@@ -219,6 +219,30 @@ async function existingTs(file: string): Promise<Set<string>> {
|
|
|
219
219
|
return set;
|
|
220
220
|
}
|
|
221
221
|
|
|
222
|
+
// #152: the store's answer to a write whose owner it cannot determine. Thrown
|
|
223
|
+
// from the one place that knows what an owner is (the stamp resolution below),
|
|
224
|
+
// so no caller — gate, import, capture, or a future one — can quietly persist
|
|
225
|
+
// an ownerless row. `unresolvedWriteMessage` is the same text the model-facing
|
|
226
|
+
// tools return, kept here so the two can never drift.
|
|
227
|
+
export function unresolvedWriteMessage(sid: string): string {
|
|
228
|
+
return (
|
|
229
|
+
`Write refused: session ${sid} has no resolvable repository, so nothing was stored. ` +
|
|
230
|
+
`A memory with no owner must not be stamped into another repository or published as a ` +
|
|
231
|
+
`global row. Retry from a session in the project you mean, or pass global:true for a ` +
|
|
232
|
+
`deliberate cross-project memory.`
|
|
233
|
+
);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export class UnresolvedWriterError extends Error {
|
|
237
|
+
/** The named-but-unresolved session whose write was refused. */
|
|
238
|
+
sid: string;
|
|
239
|
+
constructor(sid: string) {
|
|
240
|
+
super(unresolvedWriteMessage(sid));
|
|
241
|
+
this.name = "UnresolvedWriterError";
|
|
242
|
+
this.sid = sid;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
222
246
|
// Append a durable memory. GATE-4 promotions and the viewer's edit/restore-entry
|
|
223
247
|
// paths all call this single write choke point.
|
|
224
248
|
export async function appendMemory(input: AppendMemoryInput): Promise<string> {
|
|
@@ -270,10 +294,20 @@ export async function appendMemory(input: AppendMemoryInput): Promise<string> {
|
|
|
270
294
|
// the last setCurrent before persistence may belong to another session
|
|
271
295
|
// entirely (#116). Unnamed writers (tools, viewer, restore) keep the
|
|
272
296
|
// ambient binding.
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
297
|
+
//
|
|
298
|
+
// A NAMED session that never resolved a repository is not an unnamed one
|
|
299
|
+
// (#152): falling back to the module scope stamped its rows into whatever
|
|
300
|
+
// workspace set up last, and with no module scope at all it stamped nothing
|
|
301
|
+
// — which every reader calls global. Both outcomes publish private content
|
|
302
|
+
// somewhere its owner can no longer see it, so the store refuses the write
|
|
303
|
+
// instead of guessing an owner. Tools answer with this message before the
|
|
304
|
+
// gate runs; throwing here is what covers every caller, including ones that
|
|
305
|
+
// reach the store without a tool.
|
|
306
|
+
const target = writeTarget(input.sessionID ?? getCurrent().sid);
|
|
307
|
+
if (!target.ok) throw new UnresolvedWriterError(target.sid);
|
|
308
|
+
if (target.scope) {
|
|
309
|
+
repo = target.scope.key;
|
|
310
|
+
repoPath = target.scope.path;
|
|
277
311
|
}
|
|
278
312
|
}
|
|
279
313
|
// Day file chosen before the lock (it IS the lock key). A ts bumped across
|
|
@@ -668,7 +702,7 @@ export function readerFromSid(sid?: unknown): Reader {
|
|
|
668
702
|
// processes with no scope, e.g. the viewer), or was written in the reader's
|
|
669
703
|
// repo. Keeping it one predicate is what stops the filtering from drifting
|
|
670
704
|
// between entry points.
|
|
671
|
-
export function isVisibleTo(m: Memory, reader: Reader): boolean {
|
|
705
|
+
export function isVisibleTo(m: Pick<Memory, "repo" | "repoPath">, reader: Reader): boolean {
|
|
672
706
|
if (reader.kind === "admin") return true;
|
|
673
707
|
if (!m.repo || m.repo === "global") return true;
|
|
674
708
|
if (reader.kind === "global-only") return false;
|
|
@@ -679,6 +713,24 @@ export function visibleTo(mems: Memory[], reader: Reader): Memory[] {
|
|
|
679
713
|
return mems.filter((m) => isVisibleTo(m, reader));
|
|
680
714
|
}
|
|
681
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
|
+
|
|
682
734
|
// The evidence-line twin of isVisibleTo, plus the one rule rows do not need:
|
|
683
735
|
// a missing stamp is NOT the same as a global marker. An explicitly
|
|
684
736
|
// `repo=global` line is global, and a line with no stamp AND no named
|
package/src/portable.ts
CHANGED
|
@@ -4,12 +4,20 @@
|
|
|
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";
|
|
10
11
|
import { resolveContained } from "./containment.ts";
|
|
11
|
-
import {
|
|
12
|
-
|
|
12
|
+
import {
|
|
13
|
+
isActive,
|
|
14
|
+
isVisibleTo,
|
|
15
|
+
loadAll,
|
|
16
|
+
readerFromSid,
|
|
17
|
+
UnresolvedWriterError,
|
|
18
|
+
type Memory,
|
|
19
|
+
} from "./memory.ts";
|
|
20
|
+
import { writeTarget } from "./repokey.ts";
|
|
13
21
|
import { getCurrent } from "./state.ts";
|
|
14
22
|
import { TYPES } from "./types.ts";
|
|
15
23
|
import type { WriteCandidate } from "./gates.ts";
|
|
@@ -32,9 +40,19 @@ export interface ExportOptions {
|
|
|
32
40
|
scope?: string;
|
|
33
41
|
/**
|
|
34
42
|
* Destination, confined to <memory-root>/exports/ (see containment.ts).
|
|
35
|
-
* 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.
|
|
36
47
|
*/
|
|
37
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;
|
|
38
56
|
}
|
|
39
57
|
|
|
40
58
|
export interface ExportResult {
|
|
@@ -42,9 +60,14 @@ export interface ExportResult {
|
|
|
42
60
|
count: number;
|
|
43
61
|
}
|
|
44
62
|
|
|
45
|
-
// 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.
|
|
46
69
|
function stamp(d: Date = new Date()): string {
|
|
47
|
-
return d.toISOString().slice(0, 19).replace(/:/g, "")
|
|
70
|
+
return `${d.toISOString().slice(0, 19).replace(/:/g, "")}-${randomUUID()}`;
|
|
48
71
|
}
|
|
49
72
|
|
|
50
73
|
// An export is a full copy of the live store, so it may only be written inside
|
|
@@ -85,10 +108,17 @@ async function resolveExportTarget(file: string | undefined): Promise<string> {
|
|
|
85
108
|
// Exported so the flag itself can be pinned: the containment layer refuses an
|
|
86
109
|
// existing link long before this runs, so the only way to test O_NOFOLLOW
|
|
87
110
|
// without racing is to call the writer directly.
|
|
88
|
-
export async function writeExport(path: string, text: string): Promise<void> {
|
|
111
|
+
export async function writeExport(path: string, text: string, exclusive = false): Promise<void> {
|
|
89
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).
|
|
90
117
|
const flags =
|
|
91
|
-
constants.O_WRONLY |
|
|
118
|
+
constants.O_WRONLY |
|
|
119
|
+
constants.O_CREAT |
|
|
120
|
+
(exclusive ? constants.O_EXCL : constants.O_TRUNC) |
|
|
121
|
+
(constants.O_NOFOLLOW ?? 0);
|
|
92
122
|
const handle = await open(path, flags, 0o600);
|
|
93
123
|
try {
|
|
94
124
|
await handle.writeFile(text, "utf8");
|
|
@@ -107,12 +137,18 @@ export async function writeExport(path: string, text: string): Promise<void> {
|
|
|
107
137
|
// where it lives (the original logfmt files + snapshots). The header is always
|
|
108
138
|
// written, even for an empty store, so "has header" is a format invariant.
|
|
109
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
|
+
//
|
|
110
145
|
// The destination is model-supplied, so it is resolved and confined BEFORE the
|
|
111
146
|
// store is read: a rejected export must not leave a file behind, and must not
|
|
112
147
|
// be a way to learn how many rows matched either.
|
|
113
148
|
export async function exportMemories(opts: ExportOptions = {}): Promise<ExportResult> {
|
|
114
149
|
const path = await resolveExportTarget(opts.file);
|
|
115
|
-
|
|
150
|
+
const reader = readerFromSid(opts.sessionID);
|
|
151
|
+
let mems = (await loadAll()).filter(isActive).filter((m) => isVisibleTo(m, reader));
|
|
116
152
|
if (opts.scope) mems = mems.filter((m) => m.scope === opts.scope);
|
|
117
153
|
const header = JSON.stringify({
|
|
118
154
|
_export: EXPORT_HEADER,
|
|
@@ -137,7 +173,7 @@ export async function exportMemories(opts: ExportOptions = {}): Promise<ExportRe
|
|
|
137
173
|
}),
|
|
138
174
|
);
|
|
139
175
|
try {
|
|
140
|
-
await writeExport(path, `${[header, ...lines].join("\n")}\n
|
|
176
|
+
await writeExport(path, `${[header, ...lines].join("\n")}\n`, opts.file === undefined);
|
|
141
177
|
} catch (err) {
|
|
142
178
|
// Past containment, so this is not an existence oracle: `path` is one the
|
|
143
179
|
// plugin chose or already validated. The errno stays, because it is the
|
|
@@ -262,7 +298,14 @@ export async function importMemories(
|
|
|
262
298
|
const file = Bun.file(target);
|
|
263
299
|
if (!(await file.exists())) throw new Error(`import file not found: ${target}`);
|
|
264
300
|
const tally: ImportTally = { promoted: 0, collapsed: 0, blocked: 0, skipped: 0, downgraded: 0 };
|
|
265
|
-
|
|
301
|
+
// #152: the importing session's repository is resolved BEFORE the first row,
|
|
302
|
+
// through the writer rule rather than the ambient one. An unresolved named
|
|
303
|
+
// session has no write target, and half a file re-stamped into whatever
|
|
304
|
+
// workspace happened to set up last is worse than none — so this throws
|
|
305
|
+
// before a single row is gated, not partway through the tally.
|
|
306
|
+
const writeAt = writeTarget(sessionID ?? getCurrent().sid);
|
|
307
|
+
if (!writeAt.ok) throw new UnresolvedWriterError(writeAt.sid);
|
|
308
|
+
const currentScope = writeAt.scope;
|
|
266
309
|
let allowFrontier = false;
|
|
267
310
|
let first = true;
|
|
268
311
|
for (const line of (await file.text()).split("\n")) {
|
package/src/repokey.ts
CHANGED
|
@@ -154,10 +154,37 @@ export function repoScopeFor(sid?: string): RepoScope | null {
|
|
|
154
154
|
// (#127), never inherit a module scope that belongs to another workspace (or
|
|
155
155
|
// is null, which the ambient reader has always read as "everything").
|
|
156
156
|
export function sessionScope(sid?: unknown): RepoScope | undefined {
|
|
157
|
-
if (
|
|
157
|
+
if (!isNamedSid(sid)) return undefined;
|
|
158
158
|
return bySession.get(sid)?.scope;
|
|
159
159
|
}
|
|
160
160
|
|
|
161
|
+
/** Did the host actually name a session? ("?" and absent mean nobody.) */
|
|
162
|
+
export function isNamedSid(sid: unknown): sid is string {
|
|
163
|
+
return typeof sid === "string" && sid !== "" && sid !== "?";
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// The repository a DURABLE WRITE belongs to (#152) — the write-side twin of
|
|
167
|
+
// sessionScope, and deliberately not `repoScopeFor`: that helper's last resort
|
|
168
|
+
// is the module scope, which is the identity of whoever called setup() LAST.
|
|
169
|
+
// Reading with the wrong owner can only ever show too little (an unbound
|
|
170
|
+
// session reads global rows and nothing else), but writing with the wrong owner
|
|
171
|
+
// MOVES private content into a repository that cannot recall where it came
|
|
172
|
+
// from — and a null module scope turns the same write into an unstamped, hence
|
|
173
|
+
// global, row that every other project then reads. So an identity the host
|
|
174
|
+
// named but never resolved has NO write target: `ok:false`, which callers must
|
|
175
|
+
// refuse rather than downgrade. A caller that names nobody (viewer process,
|
|
176
|
+
// restore, scripts, unit tests) keeps the historical module-scope answer,
|
|
177
|
+
// including "no scope at all" — that is the deliberate admin path.
|
|
178
|
+
export type WriteTarget =
|
|
179
|
+
| { ok: true; scope: RepoScope | null }
|
|
180
|
+
| { ok: false; sid: string };
|
|
181
|
+
|
|
182
|
+
export function writeTarget(sid?: unknown): WriteTarget {
|
|
183
|
+
if (!isNamedSid(sid)) return { ok: true, scope: current };
|
|
184
|
+
const scope = sessionScope(sid);
|
|
185
|
+
return scope ? { ok: true, scope } : { ok: false, sid };
|
|
186
|
+
}
|
|
187
|
+
|
|
161
188
|
export function resetSessionScopes(): void {
|
|
162
189
|
bySession.clear();
|
|
163
190
|
byDir.clear();
|
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
|
-
|
|
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 =
|
|
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
|
|
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 {
|
|
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
|
-
|
|
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 {
|
|
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
|
);
|