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/README.md CHANGED
@@ -95,7 +95,7 @@ Nothing is deleted: `memory_update` supersedes the previous row, `memory_forget`
95
95
 
96
96
  Rows are stamped with your git origin (an id that survives re-clones and moves between machines) or, without an origin, a hash of the normalized directory path. `repoPath` keeps the human-readable path, so rows written before hashing keep matching.
97
97
 
98
- Injection, recall, the frontier block, compaction, `memory_forget` and decay only see the current repo plus global rows. Preferences that should follow you everywhere go in with `memory_remember global: true`. Rows written before scoping existed, and rows restored through the viewer, are global — upgrading changes nothing.
98
+ Injection, recall, the frontier block, compaction, `memory_forget` and decay only see the current repo plus global rows, resolved from the calling session's identity at flow entry. A session that reaches a plugin instance is bound to that instance's own workspace on first contact — in a process hosting several workspaces, one session never borrows the repository some other workspace's setup left behind. A session whose repository cannot be resolved at all sees global rows only; "unknown" is never "everything". Evidence lines carry the same stamp, so `memory_evidence` answers from the caller's repo plus global lines; a line a named session wrote while its repository was unresolvable is private to that session, and only an explicitly global (or predating-stamps) line reads as global. Preferences that should follow you everywhere go in with `memory_remember global: true`. Rows written before scoping existed are global, and the viewer (an admin surface over every repo) edits and restores a row with its own repo stamp — the viewer's missing session scope never decides a row's visibility. Upgrading changes nothing.
99
99
 
100
100
  ## Token cost and caching
101
101
 
@@ -185,7 +185,7 @@ On the eval dataset the pass takes 200 rows to 52 with **R@3 52 → 53 and R@1 5
185
185
 
186
186
  ## Secret redaction
187
187
 
188
- One best-effort credential rule set (`src/secrets.ts`) runs over the auto-capture prompt before it leaves the plugin, at the write gate before content is hashed or analysed, and again in the final write choke point used by gated writes and the viewer's edit and restore paths.
188
+ One best-effort credential rule set (`src/secrets.ts`) runs over the auto-capture prompt before it leaves the plugin, at the write gate before content is hashed or analysed, again in the final write choke point used by gated writes and the viewer's edit and restore paths, and at the durable audit boundaries — every evidence line, every supersede field written into a retired row, and every deletion-audit reason — so a recognized credential cannot persist in `evidence/` or `deletions.logfmt` or a tombstoned row regardless of which path carried it.
189
189
 
190
190
  Covered: OpenAI `sk-`, GitHub `ghp_` / `gho_` / `github_pat_`, Slack `xoxb-` / `xoxp-`, AWS `AKIA`, Google `AIza`, bearer tokens containing digits, PEM private-key blocks, and high-entropy values assigned to names ending in `_KEY`, `_TOKEN`, `_SECRET` or `_PASSWORD` (plus `password`).
191
191
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.14.11",
3
+ "version": "0.14.12",
4
4
  "description": "Durable memory for opencode: remember facts, decisions, and commands across sessions, plus a one-command per-repo setup (/repo-init).",
5
5
  "main": "index.ts",
