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/src/index.ts CHANGED
@@ -12,18 +12,22 @@
12
12
  // helper modules.
13
13
  import type { Cleanup, Plugin } from "@opencode/plugin/promise/plugin";
14
14
  import { basename, join } from "node:path";
15
- import { evidenceDir, frontierBudget, injectBudget, memoryRoot, dateStr } from "./config.ts";
15
+ import { frontierBudget, injectBudget, memoryRoot } from "./config.ts";
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";
@@ -32,7 +36,7 @@ import { pruneMemory } from "./prune.ts";
32
36
  import { exportMemories, findStaleOpen, importMemories } from "./portable.ts";
33
37
  import { listSnapshots, restoreSnapshot } from "./undo.ts";
34
38
  import { SESSION_CAP, SessionLru } from "./sessions.ts";
35
- import { record, recordCaptureLag } from "./evidence.ts";
39
+ import { evidenceFileFor, record, recordCaptureLag } from "./evidence.ts";
36
40
  import { proposeConsolidations, renderProposals } from "./consolidate.ts";
37
41
  import { readReads } from "./hits.ts";
38
42
  import {
@@ -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,31 @@ 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 }> {
653
- const file = join(evidenceDir(), `${args.date || dateStr()}.logfmt`);
717
+ async execute(args, context): Promise<{ content: string }> {
718
+ const { sid } = toolIds(context);
719
+ const reader = readerFromSid(sid);
720
+ // #130: the ONE path the schema-validated date can resolve to —
721
+ // a real calendar day inside the evidence dir, never a traversal
722
+ // into the raw store or the filesystem beyond it.
723
+ const file = evidenceFileFor(args.date);
724
+ if (!file) {
725
+ return {
726
+ content:
727
+ "memory_evidence blocked: date must be a real YYYY-MM-DD calendar date — nothing was read.",
728
+ };
729
+ }
654
730
  let lines = await readLines(file);
731
+ // Data partitions too (#131's ownership rule, applied to evidence):
732
+ // a line stamped to another repository is not this session's data,
733
+ // and a line a NAMED session wrote while unresolved is private to
734
+ // that session — the caller's sid is what the private branch
735
+ // matches against (#128 re-review).
736
+ if (reader.kind !== "admin") {
737
+ lines = lines.filter((l) => {
738
+ const fields = parseLine(l);
739
+ return !fields || evidenceVisibleTo(fields, reader, sid);
740
+ });
741
+ }
655
742
  if (args.ev) lines = lines.filter((l) => l.includes(`ev=${args.ev}`));
656
743
  if (!lines.length) return { content: "No evidence" };
657
744
  const limit = args.limit || 50;
@@ -662,54 +749,126 @@ const impl = {
662
749
  editor.add(validated(MergeReviewArgs, {
663
750
  name: "memory_merge_review",
664
751
  description:
665
- "Resolve an open merge/review gate non-destructively: mark the loser as superseded_by the survivor, and clear any supersession the survivor itself carries so the canonical row stays recallable. Both rows stay active data (the loser is recoverable via memory_undo); nothing is deleted. Fails closed (no partial apply) when the reason or the survivor id is missing, the survivor id names no row in the store, or the loser is already superseded or is the survivor itself.",
752
+ "Resolve an open merge/review gate non-destructively: mark the loser as superseded_by the survivor, and clear any supersession the survivor itself carries so the canonical row stays recallable. Both rows stay active data (the loser is recoverable via memory_undo); nothing is deleted. A session may merge exactly the rows it may read: global rows are mergeable from anywhere, but a row belonging to another repository is refused in either seat. Fails closed (no partial apply) when the reason or the survivor id is missing, the survivor id names no row in the store, the loser is already superseded or is the survivor itself, or either seat names a foreign repository's row.",
666
753
  options: direct,
667
- async execute(args): Promise<{ content: string }> {
754
+ async execute(args, context): Promise<{ content: string }> {
755
+ const { sid } = toolIds(context);
668
756
  if (!args.loser || !args.survivor || !args.reason) {
669
757
  return { content: "merge_review blocked: loser, survivor, and reason are all required (fail-closed)." };
670
758
  }
671
- // Probed: marking with a survivor id that names no row retired the
672
- // loser toward a pointer to nothing (the scope ended with zero
673
- // active rows) while the response declared it canonical. Validate
674
- // BEFORE touching the loser — a resolution must never retire real
675
- // data for a phantom. (Same-row input would mark and then revive
676
- // the same row: a silent no-op that reports full success.)
677
759
  if (args.loser === args.survivor) {
760
+ // (Same-row input would mark and then revive the same row: a
761
+ // silent no-op that reports full success.)
678
762
  return { content: "merge_review blocked: loser and survivor are the same row — nothing to resolve. No evidence written." };
679
763
  }
680
- if (!(await loadAll()).some((m) => m.ts === args.survivor)) {
681
- return { content: `merge_review blocked: survivor ${args.survivor} does not exist in the store — nothing to resolve. No evidence written.` };
682
- }
683
- const ok = await markSuperseded(args.loser, {
684
- superseded_by: args.survivor,
685
- reason: args.reason,
686
- symbol: args.loser,
687
- from: args.loser,
688
- to: args.survivor,
689
- });
690
- if (!ok) {
691
- return { content: "merge_review: loser not found or already superseded — nothing to resolve. No evidence written." };
764
+ // A row id is a pointer, not authority (#131): resolving and
765
+ // authorizing BOTH seats happens against the caller's Reader —
766
+ // captured at entry, never re-read after an await (#127) — and the
767
+ // whole resolve/check/mutate runs under the same update-order lock
768
+ // memory_update serializes on (#125), so the authorization is
769
+ // revalidated under the mutation lock instead of against a snapshot
770
+ // a concurrent update could have replaced. Acquisition order is
771
+ // always update-order then store-file locks, never the reverse, so
772
+ // this cannot deadlock against a plain writer; on timeout it fails
773
+ // closed with nothing written.
774
+ const reader = readerFromSid(sid);
775
+ // Where a throw lands decides what is true to say: before the
776
+ // mutation nothing was written (the documented fail-closed
777
+ // contract); AFTER markSuperseded the loser IS retired on disk and
778
+ // claiming "nothing was done" is a lie (review probe 5).
779
+ let mutated = false;
780
+ try {
781
+ return await withStoreLock(
782
+ join(memoryRoot(), "update-order"),
783
+ async () => {
784
+ const all = await loadAll();
785
+ const survivorRow = all.find((m) => m.ts === args.survivor);
786
+ // Probed: marking with a survivor id that names no row retired
787
+ // the loser toward a pointer to nothing (the scope ended with
788
+ // zero active rows) while the response declared it canonical.
789
+ // Validate BEFORE touching the loser — a resolution must never
790
+ // retire real data for a phantom.
791
+ if (!survivorRow) {
792
+ return { content: `merge_review blocked: survivor ${args.survivor} does not exist in the store — nothing to resolve. No evidence written.` };
793
+ }
794
+ const loserRow = all.find((m) => m.ts === args.loser);
795
+ // Visibility is the authorization contract (#131): a session
796
+ // may merge exactly the rows it may read. Global and legacy
797
+ // unstamped rows are visible everywhere and therefore
798
+ // mergeable from anywhere — stated here, not granted
799
+ // implicitly by store-wide reach. A foreign row in EITHER
800
+ // seat — including an attempt to revive another repository's
801
+ // superseded survivor — is refused before any mutation.
802
+ if (loserRow && !isVisibleTo(loserRow, reader)) {
803
+ return { content: "merge_review blocked: the loser belongs to another repository — this session may not retire it. Nothing was done. No evidence written." };
804
+ }
805
+ if (!isVisibleTo(survivorRow, reader)) {
806
+ return { content: "merge_review blocked: the survivor belongs to another repository — this session may not promote or revive it. Nothing was done. No evidence written." };
807
+ }
808
+ const ok = await markSuperseded(args.loser, {
809
+ superseded_by: args.survivor,
810
+ reason: args.reason,
811
+ symbol: args.loser,
812
+ from: args.loser,
813
+ to: args.survivor,
814
+ });
815
+ if (!ok) {
816
+ return { content: "merge_review: loser not found or already superseded — nothing to resolve. No evidence written." };
817
+ }
818
+ mutated = true;
819
+ // The survivor may itself have been superseded earlier (e.g. by
820
+ // a row this very call just made the loser). Declaring it
821
+ // canonical has to make it recallable, so clear its own marker.
822
+ const revived = await clearSuperseded(args.survivor);
823
+ // The response has always claimed "Evidence recorded" — now it
824
+ // is true, and it names the session the merge ran FOR (#121's
825
+ // residue on this line). The host tool_result hook covers
826
+ // grep/read/edit/shell only, so a merge used to leave zero
827
+ // trace: which reviewer decision, on which reason, reviving
828
+ // what — unauditable.
829
+ await record(
830
+ "merge_resolved",
831
+ {
832
+ loser: args.loser,
833
+ survivor: args.survivor,
834
+ revived,
835
+ reason: args.reason,
836
+ },
837
+ true,
838
+ sid,
839
+ );
840
+ return {
841
+ content:
842
+ `Resolved merge: ${args.survivor} is canonical; ${args.loser} superseded (recoverable via memory_undo). ` +
843
+ (revived ? `Survivor's own supersession cleared, it is active again. ` : "") +
844
+ `Evidence recorded for reason='${args.reason}'.`,
845
+ };
846
+ },
847
+ {
848
+ onTimeout: "fail",
849
+ onEvent: (event, waitedMs) => {
850
+ void record("store_lock", { event, waited_ms: waitedMs, op: "merge" });
851
+ },
852
+ },
853
+ );
854
+ } catch (err) {
855
+ // Before mutation this is the fail-closed lock contract: nothing
856
+ // written. After markSuperseded succeeded the loser IS retired —
857
+ // the honest report names the completed mutation and the failed
858
+ // follow-up (evidence/revive), not a blanket "nothing was done".
859
+ if (!mutated) {
860
+ return {
861
+ content: "merge_review blocked: the store was busy past the lock budget — nothing was done. Retry.",
862
+ };
863
+ }
864
+ const why = err instanceof Error ? err.message : String(err);
865
+ return {
866
+ content:
867
+ `merge_review PARTIAL: ${args.loser} IS retired on disk (superseded_by ${args.survivor}; ` +
868
+ `recoverable via memory_undo) but a post-mutation step failed: ${why}. ` +
869
+ `The evidence line may be missing; re-running reports the loser already superseded.`,
870
+ };
692
871
  }
693
- // The survivor may itself have been superseded earlier (e.g. by a row
694
- // this very call just made the loser). Declaring it canonical has to
695
- // make it recallable, so clear its own marker too.
696
- const revived = await clearSuperseded(args.survivor);
697
- // The response has always claimed "Evidence recorded" — now it is
698
- // true. The host tool_result hook covers grep/read/edit/shell only,
699
- // so a merge used to leave zero trace: which reviewer decision, on
700
- // which reason, reviving what — unauditable.
701
- await record("merge_resolved", {
702
- loser: args.loser,
703
- survivor: args.survivor,
704
- revived,
705
- reason: args.reason,
706
- });
707
- return {
708
- content:
709
- `Resolved merge: ${args.survivor} is canonical; ${args.loser} superseded (recoverable via memory_undo). ` +
710
- (revived ? `Survivor's own supersession cleared, it is active again. ` : "") +
711
- `Evidence recorded for reason='${args.reason}'.`,
712
- };
713
872
  },
714
873
  }));
715
874
 
@@ -735,13 +894,17 @@ const impl = {
735
894
  description:
736
895
  "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
896
  options: direct,
738
- async execute(args): Promise<{ content: string }> {
897
+ async execute(args, context): Promise<{ content: string }> {
898
+ const { sid } = toolIds(context);
739
899
  try {
740
- const t = await importMemories(args.file, (c) =>
741
- runWriteGate(
742
- { ...c, tags: [...new Set([...(c.tags ?? []), "import"])] },
743
- gateContext(),
744
- ),
900
+ const t = await importMemories(
901
+ args.file,
902
+ (c) =>
903
+ runWriteGate(
904
+ { ...c, tags: [...new Set([...(c.tags ?? []), "import"])] },
905
+ gateContext(sid),
906
+ ),
907
+ sid,
745
908
  );
746
909
  return {
747
910
  content:
@@ -764,10 +927,11 @@ const impl = {
764
927
  description:
765
928
  "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
929
  options: direct,
767
- async execute(args): Promise<{ content: string }> {
930
+ async execute(args, context): Promise<{ content: string }> {
931
+ const { sid } = toolIds(context);
768
932
  const days = Number(args.olderThanDays) > 0 ? Number(args.olderThanDays) : 14;
769
933
  const dryRun = args.dryRun !== false; // only an explicit false mutates
770
- const stale = await findStaleOpen(days);
934
+ const stale = await findStaleOpen(days, sid);
771
935
  if (!stale.length) {
772
936
  return { content: `No active open threads older than ${days} days.` };
773
937
  }
@@ -824,9 +988,9 @@ const impl = {
824
988
  description:
825
989
  "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
990
  options: direct,
827
- async execute(): Promise<{ content: string }> {
991
+ async execute(_args, context): Promise<{ content: string }> {
828
992
  // In-process truth: the live epoch + ledger, fresher than any file.
829
- const sid = getCurrent().sid;
993
+ const sid = toolIds(context).sid;
830
994
  const status = sid === "?" ? null : await buildPayload(sid);
831
995
  const all = await loadAll();
832
996
  const act = all.filter(isActive);
@@ -933,8 +1097,14 @@ const impl = {
933
1097
  // at the injection decision on every model request. The latter keeps
934
1098
  // removals fail-closed: an out-of-band redaction or a block during a tool
935
1099
  // 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));
1100
+ // The caller's sid is resolved to an immutable Reader BEFORE the store
1101
+ // read (#127): while loadAll awaits, another session's hooks may dispatch
1102
+ // and move the ambient current; filtering with THAT leaks the other
1103
+ // session's repo into this one's system prompt.
1104
+ const injectableRows = async (sid?: string): Promise<Memory[]> => {
1105
+ const reader = readerFromSid(sid);
1106
+ return (await loadAll()).filter((m) => isActive(m) && isVisibleTo(m, reader));
1107
+ };
938
1108
  // Use ledger (#42). `query` is what retrieval was asked with; what gets
939
1109
  // stored is the vocabulary the answer SHARES with the query, taken from the
940
1110
  // memory side, so the ledger can never become a copy of user prompts.
@@ -947,7 +1117,7 @@ const impl = {
947
1117
  };
948
1118
  const refreshEpoch = async (sid: string, rows?: Memory[]): Promise<void> => {
949
1119
  if (!latestPrompt.has(sid)) return;
950
- const mems = rows ?? await injectableRows();
1120
+ const mems = rows ?? (await injectableRows(sid));
951
1121
  const version = await storeVersion(mems);
952
1122
  const cached = epoch.get(sid);
953
1123
  if (cached?.version === version) return;
@@ -1016,6 +1186,13 @@ const impl = {
1016
1186
  args: event?.input,
1017
1187
  };
1018
1188
  setCurrent(input);
1189
+ // Evidence lines written below stamp the RECORDING repository. Bind
1190
+ // an unbound caller to this instance first (SYNC provisional; the
1191
+ // prompt hook / events bind firmly in production) so a tool_result
1192
+ // can never carry another instance's stamp (#127).
1193
+ if (typeof event?.sessionID === "string") {
1194
+ bindSessionProvisional(event.sessionID, instanceDir);
1195
+ }
1019
1196
  const out = { output: resultText(event?.result), metadata: resultMeta(event?.result) };
1020
1197
  await afterTool(input, out);
1021
1198
  const pulled = await contextualPull(input, out as { output?: unknown }, budget, await useSignals());
@@ -1031,11 +1208,21 @@ const impl = {
1031
1208
  // Tiny system digest + open-thread frontier block, injected into the system prompt.
1032
1209
  await ctx.session?.hook("context", (event: any) =>
1033
1210
  guarded("session.context (systemDigest)", async () => {
1034
- // Route store reads in this hook through the right session's scope.
1211
+ // Route store reads in this hook through the right session's scope:
1212
+ // the sid is captured from the event BEFORE any await and carried
1213
+ // explicitly — the global current set here is legacy bookkeeping
1214
+ // only, never the identity this flow filters with (#127).
1215
+ const sid = typeof event?.sessionID === "string" ? event.sessionID : undefined;
1035
1216
  setCurrent({ sessionID: event?.sessionID });
1036
- const sid = event?.sessionID;
1037
1217
  if (typeof sid === "string") sessions.touch(sid);
1038
- const mems = await injectableRows();
1218
+ // Resolve WHOSE repository this injection reads before the store
1219
+ // read below: an unbound session would otherwise fall to global-only
1220
+ // and silently lose its own frontier rows. SYNC provisional bind to
1221
+ // this instance's workspace — the prompt hook (or an event) has
1222
+ // already bound firmly in production, so no host lookup belongs in
1223
+ // this hot path (#127).
1224
+ if (typeof sid === "string") bindSessionProvisional(sid, instanceDir);
1225
+ const mems = await injectableRows(sid);
1039
1226
  if (typeof sid === "string") await refreshEpoch(sid, mems);
1040
1227
  const parts: string[] = [];
1041
1228
  await systemDigest(
@@ -1093,20 +1280,25 @@ const impl = {
1093
1280
  // while it still exists, BEFORE the summarizer replaces it.
1094
1281
  await ctx.session?.hook("compaction", (event: any) =>
1095
1282
  guarded("session.compaction (onCompacting)", async () => {
1283
+ const sid = typeof event?.sessionID === "string" ? event.sessionID : undefined;
1096
1284
  setCurrent({ sessionID: event?.sessionID });
1285
+ // The anchor read and the capture pass below partition by the session's
1286
+ // repository; SYNC provisional bind only — a host lookup from this
1287
+ // hook would violate the zero-token promise (#127, see capture).
1288
+ if (typeof sid === "string") bindSessionProvisional(sid, instanceDir);
1097
1289
  await onCompacting({ sessionID: event?.sessionID });
1098
1290
  if (typeof event?.sessionID === "string") {
1099
1291
  epoch.delete(event.sessionID);
1100
1292
  latestPrompt.delete(event.sessionID);
1101
1293
  }
1102
- const anchor = await compactionAnchor();
1294
+ const anchor = await compactionAnchor(12, sid);
1103
1295
  if (anchor) event?.system?.push?.({ type: "text", text: anchor });
1104
1296
  // Fire-and-forget: a capture model call must never delay the compaction
1105
1297
  // the user is waiting for, and failures stay inside the guarded path.
1106
1298
  // The payload's own messages ride along so the mining sees the
1107
1299
  // pre-compaction transcript even if the store moves under it.
1108
- if (onCompactCapture && typeof event?.sessionID === "string") {
1109
- onCompactCapture(event.sessionID, event.messages);
1300
+ if (onCompactCapture && sid) {
1301
+ onCompactCapture(sid, event.messages);
1110
1302
  }
1111
1303
  }),
1112
1304
  );
@@ -1241,6 +1433,13 @@ const impl = {
1241
1433
  // move current, so the gate context and the persisted rows thread
1242
1434
  // `sid` explicitly instead of reading it back from the global (#116).
1243
1435
  setCurrent({ sessionID: sid });
1436
+ // The capture's dedup reads and the rows it writes partition by the
1437
+ // CAPTURED session's repository — an unbound sid would otherwise
1438
+ // read global-only and mine duplicates into the store (#127; in
1439
+ // production the prompt hook already bound it firmly, so this is a
1440
+ // no-op there). SYNC only: a lookup call here would break the
1441
+ // zero-token promise of the capture tests.
1442
+ bindSessionProvisional(sid, instanceDir);
1244
1443
  let transcript = seeded;
1245
1444
  let msgs = seededMsgs;
1246
1445
  if (transcript.length < 200) {
@@ -1255,7 +1454,12 @@ const impl = {
1255
1454
  const lagMs = lagSince(msgs);
1256
1455
  const out = await generateApi.text({
1257
1456
  model: modelRef,
1258
- prompt: buildCapturePrompt(transcript.slice(-8000), captureMax),
1457
+ // Redact the COMPLETE transcript, THEN apply the character budget
1458
+ // (#132). Cropping first can start the window INSIDE a credential:
1459
+ // a PEM body whose BEGIN marker fell off, or a token whose prefix
1460
+ // fell off, matches no pattern — buildCapturePrompt's own scrub
1461
+ // (kept, defense in depth) cannot recognize a fragment.
1462
+ prompt: buildCapturePrompt(redactSecrets(transcript).slice(-8000), captureMax),
1259
1463
  });
1260
1464
  const text = typeof out === "string" ? out : out?.text ?? "";
1261
1465
  const candidates = parseCandidates(text, captureMax);