opencode-self-improvement 0.14.11 → 0.14.13
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/evidence.ts +63 -2
- package/src/gates.ts +13 -1
- package/src/index.ts +301 -97
- package/src/init.ts +16 -7
- package/src/inject.ts +27 -19
- package/src/memory.ts +140 -19
- package/src/portable.ts +10 -4
- package/src/prune.ts +18 -9
- package/src/repokey.ts +34 -0
- package/src/schema.ts +16 -4
- package/src/triggers.ts +24 -10
- package/src/viewer/mutate.ts +31 -3
- package/src/viewer/page.html +7 -5
- package/src/viewer/server.ts +21 -1
package/src/init.ts
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
import { basename, join } from "node:path";
|
|
9
9
|
import { existsSync } from "node:fs";
|
|
10
10
|
import { cbmBin } from "./config.ts";
|
|
11
|
-
import {
|
|
11
|
+
import { isVisibleTo, loadAll, markSuperseded, readerFromSid } from "./memory.ts";
|
|
12
12
|
import { runWriteGate, type GateContext } from "./gates.ts";
|
|
13
13
|
import { record } from "./evidence.ts";
|
|
14
14
|
import { evidenceCalls, hasGateCheck } from "./triggers.ts";
|
|
@@ -30,6 +30,10 @@ export interface InitArgs {
|
|
|
30
30
|
liveRoot: string;
|
|
31
31
|
force?: boolean;
|
|
32
32
|
mode?: string;
|
|
33
|
+
// The calling session (#127): rows this writes are stamped for the CALLER,
|
|
34
|
+
// resolved after runInit's own awaits (git probing) rather than from the
|
|
35
|
+
// ambient current, which a concurrent session may have moved.
|
|
36
|
+
sessionID?: string;
|
|
33
37
|
}
|
|
34
38
|
|
|
35
39
|
export interface InitSummary {
|
|
@@ -184,12 +188,14 @@ export interface InitStamp {
|
|
|
184
188
|
head: string;
|
|
185
189
|
}
|
|
186
190
|
|
|
187
|
-
export async function initStamp(scope: string): Promise<InitStamp | null> {
|
|
191
|
+
export async function initStamp(scope: string, sid?: string): Promise<InitStamp | null> {
|
|
188
192
|
// Scope is a basename, so two different repos can share one
|
|
189
193
|
// ("api" next to "api", a fork beside its upstream). Visibility filtering
|
|
190
194
|
// makes each repo see only its own stamp — basename collisions no longer
|
|
191
|
-
// alias init state between repos.
|
|
192
|
-
|
|
195
|
+
// alias init state between repos. The reader comes from the CALLER's
|
|
196
|
+
// session, not from the global current after this await (#127).
|
|
197
|
+
const reader = readerFromSid(sid);
|
|
198
|
+
const mems = (await loadAll()).filter((m) => !m.superseded_by && isVisibleTo(m, reader));
|
|
193
199
|
for (const m of mems) {
|
|
194
200
|
if (m.type !== "context" || m.scope !== scope) continue;
|
|
195
201
|
if (!m.tags?.some((t) => t === "init-stamp")) continue;
|
|
@@ -208,12 +214,15 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
|
|
|
208
214
|
|
|
209
215
|
const gateCtx: GateContext = {
|
|
210
216
|
liveRoot: root,
|
|
211
|
-
evidenceCalls: evidenceCalls(getCurrent().sid),
|
|
212
|
-
hasGateCheck: hasGateCheck(getCurrent().sid),
|
|
217
|
+
evidenceCalls: evidenceCalls(args.sessionID ?? getCurrent().sid),
|
|
218
|
+
hasGateCheck: hasGateCheck(args.sessionID ?? getCurrent().sid),
|
|
219
|
+
// Stamps land on the caller's session even though runInit awaits git
|
|
220
|
+
// probing before the gate writes (#127 / #121's write-side root cause).
|
|
221
|
+
sessionID: args.sessionID,
|
|
213
222
|
trusted: true,
|
|
214
223
|
};
|
|
215
224
|
|
|
216
|
-
const prior = await initStamp(scope);
|
|
225
|
+
const prior = await initStamp(scope, args.sessionID);
|
|
217
226
|
if (prior && !force && prior.head === head) {
|
|
218
227
|
await record("init_skip", { scope, head, since: prior.ts }, false);
|
|
219
228
|
return {
|
package/src/inject.ts
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
// "open") get a single capped frontier block in the digest so planning sessions
|
|
7
7
|
// start at the previous session's frontier instead of re-deriving it.
|
|
8
8
|
import { createHash } from "node:crypto";
|
|
9
|
-
import { isActive, loadAll, visibleHere, type Memory } from "./memory.ts";
|
|
9
|
+
import { isActive, loadAll, readerFromSid, visibleTo, visibleHere, type Memory } from "./memory.ts";
|
|
10
10
|
import { record } from "./evidence.ts";
|
|
11
11
|
import { dateStr, frontierBudget, injectBudget } from "./config.ts";
|
|
12
12
|
import { bracketList } from "./logfmt.ts";
|
|
@@ -20,6 +20,9 @@ export interface TransformOutput {
|
|
|
20
20
|
export interface PullInput {
|
|
21
21
|
tool?: unknown;
|
|
22
22
|
args?: unknown;
|
|
23
|
+
// The session the pull runs FOR (#127): resolved to an immutable Reader at
|
|
24
|
+
// entry so the loadAll await below cannot drift into another session's repo.
|
|
25
|
+
sessionID?: unknown;
|
|
23
26
|
}
|
|
24
27
|
|
|
25
28
|
export interface PullOutput {
|
|
@@ -277,8 +280,16 @@ export async function systemDigest(
|
|
|
277
280
|
output: TransformOutput,
|
|
278
281
|
opts: DigestOptions = {},
|
|
279
282
|
): Promise<void> {
|
|
280
|
-
|
|
281
|
-
|
|
283
|
+
const sid =
|
|
284
|
+
typeof _input === "object" && _input !== null &&
|
|
285
|
+
"sessionID" in _input &&
|
|
286
|
+
typeof (_input as Record<string, unknown>).sessionID === "string"
|
|
287
|
+
? String((_input as Record<string, unknown>).sessionID)
|
|
288
|
+
: "?";
|
|
289
|
+
// Repo-scoped: model-facing reads see the CALLER's repo + global rows, via
|
|
290
|
+
// the sid carried on this flow's input (#127) — never a global re-read
|
|
291
|
+
// after the loadAll await.
|
|
292
|
+
const mems = opts.rows ?? visibleTo((await loadAll()).filter(isActive), readerFromSid(sid));
|
|
282
293
|
if (!mems.length) return;
|
|
283
294
|
const latest = flattenMemoryText(mems.map((m) => m.ts).sort().pop() ?? "?");
|
|
284
295
|
output.system.push(
|
|
@@ -302,12 +313,6 @@ export async function systemDigest(
|
|
|
302
313
|
const conv = await recentConvergenceSummary();
|
|
303
314
|
if (conv) output.system.push(`\nConvergence tracking: ${conv}`);
|
|
304
315
|
|
|
305
|
-
const sid =
|
|
306
|
-
typeof _input === "object" && _input !== null &&
|
|
307
|
-
"sessionID" in _input &&
|
|
308
|
-
typeof (_input as Record<string, unknown>).sessionID === "string"
|
|
309
|
-
? String((_input as Record<string, unknown>).sessionID)
|
|
310
|
-
: "?";
|
|
311
316
|
if (frontierInjectedSessions.has(sid)) return;
|
|
312
317
|
frontierInjectedSessions.add(sid);
|
|
313
318
|
const openMems = mems.filter((m) => m.status === "open");
|
|
@@ -335,11 +340,13 @@ export async function selectRelevant(
|
|
|
335
340
|
limit = 3,
|
|
336
341
|
rows?: Memory[],
|
|
337
342
|
use?: UseSignals,
|
|
343
|
+
sid?: string,
|
|
338
344
|
): Promise<{ block: string; selected: Memory[] }> {
|
|
339
345
|
const text = message.trim();
|
|
340
346
|
if (!text) return { block: "", selected: [] };
|
|
341
|
-
// Repo-scoped: model-facing reads see
|
|
342
|
-
|
|
347
|
+
// Repo-scoped: model-facing reads see the caller's repo + global rows
|
|
348
|
+
// (their session when one was threaded, #127).
|
|
349
|
+
const mems = rows ?? visibleTo((await loadAll()).filter(isActive), readerFromSid(sid));
|
|
343
350
|
const top = scoreMemories(text, mems, limit, use);
|
|
344
351
|
if (!top.length) return { block: "", selected: [] };
|
|
345
352
|
return {
|
|
@@ -367,9 +374,9 @@ export function injectedRows(block: string, candidates: Memory[]): Memory[] {
|
|
|
367
374
|
// changes and supersession all invalidate an epoch, while evidence, hidden
|
|
368
375
|
// rows and non-rendered metadata do not. This is only a linear hash over rows
|
|
369
376
|
// loadAll() already had to read and parse for the request.
|
|
370
|
-
export async function storeVersion(rows?: Memory[]): Promise<string> {
|
|
371
|
-
// Repo-scoped: model-facing reads see
|
|
372
|
-
const mems = rows ??
|
|
377
|
+
export async function storeVersion(rows?: Memory[], sid?: string): Promise<string> {
|
|
378
|
+
// Repo-scoped: model-facing reads see the caller's repo + global rows.
|
|
379
|
+
const mems = rows ?? visibleTo((await loadAll()).filter(isActive), readerFromSid(sid));
|
|
373
380
|
if (!mems.length) return "0:";
|
|
374
381
|
let max = "";
|
|
375
382
|
const hash = createHash("sha256");
|
|
@@ -412,9 +419,9 @@ const ANCHOR_OPEN_LIMIT = 10;
|
|
|
412
419
|
const ANCHOR_SETTLED_LIMIT = 5;
|
|
413
420
|
const ANCHOR_BUDGET = 2500;
|
|
414
421
|
|
|
415
|
-
export async function compactionAnchor(limit = 12): Promise<string> {
|
|
416
|
-
// Repo-scoped: model-facing reads see
|
|
417
|
-
const mems =
|
|
422
|
+
export async function compactionAnchor(limit = 12, sid?: string): Promise<string> {
|
|
423
|
+
// Repo-scoped: model-facing reads see the caller's repo + global rows.
|
|
424
|
+
const mems = visibleTo((await loadAll()).filter(isActive), readerFromSid(sid));
|
|
418
425
|
if (!mems.length) return "";
|
|
419
426
|
const byNewest = (a: Memory, b: Memory) => cmpTs(b.ts, a.ts);
|
|
420
427
|
const open = mems
|
|
@@ -444,8 +451,9 @@ export async function contextualPull(
|
|
|
444
451
|
if (!["grep", "glob", "read"].includes(tool)) return [];
|
|
445
452
|
const term = argText(input.args);
|
|
446
453
|
if (!term) return [];
|
|
447
|
-
// Repo-scoped: model-facing reads see
|
|
448
|
-
|
|
454
|
+
// Repo-scoped: model-facing reads see the CALLER's repo + global rows —
|
|
455
|
+
// the pull's own sessionID, resolved before the store read (#127).
|
|
456
|
+
const mems = visibleTo((await loadAll()).filter(isActive), readerFromSid(input.sessionID));
|
|
449
457
|
const top = scoreMemories(term, mems, 3, use);
|
|
450
458
|
if (!top.length) return [];
|
|
451
459
|
// Held to the injection budget too: three long rows were ~12 KB per call.
|
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
|
@@ -8,7 +8,7 @@ import { mkdir, open } from "node:fs/promises";
|
|
|
8
8
|
import { dirname, join } from "node:path";
|
|
9
9
|
import { allowOutsideStorePaths, exportsDir, memoryRoot } from "./config.ts";
|
|
10
10
|
import { resolveContained } from "./containment.ts";
|
|
11
|
-
import { isActive,
|
|
11
|
+
import { isActive, isVisibleTo, loadAll, readerFromSid, type Memory } from "./memory.ts";
|
|
12
12
|
import { repoScopeFor } from "./repokey.ts";
|
|
13
13
|
import { getCurrent } from "./state.ts";
|
|
14
14
|
import { TYPES } from "./types.ts";
|
|
@@ -242,6 +242,11 @@ function parseRow(line: string): WriteCandidate | null {
|
|
|
242
242
|
export async function importMemories(
|
|
243
243
|
path: string,
|
|
244
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,
|
|
245
250
|
): Promise<ImportTally> {
|
|
246
251
|
const target = await resolveContained(path, memoryRoot(), {
|
|
247
252
|
label: "memory_import file",
|
|
@@ -257,7 +262,7 @@ export async function importMemories(
|
|
|
257
262
|
const file = Bun.file(target);
|
|
258
263
|
if (!(await file.exists())) throw new Error(`import file not found: ${target}`);
|
|
259
264
|
const tally: ImportTally = { promoted: 0, collapsed: 0, blocked: 0, skipped: 0, downgraded: 0 };
|
|
260
|
-
const currentScope = repoScopeFor(getCurrent().sid);
|
|
265
|
+
const currentScope = repoScopeFor(sessionID ?? getCurrent().sid);
|
|
261
266
|
let allowFrontier = false;
|
|
262
267
|
let first = true;
|
|
263
268
|
for (const line of (await file.text()).split("\n")) {
|
|
@@ -302,11 +307,12 @@ export async function importMemories(
|
|
|
302
307
|
|
|
303
308
|
// Active open threads with ts older than `days` days, oldest first (both sides
|
|
304
309
|
// are UTC-Z ISO strings, so plain lexicographic compare is correct).
|
|
305
|
-
export async function findStaleOpen(days: number): Promise<Memory[]> {
|
|
310
|
+
export async function findStaleOpen(days: number, sid?: string): Promise<Memory[]> {
|
|
306
311
|
const cutoff = new Date(Date.now() - days * 86_400_000).toISOString();
|
|
312
|
+
const reader = readerFromSid(sid);
|
|
307
313
|
return (await loadAll())
|
|
308
314
|
// Decay is repo-scoped: running it here must not retire
|
|
309
315
|
// another repo's open threads.
|
|
310
|
-
.filter((m) => isActive(m) &&
|
|
316
|
+
.filter((m) => isActive(m) && isVisibleTo(m, reader) && m.status === "open" && m.ts < cutoff)
|
|
311
317
|
.sort((a, b) => (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : 0));
|
|
312
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
|
@@ -121,7 +121,10 @@ export const UndoArgs = z.object({
|
|
|
121
121
|
});
|
|
122
122
|
|
|
123
123
|
export const EvidenceArgs = z.object({
|
|
124
|
-
date: z
|
|
124
|
+
date: z
|
|
125
|
+
.string()
|
|
126
|
+
.regex(/^\d{4}-\d{2}-\d{2}$/, "must be a YYYY-MM-DD calendar date (paths are refused)")
|
|
127
|
+
.optional(),
|
|
125
128
|
ev: z.string().optional(),
|
|
126
129
|
limit: z.coerce.number().optional(),
|
|
127
130
|
});
|
|
@@ -196,10 +199,15 @@ export const BlockBody = z.object({ ts: isoTs, reason: z.string() });
|
|
|
196
199
|
export const UnblockBody = z.object({ ts: isoTs });
|
|
197
200
|
// Strict fields by intent: String(body.x ?? "") coercion once let unvalidated
|
|
198
201
|
// POSTs append rows with empty type/scope/content.
|
|
202
|
+
// repo/repoPath (#129): the origin stamp of the DELETED row, replayed from the
|
|
203
|
+
// audit line so a restore-entry keeps the row's original visibility instead of
|
|
204
|
+
// silently landing global. Both absent = the documented legacy global restore.
|
|
199
205
|
export const RestoreEntryBody = z.object({
|
|
200
206
|
type: z.enum(TYPES),
|
|
201
207
|
scope: memoryField.min(1),
|
|
202
208
|
content: z.string().min(1),
|
|
209
|
+
repo: memoryField.min(1).max(64).optional(),
|
|
210
|
+
repoPath: memoryField.min(1).max(4096).optional(),
|
|
203
211
|
});
|
|
204
212
|
|
|
205
213
|
// ---- wiring ---------------------------------------------------------------
|
|
@@ -220,7 +228,11 @@ export interface ToolDef<S extends ZodTypeAny> {
|
|
|
220
228
|
name: string;
|
|
221
229
|
description: string;
|
|
222
230
|
options: { codemode: false };
|
|
223
|
-
|
|
231
|
+
// The second argument is the host's per-call execution context (V2 SDK
|
|
232
|
+
// ToolContext carries sessionID/messageID/id). It is optional because the
|
|
233
|
+
// V1-shaped test harness and direct callers omit it; tools must fall back
|
|
234
|
+
// to the ambient current, which is only safe SYNCHRONOUSLY at entry.
|
|
235
|
+
execute(args: z.infer<S>, context?: unknown): Promise<{ content: string }>;
|
|
224
236
|
}
|
|
225
237
|
|
|
226
238
|
/**
|
|
@@ -236,7 +248,7 @@ export function validated<S extends ZodTypeAny>(
|
|
|
236
248
|
return {
|
|
237
249
|
...def,
|
|
238
250
|
input: wire(schema),
|
|
239
|
-
async execute(raw: unknown): Promise<{ content: string }> {
|
|
251
|
+
async execute(raw: unknown, context?: unknown): Promise<{ content: string }> {
|
|
240
252
|
const parsed = schema.safeParse(raw ?? {});
|
|
241
253
|
if (!parsed.success) {
|
|
242
254
|
const issues = parsed.error.issues.map(
|
|
@@ -246,7 +258,7 @@ export function validated<S extends ZodTypeAny>(
|
|
|
246
258
|
content: `invalid arguments to ${def.name} — nothing was done: ${issues.join("; ")}`,
|
|
247
259
|
};
|
|
248
260
|
}
|
|
249
|
-
return def.execute(parsed.data);
|
|
261
|
+
return def.execute(parsed.data, context);
|
|
250
262
|
},
|
|
251
263
|
};
|
|
252
264
|
}
|
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 });
|