opencode-self-improvement 0.14.11 → 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/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
- // Repo-scoped: model-facing reads see this repo + global rows.
281
- const mems = opts.rows ?? visibleHere((await loadAll()).filter(isActive));
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 this repo + global rows.
342
- const mems = rows ?? visibleHere((await loadAll()).filter(isActive));
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 this repo + global rows.
372
- const mems = rows ?? visibleHere((await loadAll()).filter(isActive));
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 this repo + global rows.
417
- const mems = visibleHere((await loadAll()).filter(isActive));
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 this repo + global rows.
448
- const mems = visibleHere((await loadAll()).filter(isActive));
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
- return (await loadAll()).filter((m) => m.scope === scope && isVisibleHere(m));
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
- lines[i] = formatLine({ ...parsed, ...fields });
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
- reason,
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
- export async function prune(scope: string, type: string, reason: string): Promise<PruneResult> {
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 && isVisibleHere(m)) {
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
- // The ONLY repo filter the model-facing paths use (injection sinks, recall,
588
- // list, update targeting, prune, decay, gate scope reads). A row is visible
589
- // when it is global (explicit marker OR no stamp — legacy rows and writes by
590
- // processes with no scope, e.g. the viewer), or was written in this repo.
591
- // Keeping it one predicate is what stops the filtering from drifting between
592
- // entry points.
593
- export function isVisibleHere(m: Memory): boolean {
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
- const cur = repoScopeFor(getCurrent().sid);
596
- if (!cur) return true; // unscoped process: no partitioning
597
- return m.repo === cur.key || (!!m.repoPath && m.repoPath === cur.path);
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, isVisibleHere, loadAll, type Memory } from "./memory.ts";
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) && isVisibleHere(m) && m.status === "open" && m.ts < cutoff)
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("prune", {
16
- mem: memTs,
17
- reason,
18
- snapshot: res.snapshot[0] ?? "-",
19
- audit: deletionsFile(),
20
- tool: "memory_forget",
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
@@ -196,10 +196,15 @@ export const BlockBody = z.object({ ts: isoTs, reason: z.string() });
196
196
  export const UnblockBody = z.object({ ts: isoTs });
197
197
  // Strict fields by intent: String(body.x ?? "") coercion once let unvalidated
198
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.
199
202
  export const RestoreEntryBody = z.object({
200
203
  type: z.enum(TYPES),
201
204
  scope: memoryField.min(1),
202
205
  content: z.string().min(1),
206
+ repo: memoryField.min(1).max(64).optional(),
207
+ repoPath: memoryField.min(1).max(4096).optional(),
203
208
  });
204
209
 
205
210
  // ---- wiring ---------------------------------------------------------------
@@ -220,7 +225,11 @@ export interface ToolDef<S extends ZodTypeAny> {
220
225
  name: string;
221
226
  description: string;
222
227
  options: { codemode: false };
223
- execute(args: z.infer<S>): Promise<{ content: string }>;
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 }>;
224
233
  }
225
234
 
226
235
  /**
@@ -236,7 +245,7 @@ export function validated<S extends ZodTypeAny>(
236
245
  return {
237
246
  ...def,
238
247
  input: wire(schema),
239
- async execute(raw: unknown): Promise<{ content: string }> {
248
+ async execute(raw: unknown, context?: unknown): Promise<{ content: string }> {
240
249
  const parsed = schema.safeParse(raw ?? {});
241
250
  if (!parsed.success) {
242
251
  const issues = parsed.error.issues.map(
@@ -246,7 +255,7 @@ export function validated<S extends ZodTypeAny>(
246
255
  content: `invalid arguments to ${def.name} — nothing was done: ${issues.join("; ")}`,
247
256
  };
248
257
  }
249
- return def.execute(parsed.data);
258
+ return def.execute(parsed.data, context);
250
259
  },
251
260
  };
252
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(text),
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("tool_result", {
111
- tool,
112
- title: tool,
113
- output_summary: summarize(text),
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 });
@@ -9,6 +9,7 @@
9
9
  import { deletionsFile } from "../config.ts";
10
10
  import { addBlock, removeBlock } from "../blocklist.ts";
11
11
  import { record, chainId } from "../evidence.ts";
12
+ import { redactSecrets } from "../secrets.ts";
12
13
  import { appendLog, fileIdentity, formatLine, parseLine, readLines, writeAtomic } from "../logfmt.ts";
13
14
  import { withStoreLock, LOCK_WRITE } from "../lock.ts";
14
15
  import {
@@ -55,6 +56,18 @@ async function findMemory(ts: string): Promise<Memory> {
55
56
 
56
57
  // Non-destructive edit: snapshot the pre-state, supersede the old entry, then
57
58
  // append the edited replacement (added ONLY because the edit requires it).
59
+ //
60
+ // ORIGIN PRESERVATION (#129): the replacement carries the target's repo stamp
61
+ // verbatim. The viewer is an ADMIN entry point with no repository scope of
62
+ // its own; letting appendMemory resolve the stamp from that null scope used
63
+ // to leave every edited row unstamped — i.e. silently GLOBAL, recallable and
64
+ // injectable in every other project. An edit must never widen visibility: a
65
+ // row from repo A stays invisible everywhere except A (and global rows, as
66
+ // before) after an edit. Making a row global is a deliberate action (the
67
+ // `global` flag on memory_remember), never a side effect of who clicked edit.
68
+ // An unstamped target (legacy row, or one explicitly stored global) has no
69
+ // origin to carry: the replacement is stamped explicitly "global" — same
70
+ // visibility as the absent stamp, and now honest about it on the line itself.
58
71
  export async function editMemory(input: EditInput): Promise<MutationResult> {
59
72
  requireReason(input.reason);
60
73
  const chain = chainId();
@@ -65,9 +78,16 @@ export async function editMemory(input: EditInput): Promise<MutationResult> {
65
78
  type: input.type || target.type,
66
79
  scope: input.scope || target.scope,
67
80
  content: input.content,
68
- issue: input.issue,
69
- tags: input.tags,
81
+ // Omitted metadata survives the edit (#129): the usual UI sends
82
+ // type/scope/content/reason, and dropping the old issue/tags/kw erased
83
+ // import/auto-capture provenance and retrieval aliases from a row whose
84
+ // prose only got a typo fix.
85
+ issue: input.issue ?? target.issue,
86
+ tags: input.tags ?? target.tags,
87
+ kw: target.kw,
70
88
  status: target.status,
89
+ repo: target.repo ?? "global",
90
+ repoPath: target.repo ? target.repoPath : undefined,
71
91
  });
72
92
  await markSuperseded(input.ts, {
73
93
  superseded_by: newTs,
@@ -155,7 +175,15 @@ async function audit(
155
175
  type: mem.type,
156
176
  scope: mem.scope,
157
177
  content: mem.content,
158
- reason,
178
+ // Origin survives the audit record (#129): the viewer's restore-entry
179
+ // path reads these lines, and a restore of a repo-private row must be
180
+ // able to re-stamp what was deleted. A line with no stamp is the
181
+ // legacy/unstamped case — restore leaves it global, as documented.
182
+ repo: mem.repo,
183
+ repoPath: mem.repoPath,
184
+ // Same write-boundary rule as evidence (#128): an audit reason is
185
+ // human prose and must not persist a recognized credential.
186
+ reason: redactSecrets(reason),
159
187
  }),
160
188
  );
161
189
  }