6
6
  "exports": {
package/src/evidence.ts CHANGED
@@ -5,10 +5,25 @@ import { join } from "node:path";
5
5
  import { createHash } from "node:crypto";
6
6
  import { dateStr, evidenceDir } from "./config.ts";
7
7
  import { appendLog, formatLine } from "./logfmt.ts";
8
+ import { repoScope, sessionScope } from "./repokey.ts";
8
9
  import { getCurrent } from "./state.ts";
10
+ import { redactSecrets } from "./secrets.ts";
9
11
 
10
12
  export type EvidenceEvent = string;
11
13
 
14
+ // Credential scrub at the evidence WRITE boundary. Evidence fields routinely
15
+ // carry caller-authored prose (gate reasons, block reasons, review notes) and
16
+ // tool-derived summaries; a recognized credential must not persist in the
17
+ // durable log no matter which line carried it (#128). redactSecrets is a
18
+ // no-op on ordinary text (ids, hashes, paths, counts).
19
+ function scrubFields(fields: Record<string, unknown>): Record<string, unknown> {
20
+ const out: Record<string, unknown> = {};
21
+ for (const [key, value] of Object.entries(fields)) {
22
+ out[key] = typeof value === "string" ? redactSecrets(value) : value;
23
+ }
24
+ return out;
25
+ }
26
+
12
27
  export async function record(
13
28
  ev: EvidenceEvent,
14
29
  fields: Record<string, unknown> = {},
@@ -25,11 +40,26 @@ export async function record(
25
40
  // this is exactly the old ambient read.
26
41
  const sid = sessionID ?? cur.sid;
27
42
  const call = sessionID !== undefined && sessionID !== cur.sid ? undefined : cur.call;
43
+ // Read-side partitioning of the shared log (#131's rule, applied to
44
+ // evidence; the re-review closed the last two gaps in it). A NAMED session
45
+ // is stamped from its OWN resolved scope only — the module scope is never
46
+ // the fallback here: in a process that loaded several plugin instances it
47
+ // belongs to whoever set up LAST, and A's evidence must not live in B's
48
+ // repository. A named session whose repository is unresolvable writes an
49
+ // UNSTAMPED line that stays private to that session (memory.ts
50
+ // evidenceVisibleTo pairs with this choice): "unknown" is never
51
+ // "everything" (#127), and it is never somebody else's repo either. Only a
52
+ // genuinely session-less line — out-of-plugin maintenance, viewer, CLI —
53
+ // takes the process scope, and unstamped session-less lines (legacy, or a
54
+ // scope-less process) keep their historical global reading.
55
+ const named = typeof sid === "string" && sid !== "" && sid !== "?";
56
+ const scope = named ? sessionScope(sid) : repoScope();
28
57
  const line = formatLine({
29
58
  ev,
30
59
  ts: new Date().toISOString(),
31
60
  ...(includeContext ? { sid, call } : {}),
32
- ...fields,
61
+ ...(scope ? { repo: scope.key, repoPath: scope.path } : {}),
62
+ ...scrubFields(fields),
33
63
  });
34
64
  await appendLog(join(evidenceDir(), `${dateStr()}.logfmt`), line);
35
65
  }
package/src/gates.ts CHANGED
@@ -17,6 +17,7 @@ import {
17
17
  import { chainId, contentHash, record, recordWriteBlocked } from "./evidence.ts";
18
18
  import { flattenMemoryText } from "./sanitize.ts";
19
19
  import { containsSecret, redactSecrets } from "./secrets.ts";
20
+ import { readerForSession } from "./memory.ts";
20
21
  import {
21
22
  displayCall,
22
23
  extractCallForms,
@@ -328,7 +329,18 @@ export async function runWriteGate(
328
329
  ch,
329
330
  });
330
331
 
331
- const scopeMems = candidate.scope ? await loadScope(candidate.scope) : [];
332
+ const scopeMems = candidate.scope
333
+ ? await loadScope(
334
+ candidate.scope,
335
+ // Dedup/stale reads partition on the WRITE's session, captured at
336
+ // flow entry — not the ambient current after this await (#127). An
337
+ // unknown "?" (or absent) caller is the readerFromSid AMBIENT case,
338
+ // exactly as before: readerForSession is for named sessions only.
339
+ ctx.sessionID !== undefined && ctx.sessionID !== "?"
340
+ ? readerForSession(ctx.sessionID)
341
+ : undefined,
342
+ )
343
+ : [];
332
344
  // One tree index per write, shared by gate1 and every gate2 stale scan.
333
345
  const tree = memoTree(ctx.liveRoot);
334
346
 
package/src/index.ts CHANGED
@@ -16,14 +16,18 @@ import { evidenceDir, frontierBudget, injectBudget, memoryRoot, dateStr } from "
16
16
  import { STATUSES, TYPES } from "./types.ts";
17
17
  import {
18
18
  clearSuperseded,
19
+ evidenceVisibleTo,
19
20
  isActive,
20
21
  isVisibleHere,
22
+ isVisibleTo,
21
23
  loadAll,
22
24
  malformedCount,
23
25
  markManySuperseded,
24
26
  markSuperseded,
27
+ readerFromSid,
25
28
  resolveMemoryTarget,
26
29
  snapshotFiles,
30
+ visibleTo,
27
31
  type Memory,
28
32
  } from "./memory.ts";
29
33
  import { runWriteGate, type GateContext, type WriteCandidate } from "./gates.ts";
@@ -77,8 +81,8 @@ import {
77
81
  onCompacting,
78
82
  } from "./triggers.ts";
79
83
  import { getCurrent, setCurrent } from "./state.ts";
80
- import { resolveRepo, setRepoScope, rememberSessionDir, sessionDir } from "./repokey.ts";
81
- import { readLines } from "./logfmt.ts";
84
+ import { resolveRepo, setRepoScope, rememberSessionDir, sessionDir, sessionDirFirm, bindSessionProvisional } from "./repokey.ts";
85
+ import { parseLine, readLines } from "./logfmt.ts";
82
86
  import { buildCapturePrompt, flattenTranscript, lagSince, parseCandidates, parseModelRef } from "./capture.ts";
83
87
  import { redactSecrets } from "./secrets.ts";
84
88
  import { flattenMemoryText } from "./sanitize.ts";
@@ -278,6 +282,10 @@ const impl = {
278
282
  const setupRoot = ctx?.location?.directory;
279
283
  const liveRoot = setupRoot ?? process.cwd();
280
284
  setRepoScope(setupRoot ? resolveRepo(setupRoot) : null);
285
+ // THIS instance's own workspace. The module scope says who loaded last;
286
+ // this says who I am. An unbound session that calls into THIS instance
287
+ // resolves here — never to another instance's scope (#127, multi-setup).
288
+ const instanceDir = typeof setupRoot === "string" && setupRoot ? setupRoot : undefined;
281
289
 
282
290
  // Character budgets: relevance injection and contextual pulls share the
283
291
  // existing cap; the session-start frontier has its own larger cap. Plugin
@@ -320,6 +328,14 @@ const impl = {
320
328
  const bound = sid ?? getCurrent().sid;
321
329
  return {
322
330
  sessionID: sid,
331
+ // NOTE (re-review): this one lookup is intentionally NON-firm — a
332
+ // provisional binding may supply the gate's verification TREE. The
333
+ // tree is where a referenced file is checked to exist, not who the
334
+ // caller is: "as far as the flow can know" is the right confidence
335
+ // level, and a wrong guess fails a code-reference gate loudly rather
336
+ // than leaking across repositories. Identity itself never resolves
337
+ // through here (readers and stamps use the firm-or-provisional split
338
+ // in repokey/memory); do not mistake this for one.
323
339
  liveRoot: sessionDir(bound) ?? liveRoot,
324
340
  evidenceCalls: evidenceCalls(bound),
325
341
  hasGateCheck: hasGateCheck(bound),
@@ -327,6 +343,30 @@ const impl = {
327
343
  };
328
344
  };
329
345
 
346
+ // Identity of a tool call, captured SYNCHRONOUSLY at the tool's entry —
347
+ // the first await of the call comes after this. The V2 host hands every
348
+ // execute a per-call ToolContext carrying sessionID; the harness and any
349
+ // host that omits it fall back to the ambient current, which is correct
350
+ // exactly because execute.before ran immediately before this tool with
351
+ // no await between (#116's documented fallback). Never re-read the global
352
+ // after an await to learn who is calling (#127).
353
+ const toolIds = (context?: unknown): { sid: string; call: string } => {
354
+ const fromCtx = (context as { sessionID?: unknown; id?: unknown } | undefined)
355
+ ?.sessionID;
356
+ const call = (context as { id?: unknown } | undefined)?.id;
357
+ // Entry binding: a session this instance has never seen is resolved to
358
+ // THIS workspace (provisional — a firm event/API identity still
359
+ // replaces it), so the tool's reader partitions by the repository the
360
+ // call reached, not by the last setup's module scope (#127).
361
+ if (typeof fromCtx === "string" && fromCtx && fromCtx !== "?") {
362
+ bindSessionProvisional(fromCtx, instanceDir);
363
+ }
364
+ return {
365
+ sid: typeof fromCtx === "string" && fromCtx ? fromCtx : getCurrent().sid,
366
+ call: typeof call === "string" && call ? call : getCurrent().call,
367
+ };
368
+ };
369
+
330
370
  // Identity-event race backstop: a resumed session's FIRST turn can write
331
371
  // before the subscription has delivered its execution.started, and the
332
372
  // module-scope fallback is the last setup instance — possibly another
@@ -337,7 +377,7 @@ const impl = {
337
377
  // One-shot: never overwrites an event-bound entry.
338
378
  const bindingSids = new Set<string>();
339
379
  async function bindSessionFromMessages(sid: string | undefined): Promise<void> {
340
- if (!sid || sid === "?" || sessionDir(sid) || bindingSids.has(sid)) return;
380
+ if (!sid || sid === "?" || sessionDirFirm(sid) || bindingSids.has(sid)) return;
341
381
  bindingSids.add(sid);
342
382
  try {
343
383
  const msgs = await ctx.session?.context?.({ sessionID: sid });
@@ -369,7 +409,7 @@ const impl = {
369
409
  const apiBindTried = new Set<string>();
370
410
  const apiBindOrder = new SessionLru(SESSION_CAP, (evicted) => apiBindTried.delete(evicted));
371
411
  async function bindSessionFromApi(sid: string | undefined): Promise<void> {
372
- if (!sid || sid === "?" || sessionDir(sid) || apiBindTried.has(sid)) return;
412
+ if (!sid || sid === "?" || sessionDirFirm(sid) || apiBindTried.has(sid)) return;
373
413
  apiBindTried.add(sid);
374
414
  apiBindOrder.touch(sid);
375
415
  try {
@@ -383,11 +423,16 @@ const impl = {
383
423
  }
384
424
 
385
425
  // Identity must resolve BEFORE a row is stamped or a read is partitioned:
386
- // try the (legacy) message payloads, then the session row.
426
+ // try the (legacy) message payloads, then the session row. A session the
427
+ // host cannot describe (fresh, or a host without the lookup) is bound to
428
+ // THIS instance's workspace — the caller's repository as the flow knows
429
+ // it, and strictly better than an unbound read inheriting the module
430
+ // scope of whoever loaded last (#127's multi-setup residue).
387
431
  async function bindSessionIdentity(sid: string | undefined): Promise<void> {
388
- if (!sid || sid === "?" || sessionDir(sid)) return;
432
+ if (!sid || sid === "?" || sessionDirFirm(sid)) return;
389
433
  await bindSessionFromMessages(sid);
390
- if (!sessionDir(sid)) await bindSessionFromApi(sid);
434
+ if (!sessionDirFirm(sid)) await bindSessionFromApi(sid);
435
+ bindSessionProvisional(sid, instanceDir);
391
436
  }
392
437
 
393
438
  // ---- tools --------------------------------------------------------------
@@ -399,7 +444,8 @@ const impl = {
399
444
  description:
400
445
  "Store a memory after the 4-gate write pipeline validates it (canonical graph, stale refs, dupes). Blocked writes record evidence instead of persisting. Add `kw` — 3-5 aliases, synonyms, verb forms or the literal command a FUTURE session would search with — to make a row findable when the wording differs; keywords are indexed, never injected.",
401
446
  options: direct,
402
- async execute(args): Promise<{ content: string }> {
447
+ async execute(args, context): Promise<{ content: string }> {
448
+ const { sid } = toolIds(context);
403
449
  const candidate: WriteCandidate = {
404
450
  type: args.type,
405
451
  scope: args.scope,
@@ -410,8 +456,8 @@ const impl = {
410
456
  status: args.status,
411
457
  repo: args.global ? "global" : undefined,
412
458
  };
413
- await bindSessionIdentity(getCurrent().sid);
414
- const outcome = await runWriteGate(candidate, gateContext());
459
+ await bindSessionIdentity(sid);
460
+ const outcome = await runWriteGate(candidate, gateContext(sid));
415
461
  if (outcome.action === "promoted") return { content: `Remembered: ${args.type} in ${args.scope}` };
416
462
  if (outcome.action === "collapsed") return { content: `Duplicate ignored: ${args.type}/${args.scope}` };
417
463
  return {
@@ -427,8 +473,10 @@ const impl = {
427
473
  description:
428
474
  "Propose consolidations of near-duplicate settled rows — read-only, nothing is written. Clusters same-scope same-type rows by jaccard, picks the most recently used member as canonical (#42's rule: the row retrieval keeps landing on), and proposes it ONLY when replaying the cluster's own logged reads proves the merged row catches at least as many reads as the best single member did. A cluster with no recorded reads is reported as unmeasured, never merged on resemblance. Resolve a proposal with memory_merge_review; absorbed rows stay recoverable. The merge is deterministic — the canonical row is the survivor's prose plus the absorbed rows' aliases — because this plugin ships no model and a rewritten row cannot be diffed or audited.",
429
475
  options: direct,
430
- async execute(args): Promise<{ content: string }> {
431
- const all = (await loadAll()).filter(isActive).filter(isVisibleHere);
476
+ async execute(args, context): Promise<{ content: string }> {
477
+ const { sid } = toolIds(context);
478
+ const reader = readerFromSid(sid);
479
+ const all = (await loadAll()).filter(isActive).filter((m) => isVisibleTo(m, reader));
432
480
  const rows = args.scope ? all.filter((m) => m.scope === args.scope) : all;
433
481
  const ledger = await readLedger();
434
482
  const use = ledger.byRow;
@@ -452,9 +500,15 @@ const impl = {
452
500
  description:
453
501
  "Initialize repository memory and knowledge graph. Ensures the codebase-memory graph for this repo is indexed (one-shot `cli` spawn; no session MCP needed) and re-derives build/lint/test/typecheck command memories through the write gate, then stores an init stamp keyed on git HEAD. Idempotent: a no-op when the stamp matches HEAD, unless force=true (refresh after a refactor).",
454
502
  options: direct,
455
- async execute(args): Promise<{ content: string }> {
456
- await bindSessionIdentity(getCurrent().sid);
457
- const summary = await runInit({ liveRoot: gateContext().liveRoot, force: args.force, mode: args.mode });
503
+ async execute(args, context): Promise<{ content: string }> {
504
+ const { sid } = toolIds(context);
505
+ await bindSessionIdentity(sid);
506
+ const summary = await runInit({
507
+ liveRoot: gateContext(sid).liveRoot,
508
+ force: args.force,
509
+ mode: args.mode,
510
+ sessionID: sid,
511
+ });
458
512
  return { content: formatInit(summary) };
459
513
  },
460
514
  }));
@@ -464,8 +518,10 @@ const impl = {
464
518
  description:
465
519
  "Look up durable project knowledge — build/test/lint commands, decisions, patterns, preferences, blockers — BEFORE searching the repo or reading files. Use for 'how do I run X', conventions, and past decisions. By scope, type, or free-text query; with no filters it returns the most recent memories.",
466
520
  options: direct,
467
- async execute(args): Promise<{ content: string }> {
468
- let results = (await loadAll()).filter(isActive).filter(isVisibleHere);
521
+ async execute(args, context): Promise<{ content: string }> {
522
+ const { sid, call } = toolIds(context);
523
+ const reader = readerFromSid(sid);
524
+ let results = (await loadAll()).filter(isActive).filter((m) => isVisibleTo(m, reader));
469
525
  if (!results.length) return { content: "No memories found" };
470
526
  const total = results.length;
471
527
  if (args.scope) results = results.filter((m) => m.scope.includes(args.scope!));
@@ -482,15 +538,19 @@ const impl = {
482
538
  if (!limited.length) return { content: "No matching memories" };
483
539
  const openIn = limited.filter((m) => m.status === "open").length;
484
540
  if (openIn > 0) {
485
- const cur = getCurrent();
486
- markFrontierTap(cur.sid, cur.call);
487
- await record("frontier_tapped", {
488
- n_open: openIn,
489
- in_results: limited.length,
490
- turn: firstFrontierTap(cur.sid)?.turn,
491
- });
541
+ markFrontierTap(sid, call);
542
+ await record(
543
+ "frontier_tapped",
544
+ {
545
+ n_open: openIn,
546
+ in_results: limited.length,
547
+ turn: firstFrontierTap(sid)?.turn,
548
+ },
549
+ true,
550
+ sid,
551
+ );
492
552
  }
493
- if (args.query) await noteHits("recall", getCurrent().sid, limited, args.query);
553
+ if (args.query) await noteHits("recall", sid, limited, args.query);
494
554
  return { content: `Found ${results.length} (${total} total)\n\n${limited.map(formatMemory).join("\n")}` };
495
555
  },
496
556
  }));
@@ -500,8 +560,10 @@ const impl = {
500
560
  description:
501
561
  "Update an existing memory (gated like remember; the prior entry is superseded, not erased). `query` selects which row to update: its exact id (ts), a clock fragment (e.g. HH:MM:SS.mmm), or a unique substring of its content. Omitting `query` targets the most recent active row of scope+type. An unmatched or ambiguous `query` fails closed and writes nothing.",
502
562
  options: direct,
503
- async execute(args): Promise<{ content: string }> {
504
- await bindSessionIdentity(getCurrent().sid);
563
+ async execute(args, context): Promise<{ content: string }> {
564
+ const { sid } = toolIds(context);
565
+ await bindSessionIdentity(sid);
566
+ const reader = readerFromSid(sid);
505
567
  // The whole update — resolve, gate, supersede — runs under one
506
568
  // UPDATE-ORDER lock. Without it, two concurrent updates that both
507
569
  // resolved the same still-active target both promoted and both
@@ -520,7 +582,7 @@ const impl = {
520
582
  join(memoryRoot(), "update-order"),
521
583
  async () => {
522
584
  const prior = (await loadAll()).filter(
523
- (m) => m.scope === args.scope && m.type === args.type && isActive(m) && isVisibleHere(m),
585
+ (m) => m.scope === args.scope && m.type === args.type && isActive(m) && isVisibleTo(m, reader),
524
586
  );
525
587
  // Resolve the row BEFORE the gate: an update that cannot identify its
526
588
  // target must write nothing, rather than silently superseding whichever
@@ -543,7 +605,7 @@ const impl = {
543
605
  const target = resolved.target;
544
606
  const outcome = await runWriteGate(
545
607
  { type: args.type, scope: args.scope, content: args.content, kw: args.kw, status: args.status },
546
- { ...gateContext(), supersedesTs: target.ts },
608
+ { ...gateContext(sid), supersedesTs: target.ts },
547
609
  );
548
610
  if (outcome.action === "promoted" && outcome.ts && target) {
549
611
  await markSuperseded(target.ts, {
@@ -581,8 +643,9 @@ const impl = {
581
643
  description:
582
644
  "Delete memories by scope and type. Snapshots first, logs the reason for audit, never touches a repo.",
583
645
  options: direct,
584
- async execute(args): Promise<{ content: string }> {
585
- const res = await pruneMemory(args.scope, args.type, args.reason);
646
+ async execute(args, context): Promise<{ content: string }> {
647
+ const { sid } = toolIds(context);
648
+ const res = await pruneMemory(args.scope, args.type, args.reason, sid);
586
649
  if (!res.deleted.length) return { content: `No memories found for ${args.type} in ${args.scope}` };
587
650
  return { content: `Deleted ${res.deleted.length} ${args.type} memory(s) from ${args.scope}. Audit: ${res.audit}` };
588
651
  },
@@ -592,8 +655,10 @@ const impl = {
592
655
  name: "memory_list",
593
656
  description: "List memory scopes and types for discovery.",
594
657
  options: direct,
595
- async execute(): Promise<{ content: string }> {
596
- const mems = (await loadAll()).filter(isActive).filter(isVisibleHere);
658
+ async execute(_args, context): Promise<{ content: string }> {
659
+ const { sid } = toolIds(context);
660
+ const reader = readerFromSid(sid);
661
+ const mems = (await loadAll()).filter(isActive).filter((m) => isVisibleTo(m, reader));
597
662
  if (!mems.length) return { content: "No memories found" };
598
663
  const scopes = new Map<string, number>();
599
664
  const types = new Map<string, number>();
@@ -649,9 +714,22 @@ const impl = {
649
714
  name: "memory_evidence",
650
715
  description: "Read captured evidence (data only) for a date, optionally filtered by event.",
651
716
  options: direct,
652
- async execute(args): Promise<{ content: string }> {
717
+ async execute(args, context): Promise<{ content: string }> {
718
+ const { sid } = toolIds(context);
719
+ const reader = readerFromSid(sid);
653
720
  const file = join(evidenceDir(), `${args.date || dateStr()}.logfmt`);
654
721
  let lines = await readLines(file);
722
+ // Data partitions too (#131's ownership rule, applied to evidence):
723
+ // a line stamped to another repository is not this session's data,
724
+ // and a line a NAMED session wrote while unresolved is private to
725
+ // that session — the caller's sid is what the private branch
726
+ // matches against (#128 re-review).
727
+ if (reader.kind !== "admin") {
728
+ lines = lines.filter((l) => {
729
+ const fields = parseLine(l);
730
+ return !fields || evidenceVisibleTo(fields, reader, sid);
731
+ });
732
+ }
655
733
  if (args.ev) lines = lines.filter((l) => l.includes(`ev=${args.ev}`));
656
734
  if (!lines.length) return { content: "No evidence" };
657
735
  const limit = args.limit || 50;
@@ -735,13 +813,17 @@ const impl = {
735
813
  description:
736
814
  "Import memories from a JSONL export (see memory_export). Every row goes through the same 4-gate write pipeline as memory_remember (tagged `import`, original tags preserved), so duplicates collapse and ungrounded rows are blocked exactly as usual — those are normal tallied outcomes, not errors. Malformed lines are skipped and counted. `file` must be inside the memory root — copy the export there first. Frontier policy: status:\"open\" exempts a row from ref grounding, so it requires a memory_export header and cannot claim global scope; imported repo stamps are kept only when they match the importing session's repo, otherwise the importing repo is stamped. A stamped open row is downgraded when there is no current repo scope to verify it. Imported content is unverified by construction: injected rows surface a `[via import]` provenance marker.",
737
815
  options: direct,
738
- async execute(args): Promise<{ content: string }> {
816
+ async execute(args, context): Promise<{ content: string }> {
817
+ const { sid } = toolIds(context);
739
818
  try {
740
- const t = await importMemories(args.file, (c) =>
741
- runWriteGate(
742
- { ...c, tags: [...new Set([...(c.tags ?? []), "import"])] },
743
- gateContext(),
744
- ),
819
+ const t = await importMemories(
820
+ args.file,
821
+ (c) =>
822
+ runWriteGate(
823
+ { ...c, tags: [...new Set([...(c.tags ?? []), "import"])] },
824
+ gateContext(sid),
825
+ ),
826
+ sid,
745
827
  );
746
828
  return {
747
829
  content:
@@ -764,10 +846,11 @@ const impl = {
764
846
  description:
765
847
  "Retire stale open threads (status=open older than olderThanDays) by superseding them — never deleting; rows stay recoverable via memory_undo. DRY RUN BY DEFAULT: without an explicit dryRun=false this only LISTS what would retire and mutates nothing (fail-closed). A real run snapshots every affected file before the first mutation.",
766
848
  options: direct,
767
- async execute(args): Promise<{ content: string }> {
849
+ async execute(args, context): Promise<{ content: string }> {
850
+ const { sid } = toolIds(context);
768
851
  const days = Number(args.olderThanDays) > 0 ? Number(args.olderThanDays) : 14;
769
852
  const dryRun = args.dryRun !== false; // only an explicit false mutates
770
- const stale = await findStaleOpen(days);
853
+ const stale = await findStaleOpen(days, sid);
771
854
  if (!stale.length) {
772
855
  return { content: `No active open threads older than ${days} days.` };
773
856
  }
@@ -824,9 +907,9 @@ const impl = {
824
907
  description:
825
908
  "Plain-text memory report for chat clients (desktop/web/IDE), same sections as the terminal /memory panel: CONTEXT (this session's injected block, budget use, cumulative ride and abstentions), CACHE (plain-language cache receipts: bust count, and the provider-reported share of prompt tokens served from cache — the proof that memory never mutates your prefix), the block verbatim, recent blocked writes with gate reasons, and store stats. Reads only — no model call.",
826
909
  options: direct,
827
- async execute(): Promise<{ content: string }> {
910
+ async execute(_args, context): Promise<{ content: string }> {
828
911
  // In-process truth: the live epoch + ledger, fresher than any file.
829
- const sid = getCurrent().sid;
912
+ const sid = toolIds(context).sid;
830
913
  const status = sid === "?" ? null : await buildPayload(sid);
831
914
  const all = await loadAll();
832
915
  const act = all.filter(isActive);
@@ -933,8 +1016,14 @@ const impl = {
933
1016
  // at the injection decision on every model request. The latter keeps
934
1017
  // removals fail-closed: an out-of-band redaction or a block during a tool
935
1018
  // loop cannot ride one more request waiting for another user prompt.
936
- const injectableRows = async (): Promise<Memory[]> =>
937
- (await loadAll()).filter((m) => isActive(m) && isVisibleHere(m));
1019
+ // The caller's sid is resolved to an immutable Reader BEFORE the store
1020
+ // read (#127): while loadAll awaits, another session's hooks may dispatch
1021
+ // and move the ambient current; filtering with THAT leaks the other
1022
+ // session's repo into this one's system prompt.
1023
+ const injectableRows = async (sid?: string): Promise<Memory[]> => {
1024
+ const reader = readerFromSid(sid);
1025
+ return (await loadAll()).filter((m) => isActive(m) && isVisibleTo(m, reader));
1026
+ };
938
1027
  // Use ledger (#42). `query` is what retrieval was asked with; what gets
939
1028
  // stored is the vocabulary the answer SHARES with the query, taken from the
940
1029
  // memory side, so the ledger can never become a copy of user prompts.
@@ -947,7 +1036,7 @@ const impl = {
947
1036
  };
948
1037
  const refreshEpoch = async (sid: string, rows?: Memory[]): Promise<void> => {
949
1038
  if (!latestPrompt.has(sid)) return;
950
- const mems = rows ?? await injectableRows();
1039
+ const mems = rows ?? (await injectableRows(sid));
951
1040
  const version = await storeVersion(mems);
952
1041
  const cached = epoch.get(sid);
953
1042
  if (cached?.version === version) return;
@@ -1016,6 +1105,13 @@ const impl = {
1016
1105
  args: event?.input,
1017
1106
  };
1018
1107
  setCurrent(input);
1108
+ // Evidence lines written below stamp the RECORDING repository. Bind
1109
+ // an unbound caller to this instance first (SYNC provisional; the
1110
+ // prompt hook / events bind firmly in production) so a tool_result
1111
+ // can never carry another instance's stamp (#127).
1112
+ if (typeof event?.sessionID === "string") {
1113
+ bindSessionProvisional(event.sessionID, instanceDir);
1114
+ }
1019
1115
  const out = { output: resultText(event?.result), metadata: resultMeta(event?.result) };
1020
1116
  await afterTool(input, out);
1021
1117
  const pulled = await contextualPull(input, out as { output?: unknown }, budget, await useSignals());
@@ -1031,11 +1127,21 @@ const impl = {
1031
1127
  // Tiny system digest + open-thread frontier block, injected into the system prompt.
1032
1128
  await ctx.session?.hook("context", (event: any) =>
1033
1129
  guarded("session.context (systemDigest)", async () => {
1034
- // Route store reads in this hook through the right session's scope.
1130
+ // Route store reads in this hook through the right session's scope:
1131
+ // the sid is captured from the event BEFORE any await and carried
1132
+ // explicitly — the global current set here is legacy bookkeeping
1133
+ // only, never the identity this flow filters with (#127).
1134
+ const sid = typeof event?.sessionID === "string" ? event.sessionID : undefined;
1035
1135
  setCurrent({ sessionID: event?.sessionID });
1036
- const sid = event?.sessionID;
1037
1136
  if (typeof sid === "string") sessions.touch(sid);
1038
- const mems = await injectableRows();
1137
+ // Resolve WHOSE repository this injection reads before the store
1138
+ // read below: an unbound session would otherwise fall to global-only
1139
+ // and silently lose its own frontier rows. SYNC provisional bind to
1140
+ // this instance's workspace — the prompt hook (or an event) has
1141
+ // already bound firmly in production, so no host lookup belongs in
1142
+ // this hot path (#127).
1143
+ if (typeof sid === "string") bindSessionProvisional(sid, instanceDir);
1144
+ const mems = await injectableRows(sid);
1039
1145
  if (typeof sid === "string") await refreshEpoch(sid, mems);
1040
1146
  const parts: string[] = [];
1041
1147
  await systemDigest(
@@ -1093,20 +1199,25 @@ const impl = {
1093
1199
  // while it still exists, BEFORE the summarizer replaces it.
1094
1200
  await ctx.session?.hook("compaction", (event: any) =>
1095
1201
  guarded("session.compaction (onCompacting)", async () => {
1202
+ const sid = typeof event?.sessionID === "string" ? event.sessionID : undefined;
1096
1203
  setCurrent({ sessionID: event?.sessionID });
1204
+ // The anchor read and the capture pass below partition by the session's
1205
+ // repository; SYNC provisional bind only — a host lookup from this
1206
+ // hook would violate the zero-token promise (#127, see capture).
1207
+ if (typeof sid === "string") bindSessionProvisional(sid, instanceDir);
1097
1208
  await onCompacting({ sessionID: event?.sessionID });
1098
1209
  if (typeof event?.sessionID === "string") {
1099
1210
  epoch.delete(event.sessionID);
1100
1211
  latestPrompt.delete(event.sessionID);
1101
1212
  }
1102
- const anchor = await compactionAnchor();
1213
+ const anchor = await compactionAnchor(12, sid);
1103
1214
  if (anchor) event?.system?.push?.({ type: "text", text: anchor });
1104
1215
  // Fire-and-forget: a capture model call must never delay the compaction
1105
1216
  // the user is waiting for, and failures stay inside the guarded path.
1106
1217
  // The payload's own messages ride along so the mining sees the
1107
1218
  // pre-compaction transcript even if the store moves under it.
1108
- if (onCompactCapture && typeof event?.sessionID === "string") {
1109
- onCompactCapture(event.sessionID, event.messages);
1219
+ if (onCompactCapture && sid) {
1220
+ onCompactCapture(sid, event.messages);
1110
1221
  }
1111
1222
  }),
1112
1223
  );
@@ -1241,6 +1352,13 @@ const impl = {
1241
1352
  // move current, so the gate context and the persisted rows thread
1242
1353
  // `sid` explicitly instead of reading it back from the global (#116).
1243
1354
  setCurrent({ sessionID: sid });
1355
+ // The capture's dedup reads and the rows it writes partition by the
1356
+ // CAPTURED session's repository — an unbound sid would otherwise
1357
+ // read global-only and mine duplicates into the store (#127; in
1358
+ // production the prompt hook already bound it firmly, so this is a
1359
+ // no-op there). SYNC only: a lookup call here would break the
1360
+ // zero-token promise of the capture tests.
1361
+ bindSessionProvisional(sid, instanceDir);
1244
1362
  let transcript = seeded;
1245
1363
  let msgs = seededMsgs;
1246
1364
  if (transcript.length < 200) {
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 { isVisibleHere, loadAll, markSuperseded } from "./memory.ts";
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
- const mems = (await loadAll()).filter((m) => !m.superseded_by && isVisibleHere(m));
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 {