opencode-self-improvement 0.14.10 → 0.14.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -6
- package/package.json +1 -1
- package/src/config.ts +17 -0
- package/src/containment.ts +208 -0
- package/src/evidence.ts +31 -1
- package/src/gates.ts +13 -1
- package/src/index.ts +181 -57
- package/src/init.ts +16 -7
- package/src/inject.ts +27 -19
- package/src/memory.ts +140 -19
- package/src/portable.ts +108 -11
- package/src/prune.ts +18 -9
- package/src/repokey.ts +34 -0
- package/src/schema.ts +19 -5
- package/src/triggers.ts +24 -10
- package/src/undo.ts +4 -6
- package/src/viewer/mutate.ts +31 -3
- package/src/viewer/page.html +7 -5
- package/src/viewer/server.ts +21 -1
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 } from "./repokey.ts";
|
|
9
|
+
import { repoScopeFor, sessionScope, type RepoScope } from "./repokey.ts";
|
|
10
10
|
import { getCurrent } from "./state.ts";
|
|
11
11
|
import {
|
|
12
12
|
appendLog,
|
|
@@ -180,10 +180,11 @@ export async function loadAll(): Promise<Memory[]> {
|
|
|
180
180
|
return out;
|
|
181
181
|
}
|
|
182
182
|
|
|
183
|
-
export async function loadScope(scope: string): Promise<Memory[]> {
|
|
183
|
+
export async function loadScope(scope: string, reader: Reader = readerForAmbient()): Promise<Memory[]> {
|
|
184
184
|
// Gate dedup/stale reads are repo-scoped: a row from another repo must not
|
|
185
|
-
// collapse or supersede a write here.
|
|
186
|
-
|
|
185
|
+
// collapse or supersede a write here. The reader is the CALLER's identity,
|
|
186
|
+
// resolved at flow entry — not whatever current says after this await.
|
|
187
|
+
return (await loadAll()).filter((m) => m.scope === scope && isVisibleTo(m, reader));
|
|
187
188
|
}
|
|
188
189
|
|
|
189
190
|
export interface AppendMemoryInput {
|
|
@@ -397,7 +398,18 @@ export async function markManySuperseded(
|
|
|
397
398
|
if (!fields) continue;
|
|
398
399
|
// Whole line rewritten, not extended: an old-format line comes out in
|
|
399
400
|
// the current format with its values unchanged (as markSuperseded did).
|
|
400
|
-
|
|
401
|
+
// The one exception is SECRET SCRUB (#128, review probe 4): the
|
|
402
|
+
// fields a merge/decay/update copies into the loser's row carry
|
|
403
|
+
// caller-authored prose (the rotation note "key ghp_... rotated"),
|
|
404
|
+
// and content already scrubs at this same boundary (line 260). The
|
|
405
|
+
// durable row must not be the one place a credential survives when
|
|
406
|
+
// the evidence line beside it was cleaned.
|
|
407
|
+
const clean: SupersedeFields = { ...fields };
|
|
408
|
+
for (const k of Object.keys(clean)) {
|
|
409
|
+
const v = (clean as unknown as Record<string, unknown>)[k];
|
|
410
|
+
if (typeof v === "string") (clean as unknown as Record<string, unknown>)[k] = redactSecrets(v);
|
|
411
|
+
}
|
|
412
|
+
lines[i] = formatLine({ ...parsed, ...clean });
|
|
401
413
|
touched++;
|
|
402
414
|
}
|
|
403
415
|
if (touched === 0) return 0;
|
|
@@ -531,7 +543,12 @@ export async function logDeletion(memory: Memory, reason: string): Promise<void>
|
|
|
531
543
|
type: memory.type,
|
|
532
544
|
scope: memory.scope,
|
|
533
545
|
content: memory.content,
|
|
534
|
-
|
|
546
|
+
// Origin survives the delete/restore round trip (#129): a restore-entry
|
|
547
|
+
// made from this line re-stamps what the row carried. A row with no
|
|
548
|
+
// stamp writes no stamp here — the legacy global path, unchanged.
|
|
549
|
+
repo: memory.repo,
|
|
550
|
+
repoPath: memory.repoPath,
|
|
551
|
+
reason: redactSecrets(reason),
|
|
535
552
|
}),
|
|
536
553
|
);
|
|
537
554
|
}
|
|
@@ -544,8 +561,14 @@ export interface PruneResult {
|
|
|
544
561
|
// Remove matching memories (used by memory_forget), snapshotting first and
|
|
545
562
|
// logging every deletion with its reason. Each file is filtered and republished
|
|
546
563
|
// under the store lock, so a row another session appended while we were reading
|
|
547
|
-
// is not quietly filtered out along with the targets.
|
|
548
|
-
|
|
564
|
+
// is not quietly filtered out along with the targets. The reader is the
|
|
565
|
+
// caller's captured identity (#127); out-of-plugin callers keep ambient.
|
|
566
|
+
export async function prune(
|
|
567
|
+
scope: string,
|
|
568
|
+
type: string,
|
|
569
|
+
reason: string,
|
|
570
|
+
reader: Reader = readerForAmbient(),
|
|
571
|
+
): Promise<PruneResult> {
|
|
549
572
|
const deleted: DeletedMemory[] = [];
|
|
550
573
|
const snapshot: string[] = [];
|
|
551
574
|
for (const file of await memoryFiles()) {
|
|
@@ -562,7 +585,7 @@ export async function prune(scope: string, type: string, reason: string): Promis
|
|
|
562
585
|
// Repo floor: forgetting scope X here must never delete
|
|
563
586
|
// another repo's row for scope X — same basename collisions are real
|
|
564
587
|
// (a fork next to its upstream).
|
|
565
|
-
if (m && m.scope === scope && m.type === type &&
|
|
588
|
+
if (m && m.scope === scope && m.type === type && isVisibleTo(m, reader)) {
|
|
566
589
|
deleted.push({ memory: m, reason });
|
|
567
590
|
await logDeletion(m, reason);
|
|
568
591
|
changed = true;
|
|
@@ -584,17 +607,115 @@ export function isActive(m: Memory): boolean {
|
|
|
584
607
|
return !m.superseded_by;
|
|
585
608
|
}
|
|
586
609
|
|
|
587
|
-
//
|
|
588
|
-
//
|
|
589
|
-
//
|
|
590
|
-
//
|
|
591
|
-
//
|
|
592
|
-
//
|
|
593
|
-
|
|
610
|
+
// --- repo visibility ---------------------------------------------------------
|
|
611
|
+
// A READER is an immutable caller identity, resolved once at the entry of a
|
|
612
|
+
// flow (a hook, a tool call, a viewer route) and carried through every await
|
|
613
|
+
// in that flow. Resolution must NOT be deferred to filter time: the module
|
|
614
|
+
// global current moves whenever another session's hook or tool dispatches, and
|
|
615
|
+
// a store read awaits filesystem I/O — filtering after the await with the
|
|
616
|
+
// ambient identity injects the OTHER session's repo (#127).
|
|
617
|
+
//
|
|
618
|
+
// repo — the caller's session resolved a repository (its own when
|
|
619
|
+
// bound; the setup location for an unbound session in a
|
|
620
|
+
// single-workspace plugin, exactly the historical semantics).
|
|
621
|
+
// global-only — a plugin flow whose caller identity names no repository:
|
|
622
|
+
// explicit/legacy global rows ONLY. This is the fail-closed
|
|
623
|
+
// answer for an unbound session on a serve host; "unknown"
|
|
624
|
+
// is never "everything".
|
|
625
|
+
// admin — explicit all-repositories access: the standalone viewer and
|
|
626
|
+
// out-of-plugin maintenance callers. Administrative breadth is
|
|
627
|
+
// a property of the entry point, never of a missing session.
|
|
628
|
+
export type Reader =
|
|
629
|
+
| { kind: "repo"; scope: RepoScope }
|
|
630
|
+
| { kind: "global-only" }
|
|
631
|
+
| { kind: "admin" };
|
|
632
|
+
|
|
633
|
+
/** Explicit all-repositories identity (viewer routes, CLI maintenance). */
|
|
634
|
+
export const ADMIN_READER: Reader = { kind: "admin" };
|
|
635
|
+
|
|
636
|
+
// Reader for a plugin-session flow, resolved from the caller's OWN session id
|
|
637
|
+
// captured synchronously at flow entry. Bound session → its repo; unbound →
|
|
638
|
+
// global-only. The module scope is NOT a fallback here: in a process that
|
|
639
|
+
// loaded more than one plugin instance it belongs to whoever set up LAST,
|
|
640
|
+
// which is another workspace (#127's multi-setup gap). Plugin flows bind an
|
|
641
|
+
// unbound caller to their OWN setup location at entry (index.ts), so ordinary
|
|
642
|
+
// single-workspace sessions resolve through the session map, never here.
|
|
643
|
+
export function readerForSession(sid?: unknown): Reader {
|
|
644
|
+
const scope = sessionScope(sid);
|
|
645
|
+
return scope ? { kind: "repo", scope } : { kind: "global-only" };
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
// The historical AMBIENT reader: live session, then module scope, and no
|
|
649
|
+
// scope at all reads as unpartitioned. Correct only for out-of-plugin callers
|
|
650
|
+
// (viewer, scripts, unit tests) with no concurrent sessions; model-facing
|
|
651
|
+
// plugin paths carry a Reader instead of using this.
|
|
652
|
+
export function readerForAmbient(): Reader {
|
|
653
|
+
const scope = repoScopeFor(getCurrent().sid);
|
|
654
|
+
return scope ? { kind: "repo", scope } : { kind: "admin" };
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
// Ambient-style entry points take an optional sid: a real session id resolves
|
|
658
|
+
// fail-closed through readerForSession; "?" or absent keeps legacy semantics.
|
|
659
|
+
export function readerFromSid(sid?: unknown): Reader {
|
|
660
|
+
return typeof sid === "string" && sid !== "" && sid !== "?"
|
|
661
|
+
? readerForSession(sid)
|
|
662
|
+
: readerForAmbient();
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
// The ONLY repo filter every read path uses (injection sinks, recall, list,
|
|
666
|
+
// update targeting, prune, decay, gate scope reads). A row is visible when it
|
|
667
|
+
// is global (explicit marker OR no stamp — legacy rows and writes by
|
|
668
|
+
// processes with no scope, e.g. the viewer), or was written in the reader's
|
|
669
|
+
// repo. Keeping it one predicate is what stops the filtering from drifting
|
|
670
|
+
// between entry points.
|
|
671
|
+
export function isVisibleTo(m: Memory, reader: Reader): boolean {
|
|
672
|
+
if (reader.kind === "admin") return true;
|
|
594
673
|
if (!m.repo || m.repo === "global") return true;
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
674
|
+
if (reader.kind === "global-only") return false;
|
|
675
|
+
return m.repo === reader.scope.key || (!!m.repoPath && m.repoPath === reader.scope.path);
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
export function visibleTo(mems: Memory[], reader: Reader): Memory[] {
|
|
679
|
+
return mems.filter((m) => isVisibleTo(m, reader));
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
// The evidence-line twin of isVisibleTo, plus the one rule rows do not need:
|
|
683
|
+
// a missing stamp is NOT the same as a global marker. An explicitly
|
|
684
|
+
// `repo=global` line is global, and a line with no stamp AND no named
|
|
685
|
+
// session (legacy, or an out-of-plugin maintenance write) keeps its
|
|
686
|
+
// historical global reading. But a line a NAMED session wrote while its
|
|
687
|
+
// repository was unresolvable (evidence.ts) belongs to that session alone —
|
|
688
|
+
// visible back to the same session and to the admin surface, never to a
|
|
689
|
+
// stranger's memory_evidence. `callerSid` is the reading session's own id
|
|
690
|
+
// captured at flow entry; without it the private branch can only fail
|
|
691
|
+
// closed (admin sees all, everyone else does not).
|
|
692
|
+
export function evidenceVisibleTo(
|
|
693
|
+
fields: Record<string, unknown>,
|
|
694
|
+
reader: Reader,
|
|
695
|
+
callerSid?: unknown,
|
|
696
|
+
): boolean {
|
|
697
|
+
if (reader.kind === "admin") return true;
|
|
698
|
+
const repo = fields.repo;
|
|
699
|
+
if (typeof repo === "string" && repo !== "") {
|
|
700
|
+
if (repo === "global") return true;
|
|
701
|
+
if (reader.kind === "global-only") return false;
|
|
702
|
+
const repoPath = fields.repoPath;
|
|
703
|
+
return (
|
|
704
|
+
repo === reader.scope.key ||
|
|
705
|
+
(typeof repoPath === "string" && !!repoPath && repoPath === reader.scope.path)
|
|
706
|
+
);
|
|
707
|
+
}
|
|
708
|
+
const sid = fields.sid;
|
|
709
|
+
if (typeof sid === "string" && sid !== "" && sid !== "?") {
|
|
710
|
+
return typeof callerSid === "string" && callerSid === sid;
|
|
711
|
+
}
|
|
712
|
+
return true;
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
// Ambient (out-of-plugin) convenience: resolves the reader at CALL time.
|
|
716
|
+
// Plugin paths must pass an explicit Reader/sid instead of relying on this.
|
|
717
|
+
export function isVisibleHere(m: Memory): boolean {
|
|
718
|
+
return isVisibleTo(m, readerForAmbient());
|
|
598
719
|
}
|
|
599
720
|
|
|
600
721
|
// Rows visible to the current process (active filtering stays with callers).
|
package/src/portable.ts
CHANGED
|
@@ -3,9 +3,12 @@
|
|
|
3
3
|
// row flows through the caller-provided gate callback (index.ts wires it to
|
|
4
4
|
// runWriteGate), so moving memories between machines cannot bypass the 4-gate
|
|
5
5
|
// moat. Decay is supersede-not-delete and snapshot-first, mirroring prune.
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
6
|
+
import { constants } from "node:fs";
|
|
7
|
+
import { mkdir, open } from "node:fs/promises";
|
|
8
|
+
import { dirname, join } from "node:path";
|
|
9
|
+
import { allowOutsideStorePaths, exportsDir, memoryRoot } from "./config.ts";
|
|
10
|
+
import { resolveContained } from "./containment.ts";
|
|
11
|
+
import { isActive, isVisibleTo, loadAll, readerFromSid, type Memory } from "./memory.ts";
|
|
9
12
|
import { repoScopeFor } from "./repokey.ts";
|
|
10
13
|
import { getCurrent } from "./state.ts";
|
|
11
14
|
import { TYPES } from "./types.ts";
|
|
@@ -27,7 +30,10 @@ export const EXPORT_VERSION = 1;
|
|
|
27
30
|
export interface ExportOptions {
|
|
28
31
|
/** Only export rows from this exact scope. */
|
|
29
32
|
scope?: string;
|
|
30
|
-
/**
|
|
33
|
+
/**
|
|
34
|
+
* Destination, confined to <memory-root>/exports/ (see containment.ts).
|
|
35
|
+
* Defaults to <memory-root>/exports/<stamp>.jsonl.
|
|
36
|
+
*/
|
|
31
37
|
file?: string;
|
|
32
38
|
}
|
|
33
39
|
|
|
@@ -41,15 +47,73 @@ function stamp(d: Date = new Date()): string {
|
|
|
41
47
|
return d.toISOString().slice(0, 19).replace(/:/g, "");
|
|
42
48
|
}
|
|
43
49
|
|
|
50
|
+
// An export is a full copy of the live store, so it may only be written inside
|
|
51
|
+
// the store's own exports/ directory: ~/.gitconfig, a relative path landing in
|
|
52
|
+
// the host process's cwd, ../.., and links out of the root are all rejected.
|
|
53
|
+
// Only an absent `file` means the default — an empty or whitespace-only one is
|
|
54
|
+
// a caller bug and fails rather than silently redirecting.
|
|
55
|
+
async function resolveExportTarget(file: string | undefined): Promise<string> {
|
|
56
|
+
const allowOutside = allowOutsideStorePaths();
|
|
57
|
+
const opts = {
|
|
58
|
+
label: "memory_export file",
|
|
59
|
+
hint: `omit file for the default, or name a path under ${exportsDir()}`,
|
|
60
|
+
// An exports/ that is itself a symlink must not move the write out of the
|
|
61
|
+
// store either — same two-level check undo.ts's restore makes.
|
|
62
|
+
outerRoot: memoryRoot(),
|
|
63
|
+
allowOutside,
|
|
64
|
+
};
|
|
65
|
+
// A default destination is still a destination. Routing it through the same
|
|
66
|
+
// check is what stops an exports/ that is a link from writing the whole store
|
|
67
|
+
// copy outside the store on the argument-free call — the one a model reaches
|
|
68
|
+
// without knowing anything about the layout. Under the operator escape hatch
|
|
69
|
+
// there is nothing to check, so the plain join is what remains.
|
|
70
|
+
if (file === undefined && allowOutside) return join(exportsDir(), `${stamp()}.jsonl`);
|
|
71
|
+
return resolveContained(file ?? `${stamp()}.jsonl`, exportsDir(), opts);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// An export is a plaintext copy of the whole store, so it is written 0600 and
|
|
75
|
+
// opened O_NOFOLLOW. The flag matters: the containment check and this open are
|
|
76
|
+
// separate syscalls, and the gap is the entire store read — single-digit to tens
|
|
77
|
+
// of milliseconds on a 5 000-row store depending on the machine, which is long
|
|
78
|
+
// enough for anything that can create a link inside exports/.
|
|
79
|
+
//
|
|
80
|
+
// Both are POSIX guarantees. libuv does not implement O_NOFOLLOW on Windows
|
|
81
|
+
// (verified on the CI windows leg: the open follows the link) and Windows
|
|
82
|
+
// reports every writable file as 0666, so there the containment check that ran
|
|
83
|
+
// before this call is the only protection.
|
|
84
|
+
//
|
|
85
|
+
// Exported so the flag itself can be pinned: the containment layer refuses an
|
|
86
|
+
// existing link long before this runs, so the only way to test O_NOFOLLOW
|
|
87
|
+
// without racing is to call the writer directly.
|
|
88
|
+
export async function writeExport(path: string, text: string): Promise<void> {
|
|
89
|
+
await mkdir(dirname(path), { recursive: true });
|
|
90
|
+
const flags =
|
|
91
|
+
constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | (constants.O_NOFOLLOW ?? 0);
|
|
92
|
+
const handle = await open(path, flags, 0o600);
|
|
93
|
+
try {
|
|
94
|
+
await handle.writeFile(text, "utf8");
|
|
95
|
+
// open()'s mode applies only when the file is created, so re-exporting over
|
|
96
|
+
// a file that already existed (a 0644 one, say) would otherwise leave it
|
|
97
|
+
// world-readable and make the 0600 above a claim rather than a guarantee.
|
|
98
|
+
await handle.chmod(0o600);
|
|
99
|
+
} finally {
|
|
100
|
+
await handle.close();
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
44
104
|
// Write the ACTIVE store as JSONL — a header line followed by one JSON object
|
|
45
105
|
// per line carrying {ts,type,scope,content,status,tags,issue}. Superseded rows
|
|
46
106
|
// are not exported: the export is the live store, and history stays auditable
|
|
47
107
|
// where it lives (the original logfmt files + snapshots). The header is always
|
|
48
108
|
// written, even for an empty store, so "has header" is a format invariant.
|
|
109
|
+
//
|
|
110
|
+
// The destination is model-supplied, so it is resolved and confined BEFORE the
|
|
111
|
+
// store is read: a rejected export must not leave a file behind, and must not
|
|
112
|
+
// be a way to learn how many rows matched either.
|
|
49
113
|
export async function exportMemories(opts: ExportOptions = {}): Promise<ExportResult> {
|
|
114
|
+
const path = await resolveExportTarget(opts.file);
|
|
50
115
|
let mems = (await loadAll()).filter(isActive);
|
|
51
116
|
if (opts.scope) mems = mems.filter((m) => m.scope === opts.scope);
|
|
52
|
-
const path = opts.file ?? join(memoryRoot(), "exports", `${stamp()}.jsonl`);
|
|
53
117
|
const header = JSON.stringify({
|
|
54
118
|
_export: EXPORT_HEADER,
|
|
55
119
|
version: EXPORT_VERSION,
|
|
@@ -72,7 +136,16 @@ export async function exportMemories(opts: ExportOptions = {}): Promise<ExportRe
|
|
|
72
136
|
repoPath: m.repoPath,
|
|
73
137
|
}),
|
|
74
138
|
);
|
|
75
|
-
|
|
139
|
+
try {
|
|
140
|
+
await writeExport(path, `${[header, ...lines].join("\n")}\n`);
|
|
141
|
+
} catch (err) {
|
|
142
|
+
// Past containment, so this is not an existence oracle: `path` is one the
|
|
143
|
+
// plugin chose or already validated. The errno stays, because it is the
|
|
144
|
+
// operator's only diagnostic — but in our sentence rather than the runtime's,
|
|
145
|
+
// so a model-facing tool result never carries a raw stack-adjacent string.
|
|
146
|
+
const code = err instanceof Error && "code" in err ? String(err.code) : "unknown error";
|
|
147
|
+
throw new Error(`memory_export could not write ${path} (${code})`);
|
|
148
|
+
}
|
|
76
149
|
return { path, count: mems.length };
|
|
77
150
|
}
|
|
78
151
|
|
|
@@ -159,14 +232,37 @@ function parseRow(line: string): WriteCandidate | null {
|
|
|
159
232
|
// instead. With no current scope, stamps are kept (removing them would widen
|
|
160
233
|
// the row to global) and a stamped open row is downgraded, since its stamp
|
|
161
234
|
// cannot be verified. Only a missing file throws.
|
|
235
|
+
//
|
|
236
|
+
// The path is a model-supplied READ primitive, so it is confined to the memory
|
|
237
|
+
// root BEFORE the filesystem is touched, and containment's error never says
|
|
238
|
+
// whether the path exists — otherwise a rejection is an existence oracle for
|
|
239
|
+
// files outside the store. The .jsonl requirement closes the rest of that door:
|
|
240
|
+
// without it, the tally ("N malformed lines skipped") would leak line counts of
|
|
241
|
+
// day files, snapshots and the blocklist, none of which are import formats.
|
|
162
242
|
export async function importMemories(
|
|
163
243
|
path: string,
|
|
164
244
|
gate: (c: WriteCandidate) => Promise<{ action: string }>,
|
|
245
|
+
// The importing session, captured at tool entry (#127): "the importing
|
|
246
|
+
// session's current repo" must be the CALLER's repo even though this loop
|
|
247
|
+
// awaits the gate on every row, during which a concurrent session can move
|
|
248
|
+
// the ambient current.
|
|
249
|
+
sessionID?: string,
|
|
165
250
|
): Promise<ImportTally> {
|
|
166
|
-
const
|
|
167
|
-
|
|
251
|
+
const target = await resolveContained(path, memoryRoot(), {
|
|
252
|
+
label: "memory_import file",
|
|
253
|
+
// Deliberately no mention of the operator escape hatch: this string goes
|
|
254
|
+
// back to the model, and naming the variable there is an instruction it can
|
|
255
|
+
// relay. The hatch lives in the README.
|
|
256
|
+
hint: `copy the export under ${memoryRoot()} first`,
|
|
257
|
+
allowOutside: allowOutsideStorePaths(),
|
|
258
|
+
});
|
|
259
|
+
if (!target.toLowerCase().endsWith(".jsonl")) {
|
|
260
|
+
throw new Error(`memory_import file must be a .jsonl export (got "${path}")`);
|
|
261
|
+
}
|
|
262
|
+
const file = Bun.file(target);
|
|
263
|
+
if (!(await file.exists())) throw new Error(`import file not found: ${target}`);
|
|
168
264
|
const tally: ImportTally = { promoted: 0, collapsed: 0, blocked: 0, skipped: 0, downgraded: 0 };
|
|
169
|
-
const currentScope = repoScopeFor(getCurrent().sid);
|
|
265
|
+
const currentScope = repoScopeFor(sessionID ?? getCurrent().sid);
|
|
170
266
|
let allowFrontier = false;
|
|
171
267
|
let first = true;
|
|
172
268
|
for (const line of (await file.text()).split("\n")) {
|
|
@@ -211,11 +307,12 @@ export async function importMemories(
|
|
|
211
307
|
|
|
212
308
|
// Active open threads with ts older than `days` days, oldest first (both sides
|
|
213
309
|
// are UTC-Z ISO strings, so plain lexicographic compare is correct).
|
|
214
|
-
export async function findStaleOpen(days: number): Promise<Memory[]> {
|
|
310
|
+
export async function findStaleOpen(days: number, sid?: string): Promise<Memory[]> {
|
|
215
311
|
const cutoff = new Date(Date.now() - days * 86_400_000).toISOString();
|
|
312
|
+
const reader = readerFromSid(sid);
|
|
216
313
|
return (await loadAll())
|
|
217
314
|
// Decay is repo-scoped: running it here must not retire
|
|
218
315
|
// another repo's open threads.
|
|
219
|
-
.filter((m) => isActive(m) &&
|
|
316
|
+
.filter((m) => isActive(m) && isVisibleTo(m, reader) && m.status === "open" && m.ts < cutoff)
|
|
220
317
|
.sort((a, b) => (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : 0));
|
|
221
318
|
}
|
package/src/prune.ts
CHANGED
|
@@ -2,22 +2,31 @@
|
|
|
2
2
|
// reversible (snapshot) and never touches a repo. The `prune` evidence line is
|
|
3
3
|
// emitted before/around the mutation so S5 can assert the reason and snapshot.
|
|
4
4
|
import { deletionsFile } from "./config.ts";
|
|
5
|
-
import { prune, type PruneResult } from "./memory.ts";
|
|
5
|
+
import { prune, readerFromSid, type PruneResult } from "./memory.ts";
|
|
6
6
|
import { record } from "./evidence.ts";
|
|
7
7
|
|
|
8
8
|
export async function pruneMemory(
|
|
9
9
|
scope: string,
|
|
10
10
|
type: string,
|
|
11
11
|
reason: string,
|
|
12
|
+
// The calling session (#127): the repo floor on prune must follow the
|
|
13
|
+
// CALLER's identity, captured at tool entry, not the ambient current the
|
|
14
|
+
// locked file walk may outlive. "?" / undefined keep ambient semantics.
|
|
15
|
+
sid?: string,
|
|
12
16
|
): Promise<PruneResult & { audit: string }> {
|
|
13
|
-
const res = await prune(scope, type, reason);
|
|
17
|
+
const res = await prune(scope, type, reason, readerFromSid(sid));
|
|
14
18
|
const memTs = res.deleted.map((d) => d.memory.ts).join(",") || "-";
|
|
15
|
-
await record(
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
19
|
+
await record(
|
|
20
|
+
"prune",
|
|
21
|
+
{
|
|
22
|
+
mem: memTs,
|
|
23
|
+
reason,
|
|
24
|
+
snapshot: res.snapshot[0] ?? "-",
|
|
25
|
+
audit: deletionsFile(),
|
|
26
|
+
tool: "memory_forget",
|
|
27
|
+
},
|
|
28
|
+
true,
|
|
29
|
+
sid,
|
|
30
|
+
);
|
|
22
31
|
return { ...res, audit: deletionsFile() };
|
|
23
32
|
}
|
package/src/repokey.ts
CHANGED
|
@@ -104,12 +104,35 @@ function scopeForDir(dir: string): RepoScope {
|
|
|
104
104
|
}
|
|
105
105
|
|
|
106
106
|
export function rememberSessionDir(sid: string, dir: string): void {
|
|
107
|
+
provisional.delete(sid);
|
|
107
108
|
const prev = bySession.get(sid);
|
|
108
109
|
if (prev && prev.dir === dir) return;
|
|
109
110
|
bySession.set(sid, { dir, scope: scopeForDir(dir) });
|
|
110
111
|
while (bySession.size > SESSION_CAP) bySession.delete(bySession.keys().next().value as string);
|
|
111
112
|
}
|
|
112
113
|
|
|
114
|
+
// A binding learned from a fallback, not from the session's own identity. A
|
|
115
|
+
// plugin instance may resolve an UNKNOWN session to its own setup location —
|
|
116
|
+
// the caller reached this instance, so this workspace is the caller's repo as
|
|
117
|
+
// far as the flow can know (never the module scope, which belongs to whoever
|
|
118
|
+
// loaded LAST, #127's residual multi-setup gap). Real identity from the event
|
|
119
|
+
// stream or the session-row API always replaces a provisional binding.
|
|
120
|
+
const provisional = new Set<string>();
|
|
121
|
+
|
|
122
|
+
export function bindSessionProvisional(sid: string, dir: string | undefined): void {
|
|
123
|
+
if (!sid || sid === "?" || !dir || bySession.has(sid)) return;
|
|
124
|
+
rememberSessionDir(sid, dir);
|
|
125
|
+
provisional.add(sid);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// sessionDir, but only when the binding is FIRM (learned from the session's
|
|
129
|
+
// own events or the session row) — the guard for lookups that must not stop
|
|
130
|
+
// early on a provisional guess.
|
|
131
|
+
export function sessionDirFirm(sid?: string): string | undefined {
|
|
132
|
+
if (sid && provisional.has(sid)) return undefined;
|
|
133
|
+
return sessionDir(sid);
|
|
134
|
+
}
|
|
135
|
+
|
|
113
136
|
export function sessionDir(sid?: string): string | undefined {
|
|
114
137
|
if (!sid || sid === "?") return undefined;
|
|
115
138
|
return bySession.get(sid)?.dir;
|
|
@@ -125,7 +148,18 @@ export function repoScopeFor(sid?: string): RepoScope | null {
|
|
|
125
148
|
return current;
|
|
126
149
|
}
|
|
127
150
|
|
|
151
|
+
// The scope of a session bound from the event stream / session-row API, with
|
|
152
|
+
// NO module-scope fallback. Read paths that carry a caller's session identity
|
|
153
|
+
// resolve through this: an unbound session must fail closed to global rows
|
|
154
|
+
// (#127), never inherit a module scope that belongs to another workspace (or
|
|
155
|
+
// is null, which the ambient reader has always read as "everything").
|
|
156
|
+
export function sessionScope(sid?: unknown): RepoScope | undefined {
|
|
157
|
+
if (typeof sid !== "string" || sid === "" || sid === "?") return undefined;
|
|
158
|
+
return bySession.get(sid)?.scope;
|
|
159
|
+
}
|
|
160
|
+
|
|
128
161
|
export function resetSessionScopes(): void {
|
|
129
162
|
bySession.clear();
|
|
130
163
|
byDir.clear();
|
|
164
|
+
provisional.clear();
|
|
131
165
|
}
|
package/src/schema.ts
CHANGED
|
@@ -147,11 +147,16 @@ export const ConsolidateArgs = z.object({
|
|
|
147
147
|
|
|
148
148
|
export const ExportArgs = z.object({
|
|
149
149
|
scope: z.string().describe("Only export memories in this exact scope").optional(),
|
|
150
|
-
file: z
|
|
150
|
+
file: z
|
|
151
|
+
.string()
|
|
152
|
+
.describe(
|
|
153
|
+
"Destination inside <memory-root>/exports/ (a relative path resolves against it). Default: <memory-root>/exports/<timestamp>.jsonl",
|
|
154
|
+
)
|
|
155
|
+
.optional(),
|
|
151
156
|
});
|
|
152
157
|
|
|
153
158
|
export const ImportArgs = z.object({
|
|
154
|
-
file: z.string().describe("Path to a .jsonl export file"),
|
|
159
|
+
file: z.string().describe("Path to a .jsonl export file, inside the memory root"),
|
|
155
160
|
});
|
|
156
161
|
|
|
157
162
|
export const DecayArgs = z.object({
|
|
@@ -191,10 +196,15 @@ export const BlockBody = z.object({ ts: isoTs, reason: z.string() });
|
|
|
191
196
|
export const UnblockBody = z.object({ ts: isoTs });
|
|
192
197
|
// Strict fields by intent: String(body.x ?? "") coercion once let unvalidated
|
|
193
198
|
// POSTs append rows with empty type/scope/content.
|
|
199
|
+
// repo/repoPath (#129): the origin stamp of the DELETED row, replayed from the
|
|
200
|
+
// audit line so a restore-entry keeps the row's original visibility instead of
|
|
201
|
+
// silently landing global. Both absent = the documented legacy global restore.
|
|
194
202
|
export const RestoreEntryBody = z.object({
|
|
195
203
|
type: z.enum(TYPES),
|
|
196
204
|
scope: memoryField.min(1),
|
|
197
205
|
content: z.string().min(1),
|
|
206
|
+
repo: memoryField.min(1).max(64).optional(),
|
|
207
|
+
repoPath: memoryField.min(1).max(4096).optional(),
|
|
198
208
|
});
|
|
199
209
|
|
|
200
210
|
// ---- wiring ---------------------------------------------------------------
|
|
@@ -215,7 +225,11 @@ export interface ToolDef<S extends ZodTypeAny> {
|
|
|
215
225
|
name: string;
|
|
216
226
|
description: string;
|
|
217
227
|
options: { codemode: false };
|
|
218
|
-
|
|
228
|
+
// The second argument is the host's per-call execution context (V2 SDK
|
|
229
|
+
// ToolContext carries sessionID/messageID/id). It is optional because the
|
|
230
|
+
// V1-shaped test harness and direct callers omit it; tools must fall back
|
|
231
|
+
// to the ambient current, which is only safe SYNCHRONOUSLY at entry.
|
|
232
|
+
execute(args: z.infer<S>, context?: unknown): Promise<{ content: string }>;
|
|
219
233
|
}
|
|
220
234
|
|
|
221
235
|
/**
|
|
@@ -231,7 +245,7 @@ export function validated<S extends ZodTypeAny>(
|
|
|
231
245
|
return {
|
|
232
246
|
...def,
|
|
233
247
|
input: wire(schema),
|
|
234
|
-
async execute(raw: unknown): Promise<{ content: string }> {
|
|
248
|
+
async execute(raw: unknown, context?: unknown): Promise<{ content: string }> {
|
|
235
249
|
const parsed = schema.safeParse(raw ?? {});
|
|
236
250
|
if (!parsed.success) {
|
|
237
251
|
const issues = parsed.error.issues.map(
|
|
@@ -241,7 +255,7 @@ export function validated<S extends ZodTypeAny>(
|
|
|
241
255
|
content: `invalid arguments to ${def.name} — nothing was done: ${issues.join("; ")}`,
|
|
242
256
|
};
|
|
243
257
|
}
|
|
244
|
-
return def.execute(parsed.data);
|
|
258
|
+
return def.execute(parsed.data, context);
|
|
245
259
|
},
|
|
246
260
|
};
|
|
247
261
|
}
|
package/src/triggers.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { join } from "node:path";
|
|
|
5
5
|
import { record } from "./evidence.ts";
|
|
6
6
|
import { evidenceDir } from "./config.ts";
|
|
7
7
|
import { parseLine, readLines } from "./logfmt.ts";
|
|
8
|
+
import { redactSecrets } from "./secrets.ts";
|
|
8
9
|
import {
|
|
9
10
|
session,
|
|
10
11
|
setLastSeenSid,
|
|
@@ -86,18 +87,22 @@ function summarize(text: string, n = 80): string {
|
|
|
86
87
|
|
|
87
88
|
export async function afterTool(input: AfterInput, out: AfterOutput): Promise<void> {
|
|
88
89
|
const tool = typeof input.tool === "string" ? input.tool : "?";
|
|
89
|
-
const sid = typeof input.sessionID === "string" ? input.sessionID :
|
|
90
|
+
const sid = typeof input.sessionID === "string" ? input.sessionID : undefined;
|
|
90
91
|
const call = typeof input.callID === "string" ? input.callID : "?";
|
|
91
92
|
const cmd = argString(input.args);
|
|
92
93
|
const text = typeof out.output === "string" ? out.output : "";
|
|
94
|
+
// Redact the COMPLETE tool text before folding/truncating (#128): summarize
|
|
95
|
+
// first would cut a token at the 80-char boundary or strip a PEM END marker,
|
|
96
|
+
// and the surviving fragment would persist byte-for-byte in evidence.
|
|
97
|
+
const safeText = text ? redactSecrets(text) : "";
|
|
93
98
|
const status = classify(tool, out);
|
|
94
99
|
const ts = new Date().toISOString();
|
|
95
100
|
|
|
96
|
-
const s = session(sid);
|
|
101
|
+
const s = session(sid ?? "?");
|
|
97
102
|
const rec: ToolResult = {
|
|
98
103
|
call,
|
|
99
104
|
tool,
|
|
100
|
-
summary: summarize(
|
|
105
|
+
summary: summarize(safeText),
|
|
101
106
|
ts,
|
|
102
107
|
status: null,
|
|
103
108
|
arg: cmd || undefined,
|
|
@@ -105,13 +110,20 @@ export async function afterTool(input: AfterInput, out: AfterOutput): Promise<vo
|
|
|
105
110
|
};
|
|
106
111
|
const family = tool === "bash" || tool === "shell" ? gateCmd(cmd) : null;
|
|
107
112
|
|
|
108
|
-
// Generic capture (data, not chat).
|
|
113
|
+
// Generic capture (data, not chat). The output_summary is telemetry about
|
|
114
|
+
// the call (tool name + a short, redacted glimpse); the session/repo scoping
|
|
115
|
+
// of evidence reads is tracked separately (#128 acceptance, #130).
|
|
109
116
|
if (["grep", "glob", "read", "edit", "write", "bash", "shell"].includes(tool)) {
|
|
110
|
-
await record(
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
117
|
+
await record(
|
|
118
|
+
"tool_result",
|
|
119
|
+
{
|
|
120
|
+
tool,
|
|
121
|
+
title: tool,
|
|
122
|
+
output_summary: summarize(safeText),
|
|
123
|
+
},
|
|
124
|
+
true,
|
|
125
|
+
sid,
|
|
126
|
+
);
|
|
115
127
|
rec.status = status;
|
|
116
128
|
}
|
|
117
129
|
|
|
@@ -119,7 +131,7 @@ export async function afterTool(input: AfterInput, out: AfterOutput): Promise<vo
|
|
|
119
131
|
if (family) {
|
|
120
132
|
rec.gateCheck = true;
|
|
121
133
|
rec.cmd = family;
|
|
122
|
-
await record("gate_check", { cmd: family, status });
|
|
134
|
+
await record("gate_check", { cmd: family, status }, true, sid);
|
|
123
135
|
if (status === "FAIL") {
|
|
124
136
|
s.pendingGate = { call, cmd: family, chain: [] };
|
|
125
137
|
} else if (s.pendingGate && s.pendingGate.cmd === family) {
|
|
@@ -139,6 +151,7 @@ export async function afterTool(input: AfterInput, out: AfterOutput): Promise<vo
|
|
|
139
151
|
fix_ref: fix,
|
|
140
152
|
},
|
|
141
153
|
false,
|
|
154
|
+
sid,
|
|
142
155
|
);
|
|
143
156
|
s.pendingGate = null;
|
|
144
157
|
} else if (s.pendingGate) {
|
|
@@ -166,6 +179,7 @@ export async function afterTool(input: AfterInput, out: AfterOutput): Promise<vo
|
|
|
166
179
|
kind: "learning",
|
|
167
180
|
},
|
|
168
181
|
false,
|
|
182
|
+
sid,
|
|
169
183
|
);
|
|
170
184
|
}
|
|
171
185
|
s.lastByTool.set(tool, { status, call, emitted: prev?.emitted ?? false });
|
package/src/undo.ts
CHANGED
|
@@ -11,8 +11,9 @@
|
|
|
11
11
|
// and additionally snapshots the file it replaces, so the state it drops stays
|
|
12
12
|
// undoable (result.safety).
|
|
13
13
|
import { lstat, realpath, stat } from "node:fs/promises";
|
|
14
|
-
import { basename, isAbsolute, join, relative, resolve
|
|
14
|
+
import { basename, isAbsolute, join, relative, resolve } from "node:path";
|
|
15
15
|
import { deletionsFile, snapshotDir } from "./config.ts";
|
|
16
|
+
import { isWithin } from "./containment.ts";
|
|
16
17
|
import { ensureDir, fileIdentity, parseLine, readLines, writeAtomic } from "./logfmt.ts";
|
|
17
18
|
import { withStoreLock, LOCK_RESTORE } from "./lock.ts";
|
|
18
19
|
import { snapshotFiles } from "./memory.ts";
|
|
@@ -90,11 +91,8 @@ function rows(text: string): string[] {
|
|
|
90
91
|
return text.split("\n").filter((l) => l.trim());
|
|
91
92
|
}
|
|
92
93
|
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
return rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
|
|
96
|
-
}
|
|
97
|
-
|
|
94
|
+
// isWithin comes from src/containment.ts: the snapshot restore below and the
|
|
95
|
+
// export/import destinations are the same boundary and must not drift.
|
|
98
96
|
async function resolveSnapshot(
|
|
99
97
|
snapshot: string,
|
|
100
98
|
memoryRootDir: string,
|