opencode-self-improvement 0.14.17 → 0.14.19

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
@@ -3,22 +3,17 @@
3
3
  // tiny-digest injection with deterministic memory-first context and
4
4
  // contextual pull, and snapshot/rollback.
5
5
  //
6
- // V2 port: registers tools via `ctx.tool.transform` (JSON Schema), mirrors the
7
- // V1 hooks onto the OpenCode V2 session/tool hook API, and registers the
8
- // /repo-init command via `ctx.command.transform`. The plugin contract is a
9
- // default export object `{ id, setup(ctx) }` (OpenCode >= 2.0), pinned at
10
- // compile time against the real SDK type (`@opencode/plugin`, type-only — see
11
- // the note on `plugin` below). All business logic still lives in the decoupled
12
- // helper modules.
6
+ // Registers tools via `ctx.tool.transform` (JSON Schema) and hooks via the
7
+ // OpenCode V2 session/tool API. Slash commands are installed as markdown by
8
+ // src/command.ts. The default export `{ id, setup(ctx) }` is checked against
9
+ // the SDK's Plugin type using a type-only import (see the note on `plugin`).
13
10
  import type { Cleanup, Plugin } from "@opencode/plugin/promise/plugin";
14
11
  import { basename, join } from "node:path";
15
12
  import { frontierBudget, injectBudget, memoryRoot } from "./config.ts";
16
- import { STATUSES, TYPES } from "./types.ts";
17
13
  import {
18
14
  clearSuperseded,
19
15
  evidenceVisibleTo,
20
16
  isActive,
21
- isVisibleHere,
22
17
  isVisibleTo,
23
18
  loadAll,
24
19
  malformedCount,
@@ -28,10 +23,9 @@ import {
28
23
  resolveMemoryTarget,
29
24
  snapshotFiles,
30
25
  unresolvedWriteMessage,
31
- visibleTo,
32
26
  type Memory,
33
27
  } from "./memory.ts";
34
- import { runWriteGate, type GateContext, type WriteCandidate } from "./gates.ts";
28
+ import { auditCaveat, runWriteGate, sameStrList, type GateContext, type WriteCandidate } from "./gates.ts";
35
29
  import { withStoreLock } from "./lock.ts";
36
30
  import { pruneMemory } from "./prune.ts";
37
31
  import { exportMemories, findStaleOpen, importMemories } from "./portable.ts";
@@ -41,39 +35,29 @@ import { evidenceFileFor, record, recordCaptureLag } from "./evidence.ts";
41
35
  import { proposeConsolidations, renderProposals } from "./consolidate.ts";
42
36
  import { readReads } from "./hits.ts";
43
37
  import {
44
- capToBudget,
45
38
  compactionAnchor,
46
39
  contextualPull,
47
40
  formatMemory,
48
- injectedRows,
49
41
  pullQuery,
50
- selectRelevant,
51
42
  sharedTerms,
52
- storeVersion,
53
- systemDigest,
54
43
  } from "./inject.ts";
55
- import { attributeSession, deriveMemoryRefs, type MemoryRefs } from "./attribution.ts";
44
+ import { createInjectionEpochs } from "./injection-epochs.ts";
56
45
  import { readLedger, neverRetrieved, recordHits, useSignals, type HitSource } from "./hits.ts";
57
46
  import { formatInit, runInit } from "./init.ts";
58
47
  import { ensureInitCommand, ensureMemoryReportCommand } from "./command.ts";
59
48
  import {
60
49
  blockedRecent,
61
- emptyStats,
62
50
  renderMemoryReport,
63
- writeStatus,
64
51
  type Measured,
65
- type SessionStats,
66
52
  captureLag,
67
53
  captureLagLines,
68
54
  rowsPerDay,
69
- type StatusPayload,
70
55
  type StoreCounts,
71
56
  } from "./status.ts";
72
57
  import {
73
58
  afterTool,
74
- callsFor,
75
59
  checkNewSession,
76
- evidenceCalls,
60
+ writeEvidence,
77
61
  firstFrontierTap,
78
62
  hasEngagement,
79
63
  hasGateCheck,
@@ -81,13 +65,21 @@ import {
81
65
  markTurn,
82
66
  onCompacting,
83
67
  } from "./triggers.ts";
84
- import { authoredFor, getCurrent, setCurrent } from "./state.ts";
68
+ import { getCurrent, setCurrent } from "./state.ts";
85
69
  import { resolveRepo, setRepoScope, rememberSessionDir, sessionDir, sessionDirFirm, bindSessionProvisional, writeTarget } from "./repokey.ts";
86
70
  import { parseLine, readLines } from "./logfmt.ts";
87
71
  import { buildCapturePrompt, flattenTranscript, lagSince, parseCandidates, parseModelRef } from "./capture.ts";
88
72
  import { redactSecrets } from "./secrets.ts";
89
73
  import { flattenMemoryText } from "./sanitize.ts";
90
74
  import { bunFloorWarning } from "./runtime.ts";
75
+ import {
76
+ captureSessionID,
77
+ sessionDirectoryFromMessages,
78
+ sessionDirectoryFromRow,
79
+ sessionIdentityEvent,
80
+ sessionUsageEvent,
81
+ toolIdentity,
82
+ } from "./host.ts";
91
83
 
92
84
  // Tool/input boundaries are zod schemas (src/schema.ts): the JSON Schema the
93
85
  // host sees is GENERATED from them, and raw args are re-parsed at execution.
@@ -143,16 +135,8 @@ interface PluginCtx {
143
135
  transform: (cb: (editor: ToolEditorLike) => void) => Promise<unknown>;
144
136
  hook: (name: string, cb: (event: any) => Promise<void> | void) => Promise<HookReg | void>;
145
137
  };
146
- command?: {
147
- transform: (cb: (editor: { add: (cmd: Record<string, unknown>) => void }) => void) => Promise<unknown>;
148
- };
149
138
  session?: {
150
139
  hook: (name: string, cb: (event: any) => Promise<void> | void) => Promise<HookReg | void>;
151
- prompt: (input: {
152
- sessionID: string;
153
- text: string;
154
- delivery?: "steer" | "queue";
155
- }) => Promise<unknown>;
156
140
  context?: (input: { sessionID: string }) => Promise<unknown>;
157
141
  get?: (input: { sessionID: string }) => Promise<unknown>;
158
142
  };
@@ -231,36 +215,19 @@ export function resetCaptureCooldowns(): void {
231
215
  }
232
216
 
233
217
  // ---- capture trigger vocabulary (#136) -------------------------------------
234
- // opencode 2.x has no `session.idle`. The subscription used to wait for exactly
235
- // that string, so auto-capture was dead on every 2.x host with no warning
236
- // anywhere: live proof is in the issue (45 s of the running service's own SSE
237
- // stream over a complete turn, and zero `capture_lag` lines in the whole
238
- // evidence history). What the host really publishes when a turn ends is the
239
- // `session.execution.*` family; `session.status` is the ephemeral variant whose
240
- // `status.type` says "idle".
241
- //
242
- // These lists are the single source of truth for what the capture subscription
243
- // reacts to, and test/event-fidelity.test.ts asserts every name here appears in
244
- // the installed @opencode/schema event manifest. Invented event names are the
245
- // bug class that caused #78 and then survived a review, a merge and 480 green
246
- // tests, because the tests fabricated the same invented payload.
247
- // Recorded live, not guessed: `succeeded` and `interrupted` were both observed
248
- // on a running desktop service (test/fixtures/host-events.jsonl).
218
+ // Single source of truth for capture subscriptions. Both turn-end events were
219
+ // observed on the desktop service (test/fixtures/host-events.jsonl).
220
+ // test/event-fidelity.test.ts requires every trigger to appear in both that
221
+ // recording and the installed @opencode/schema manifest: a declared event
222
+ // alone is insufficient evidence that the host emits it (#78, #136).
249
223
  export const TURN_END_EVENTS = ["session.execution.succeeded", "session.execution.interrupted"] as const;
250
224
 
251
225
  /** Every event type the capture subscription reacts to (fidelity-tested). */
252
226
  export const CAPTURE_EVENT_TYPES: readonly string[] = [...TURN_END_EVENTS];
253
227
 
254
- // Deliberately NOT triggers, because a live host was never observed sending
255
- // them, and dead branches are what caused #136 in the first place:
256
- // • `session.idle` - declared, never emitted (the original bug).
257
- // • `session.status` - declared, never emitted; would also need
258
- // `data.status.type === "idle"` filtering.
259
- // • `session.execution.failed` - declared, not reproduced here. A failed turn
260
- // simply does not capture, which costs nothing; adding it
261
- // later is allowed the moment a recording shows it.
262
- // test/event-fidelity.test.ts enforces that nothing enters TURN_END_EVENTS
263
- // without appearing in the recording.
228
+ // `session.idle`, `session.status`, and `session.execution.failed` are declared
229
+ // but absent from that recording, so they deliberately do not trigger capture.
230
+ // Adding a trigger requires a recording; status would also need idle filtering.
264
231
 
265
232
  /**
266
233
  * True when a host event means "this session just went quiet". The internal
@@ -338,7 +305,7 @@ const impl = {
338
305
  // through here (readers and stamps use the firm-or-provisional split
339
306
  // in repokey/memory); do not mistake this for one.
340
307
  liveRoot: sessionDir(bound) ?? liveRoot,
341
- evidenceCalls: evidenceCalls(bound),
308
+ ...writeEvidence(bound),
342
309
  hasGateCheck: hasGateCheck(bound),
343
310
  hasEngagement: hasEngagement(bound),
344
311
  };
@@ -370,19 +337,17 @@ const impl = {
370
337
  // no await between (#116's documented fallback). Never re-read the global
371
338
  // after an await to learn who is calling (#127).
372
339
  const toolIds = (context?: unknown): { sid: string; call: string } => {
373
- const fromCtx = (context as { sessionID?: unknown; id?: unknown } | undefined)
374
- ?.sessionID;
375
- const call = (context as { id?: unknown } | undefined)?.id;
340
+ const { sessionID: fromCtx, callID: call } = toolIdentity(context);
376
341
  // Entry binding: a session this instance has never seen is resolved to
377
342
  // THIS workspace (provisional — a firm event/API identity still
378
343
  // replaces it), so the tool's reader partitions by the repository the
379
344
  // call reached, not by the last setup's module scope (#127).
380
- if (typeof fromCtx === "string" && fromCtx && fromCtx !== "?") {
345
+ if (fromCtx && fromCtx !== "?") {
381
346
  bindSessionProvisional(fromCtx, instanceDir);
382
347
  }
383
348
  return {
384
- sid: typeof fromCtx === "string" && fromCtx ? fromCtx : getCurrent().sid,
385
- call: typeof call === "string" && call ? call : getCurrent().call,
349
+ sid: fromCtx ?? getCurrent().sid,
350
+ call: call ?? getCurrent().call,
386
351
  };
387
352
  };
388
353
 
@@ -400,17 +365,8 @@ const impl = {
400
365
  bindingSids.add(sid);
401
366
  try {
402
367
  const msgs = await ctx.session?.context?.({ sessionID: sid });
403
- if (Array.isArray(msgs)) {
404
- for (const m of msgs) {
405
- if (!m || typeof m !== "object") continue;
406
- const r = m as Record<string, any>;
407
- const dir = r.location?.directory ?? r.info?.location?.directory;
408
- if (typeof dir === "string" && dir) {
409
- rememberSessionDir(sid, dir);
410
- break;
411
- }
412
- }
413
- }
368
+ const dir = sessionDirectoryFromMessages(msgs);
369
+ if (dir !== undefined) rememberSessionDir(sid, dir);
414
370
  } catch {
415
371
  // no context access or host error: the event stream still binds later
416
372
  } finally {
@@ -432,10 +388,9 @@ const impl = {
432
388
  apiBindTried.add(sid);
433
389
  apiBindOrder.touch(sid);
434
390
  try {
435
- const got = (await ctx.session?.get?.({ sessionID: sid })) as Record<string, any> | undefined;
436
- const row = (got?.data ?? got) as Record<string, any> | undefined;
437
- const dir = row?.location?.directory ?? row?.directory;
438
- if (typeof dir === "string" && dir) rememberSessionDir(sid, dir);
391
+ const got = await ctx.session?.get?.({ sessionID: sid });
392
+ const dir = sessionDirectoryFromRow(got);
393
+ if (dir !== undefined) rememberSessionDir(sid, dir);
439
394
  } catch {
440
395
  // no session.get on this host (or unknown session): stay unbound
441
396
  }
@@ -483,7 +438,11 @@ const impl = {
483
438
  if (ownerless) return await refuseOwnerlessWrite(ownerless, "remember");
484
439
  }
485
440
  const outcome = await runWriteGate(candidate, gateContext(sid));
486
- if (outcome.action === "promoted") return { content: `Remembered: ${args.type} in ${args.scope}` };
441
+ // A durable row whose audit line fell is NOT a clean success
442
+ // (#155 review): the reply says what is missing where it is
443
+ // missing, and the row itself stands.
444
+ if (outcome.action === "promoted")
445
+ return { content: `Remembered: ${args.type} in ${args.scope}${auditCaveat(outcome)}` };
487
446
  if (outcome.action === "collapsed") return { content: `Duplicate ignored: ${args.type}/${args.scope}` };
488
447
  return {
489
448
  content: `Write blocked at GATE (${outcome.reason}). ${
@@ -585,7 +544,7 @@ const impl = {
585
544
  editor.add(validated(UpdateArgs, {
586
545
  name: "memory_update",
587
546
  description:
588
- "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.",
547
+ "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. A prose edit carries over everything the call does not name — tags, issue, keywords, status, and the row's repository. Naming a row that was already updated to exactly this content (metadata included) reports the duplicate; if its live successor holds the prose and only the metadata you name differs, the successor is updated. A failure after the write is reported as PARTIAL: the replacement is durable and memory_undo merge/force restores the old row.",
589
548
  options: direct,
590
549
  async execute(args, context): Promise<{ content: string }> {
591
550
  const { sid } = toolIds(context);
@@ -606,6 +565,14 @@ const impl = {
606
565
  // is exactly the race this lock exists to close. The loser then
607
566
  // re-resolves under the lock, finds its target already retired,
608
567
  // and writes nothing — the documented fail-closed contract.
568
+ // Flips once a replacement row is durable, so the catch below can
569
+ // never claim "Nothing was written" about a write that happened
570
+ // (#155's lie).
571
+ let mutated = false;
572
+ // The gate's durable steps: rows GATE-2 retired before a later
573
+ // failure (round-3 probe 3). Non-empty means "Nothing was written"
574
+ // is no longer writable.
575
+ const gateDurable: string[] = [];
609
576
  try {
610
577
  return await withStoreLock(
611
578
  join(memoryRoot(), "update-order"),
@@ -616,12 +583,65 @@ const impl = {
616
583
  // Resolve the row BEFORE the gate: an update that cannot identify its
617
584
  // target must write nothing, rather than silently superseding whichever
618
585
  // row happened to be newest in this scope+type.
619
- const resolved = resolveMemoryTarget(prior, args.query);
586
+ let resolved = resolveMemoryTarget(prior, args.query);
620
587
  if (resolved.status === "not_found") {
621
- const where = args.query ? ` matches ${JSON.stringify(args.query)}` : "";
622
- return {
623
- content: `memory_update blocked: no active ${args.type} row in ${args.scope}${where}. Nothing was written.`,
624
- };
588
+ // Naming a SUPERSEDED row is not a miss (#155): the retry
589
+ // after a partial update lands here, and when that row's
590
+ // active successor already carries exactly this content the
591
+ // honest verdict is the duplicate one, not a dead end. Two
592
+ // subtleties the first cut missed: the successor's prose was
593
+ // stored REDACTED while a retry re-carries the raw input
594
+ // (the comparison must scrub), and "exactly this content"
595
+ // must mean the metadata too — a retry that also names new
596
+ // keywords still has work to do, and that work belongs on
597
+ // the chain head, so the update CONTINUES against the
598
+ // successor instead of collapsing here.
599
+ let chainHead: Memory | undefined;
600
+ if (args.query) {
601
+ const rows = (await loadAll()).filter(
602
+ (m) => m.scope === args.scope && m.type === args.type && isVisibleTo(m, reader),
603
+ );
604
+ const stale = resolveMemoryTarget(rows, args.query);
605
+ if (stale.status === "ok" && stale.target && !isActive(stale.target)) {
606
+ let latest = stale.target;
607
+ const walked = new Set<string>([latest.ts]);
608
+ while (latest.superseded_by) {
609
+ const next = rows.find((m) => m.ts === latest.superseded_by);
610
+ if (!next || walked.has(next.ts)) break;
611
+ walked.add(next.ts);
612
+ latest = next;
613
+ }
614
+ if (isActive(latest) && latest.content.trim() === redactSecrets(args.content).trim()) {
615
+ const restated =
616
+ (args.kw === undefined || sameStrList(args.kw, latest.kw)) &&
617
+ (args.status === undefined || args.status === (latest.status ?? "settled"));
618
+ if (restated) {
619
+ // Every other verdict is auditable; this one must
620
+ // be too — the message tells the model to consult
621
+ // memory_evidence.
622
+ await record(
623
+ "dedup_collapse",
624
+ { op: "update", named: stale.target.ts, match: latest.ts, action: "exact_successor", incoming_ignored: true },
625
+ true,
626
+ sid,
627
+ );
628
+ return {
629
+ content:
630
+ `Duplicate ignored: ${args.type}/${args.scope} — ${JSON.stringify(args.query)} was already ` +
631
+ `updated to exactly this content (${latest.ts}). Nothing was written.`,
632
+ };
633
+ }
634
+ chainHead = latest;
635
+ }
636
+ }
637
+ }
638
+ if (!chainHead) {
639
+ const where = args.query ? ` matches ${JSON.stringify(args.query)}` : "";
640
+ return {
641
+ content: `memory_update blocked: no active ${args.type} row in ${args.scope}${where}. Nothing was written.`,
642
+ };
643
+ }
644
+ resolved = { status: "ok", target: chainHead };
625
645
  }
626
646
  if (resolved.status === "ambiguous") {
627
647
  return {
@@ -632,22 +652,165 @@ const impl = {
632
652
  };
633
653
  }
634
654
  const target = resolved.target;
655
+ // A prose edit is not a metadata reset (#154): fields the
656
+ // call does not name carry over from the row being
657
+ // replaced, so updating an imported row can no longer
658
+ // launder away its provenance or issue link. kw follows
659
+ // the same rule with an override: omitted keeps the
660
+ // target's, provided replaces. The carry completes to the
661
+ // five fields of the #129 viewer precedent: STATUS (an
662
+ // open frontier row stays open) and REPO (updating a
663
+ // global row from one repository must not re-house it out
664
+ // of every other repository's view — "an edit must never
665
+ // widen visibility", and it must never narrow it either).
666
+ // These are also the fields the collapse-completion judges
667
+ // (review round 3): the fold asks whether the survivor
668
+ // already carries the REQUESTED state — not the pre-edit
669
+ // target's. An update naming kw:["new-alias"] is not
670
+ // "already standing" on a row holding ["old-alias"].
671
+ const requested = {
672
+ kw: args.kw ?? target.kw,
673
+ tags: target.tags,
674
+ issue: target.issue,
675
+ status: (args.status ?? target.status) ?? "settled",
676
+ repo: target.repo ?? "global",
677
+ };
635
678
  const outcome = await runWriteGate(
636
- { type: args.type, scope: args.scope, content: args.content, kw: args.kw, status: args.status },
637
- { ...gateContext(sid), supersedesTs: target.ts },
679
+ {
680
+ type: args.type,
681
+ scope: args.scope,
682
+ content: args.content,
683
+ kw: requested.kw,
684
+ tags: requested.tags,
685
+ issue: requested.issue,
686
+ status: requested.status,
687
+ repo: requested.repo,
688
+ repoPath: target.repo ? target.repoPath : undefined,
689
+ },
690
+ { ...gateContext(sid), supersedesTs: target.ts, durable: gateDurable },
638
691
  );
639
692
  if (outcome.action === "promoted" && outcome.ts && target) {
640
- await markSuperseded(target.ts, {
641
- superseded_by: outcome.ts,
642
- reason: "update",
643
- symbol: target.ts,
644
- from: target.ts,
645
- to: outcome.ts,
693
+ mutated = true;
694
+ const replacement = outcome.ts;
695
+ const retired = target.ts;
696
+ // The merge_review PARTIAL shape (156e887) applied to
697
+ // update: the replacement IS durable, so the message says
698
+ // exactly which follow-up step failed and what a retry does
699
+ // (#155 — never claim "Nothing was written" from here).
700
+ const partial = (why: string) => ({
701
+ content:
702
+ `memory_update PARTIAL: replacement ${replacement} IS on disk (memory_undo merge or force ` +
703
+ `restores ${retired}), but ${why}. Re-running this update reports the duplicate.`,
646
704
  });
647
- return { content: `Updated ${args.type} in ${args.scope} (superseded ${target.ts})` };
705
+ let retiredNow = false;
706
+ try {
707
+ retiredNow = await markSuperseded(retired, {
708
+ superseded_by: replacement,
709
+ reason: "update",
710
+ symbol: retired,
711
+ from: retired,
712
+ to: replacement,
713
+ });
714
+ } catch (err) {
715
+ return partial(
716
+ `retiring ${retired} failed: ${err instanceof Error && err.message ? err.message : String(err)}`,
717
+ );
718
+ }
719
+ if (!retiredNow) {
720
+ // merge_review checks exactly this boolean (156e887);
721
+ // "Updated (superseded X)" cannot be printed over a
722
+ // retirement a parallel supersession performed — that
723
+ // pointer names a DIFFERENT successor, and the confident
724
+ // line would hide a second active row.
725
+ return partial(
726
+ `${retired} had ALREADY been retired by another supersession while this call ran — ` +
727
+ `it points at that successor, not at ${replacement}; check memory_evidence`,
728
+ );
729
+ }
730
+ if (outcome.evidenceError !== undefined) {
731
+ return partial(`its write_promoted audit line was not recorded (${outcome.evidenceError})`);
732
+ }
733
+ return { content: `Updated ${args.type} in ${args.scope} (superseded ${retired})` };
734
+ }
735
+ if (outcome.action === "promoted")
736
+ return { content: `Remembered: ${args.type} in ${args.scope}${auditCaveat(outcome)}` };
737
+ if (outcome.action === "collapsed") {
738
+ // Completion (#155 convergence): when a retry collapses
739
+ // because an ACTIVE row already holds exactly this content
740
+ // while the row it NAMES is still active (the supersede
741
+ // step of an earlier PARTIAL attempt never landed), the
742
+ // idempotent close is to retire the named row in the
743
+ // survivor's favor — a bare "Duplicate ignored" would leave
744
+ // two active rows forever and a retry that never converges.
745
+ // first-call-wins makes this safe to attempt on any path.
746
+ // But the fold must not INVERT #154 (review): retiring the
747
+ // named row is loss-free only when the survivor already
748
+ // carries what the named row carries — the SAME predicate
749
+ // GATE-3 uses to call same-prose-different-metadata an
750
+ // edit rather than a duplicate. Otherwise the survivor
751
+ // would stand stripped of the named row's issue link,
752
+ // keywords, tags or OPEN frontier standing, and a "clean
753
+ // no-op" message would paper over a metadata destruction.
754
+ // On disagreement nothing retires: both ids are named and
755
+ // a human (or an update on the survivor) decides.
756
+ const survivorTs = outcome.collapsedWith;
757
+ if (target && survivorTs && survivorTs !== target.ts) {
758
+ const survivor = (await loadAll()).find((m) => m.ts === survivorTs && !m.superseded_by);
759
+ if (survivor) {
760
+ // The predicate is the REQUESTED state vs the survivor
761
+ // (round 3): content equality is already proven by the
762
+ // collapse, so the fold is loss-free only when the
763
+ // survivor also carries the metadata THIS call asked
764
+ // for — and stands where the target stands for readers
765
+ // of other repositories (repo visibility: folding a
766
+ // global row into a repo-private survivor would
767
+ // narrow a visibility the promotion path exists to
768
+ // preserve, and the reverse would leak).
769
+ if (
770
+ sameStrList(requested.kw, survivor.kw) &&
771
+ sameStrList(requested.tags, survivor.tags) &&
772
+ requested.issue === survivor.issue &&
773
+ requested.status === (survivor.status ?? "settled") &&
774
+ requested.repo === (survivor.repo ?? "global")
775
+ ) {
776
+ const done = await markSuperseded(target.ts, {
777
+ superseded_by: survivorTs,
778
+ reason: "update",
779
+ symbol: target.ts,
780
+ from: target.ts,
781
+ to: survivorTs,
782
+ });
783
+ if (done) {
784
+ return {
785
+ content:
786
+ `Duplicate: ${args.type}/${args.scope} already stands active as ${survivorTs}; ` +
787
+ `${target.ts} was retired in its favor. Nothing new was written.`,
788
+ };
789
+ }
790
+ } else {
791
+ const differs: string[] = [];
792
+ if (requested.status !== (survivor.status ?? "settled"))
793
+ differs.push(`status ${requested.status} vs ${survivor.status ?? "settled"}`);
794
+ if (requested.issue !== survivor.issue)
795
+ differs.push(`issue ${requested.issue ?? "-"} vs ${survivor.issue ?? "-"}`);
796
+ if (!sameStrList(requested.kw, survivor.kw))
797
+ differs.push(`kw [${(requested.kw ?? []).join(", ") || "-"}] vs [${(survivor.kw ?? []).join(", ") || "-"}]`);
798
+ if (!sameStrList(requested.tags, survivor.tags))
799
+ differs.push(`tags [${(requested.tags ?? []).join(", ") || "-"}] vs [${(survivor.tags ?? []).join(", ") || "-"}]`);
800
+ if (requested.repo !== (survivor.repo ?? "global"))
801
+ differs.push(`visibility ${requested.repo} vs ${survivor.repo ?? "global"}`);
802
+ return {
803
+ content:
804
+ `Duplicate: ${args.type}/${args.scope} stands active as ${survivorTs}, but ${target.ts} ` +
805
+ `was NOT retired — the survivor does not carry what this update asked for ` +
806
+ `(${differs.join("; ")}), and the fold would drop it. Both stay active: restate them ` +
807
+ `onto ${survivorTs} with a memory_update, or memory_forget the row that should lose.`,
808
+ };
809
+ }
810
+ }
811
+ }
812
+ return { content: `Duplicate ignored: ${args.type}/${args.scope}` };
648
813
  }
649
- if (outcome.action === "promoted") return { content: `Remembered: ${args.type} in ${args.scope}` };
650
- if (outcome.action === "collapsed") return { content: `Duplicate ignored: ${args.type}/${args.scope}` };
651
814
  return { content: `Write blocked at GATE (${outcome.reason}). ${outcome.hint ?? ""}`.trimEnd() };
652
815
  },
653
816
  {
@@ -658,10 +821,27 @@ const impl = {
658
821
  },
659
822
  );
660
823
  } catch (err) {
661
- // Only the fail-closed lock timeout throws here; the write path
662
- // has its own outcomes. Nothing was written either way.
824
+ // Everything that still throws here was PRE-WRITE for THIS call's
825
+ // replacement: the fail-closed lock timeout, the #152 choke-point
826
+ // refusal, an evidence fault BEFORE the append. Post-append audit
827
+ // failures no longer reach this catch — the gate reports them on
828
+ // the promoted outcome (#155). mutated is the belt-and-braces
829
+ // truth check: a future post-write throw must report a partial,
830
+ // never a clean nothing. And gateDurable closes the last gap
831
+ // (round 3): the gate may have RETIRED OTHER rows at GATE-2
832
+ // before the fault that got here — those tombstones are on disk,
833
+ // and naming them beats the "Nothing was written" premise.
834
+ const msg = err instanceof Error && err.message ? err.message : String(err);
663
835
  return {
664
- content: `memory_update blocked: ${(err as Error).message} Nothing was written.`,
836
+ content: mutated
837
+ ? `memory_update PARTIAL: a step after the durable write failed: ${msg}. ` +
838
+ "Re-running this update reports the duplicate; inspect with memory_evidence."
839
+ : gateDurable.length > 0
840
+ ? `memory_update blocked: ${msg} No replacement was written, but the gate had ALREADY retired ` +
841
+ `${gateDurable.length} other row(s) (${gateDurable.join(", ")}): those retirements ARE on ` +
842
+ "disk and their audit lines may not all have landed. Re-running this update will not undo " +
843
+ "them — reconcile with memory_evidence / memory_undo before retrying."
844
+ : `memory_update blocked: ${msg} Nothing was written.`,
665
845
  };
666
846
  }
667
847
  },
@@ -958,6 +1138,12 @@ const impl = {
958
1138
  `${t.blocked} blocked by the gate, ${t.skipped} malformed lines skipped.` +
959
1139
  (t.downgraded
960
1140
  ? ` ${t.downgraded} open rows downgraded to settled (missing eligible memory_export header or verifiable repo scope).`
1141
+ : "") +
1142
+ // Rows that landed without their write_promoted line are
1143
+ // durable but invisible to memory_evidence (#155 review) —
1144
+ // the tally owes the reader the count, not silence.
1145
+ (t.unaudited
1146
+ ? ` ${t.unaudited} promoted rows landed without their write_promoted audit line (${t.auditError}); memory_evidence will miss them.`
961
1147
  : ""),
962
1148
  };
963
1149
  } catch (err) {
@@ -1037,7 +1223,7 @@ const impl = {
1037
1223
  async execute(_args, context): Promise<{ content: string }> {
1038
1224
  // In-process truth: the live epoch + ledger, fresher than any file.
1039
1225
  const sid = toolIds(context).sid;
1040
- const status = sid === "?" ? null : await buildPayload(sid);
1226
+ const status = sid === "?" ? null : await sessions.buildPayload(sid);
1041
1227
  const all = await loadAll();
1042
1228
  const act = all.filter(isActive);
1043
1229
  const store: StoreCounts = {
@@ -1066,121 +1252,6 @@ const impl = {
1066
1252
  }));
1067
1253
  });
1068
1254
 
1069
- // Per-session frozen injection epochs: the whole memory section (digest +
1070
- // frontier + relevance) plus the store fingerprint it was rendered from.
1071
- // Recomputed on the first prompt of a tracked session, when injectable rows
1072
- // change, or after a compaction (see the prompt/context/compaction hooks).
1073
- // The RENDERED BYTES, not the fingerprint, decide whether the epoch moved
1074
- // (issue #162): a write that changes nothing the model is shown must not
1075
- // cost the next request a full re-prefill. And a pure addition the session
1076
- // wrote itself does not move them either (#165) — see refreshEpoch. The
1077
- // shared LRU below may evict the whole session state; a later prompt starts
1078
- // it fresh.
1079
- const epoch = new Map<
1080
- string,
1081
- {
1082
- version: string;
1083
- /** Frozen standing digest + frontier + convergence parts, in push order. */
1084
- parts: string[];
1085
- /** The budgeted relevance block the surfaces report against injectBudget. */
1086
- block: string;
1087
- /** Comparison key: every byte of the memory section, joined. */
1088
- prefix: string;
1089
- /**
1090
- * Rows THIS session had already authored when these bytes were rendered
1091
- * (#165). The riding-bytes test subtracts everything authored after this
1092
- * snapshot; if what remains renders identically, the whole difference is
1093
- * the session's own additions and the bytes keep riding.
1094
- */
1095
- ownRows: Set<string>;
1096
- /**
1097
- * The prompt these bytes were scored against. The counterfactual below
1098
- * has to re-score the SAME inputs, or a topic change between the freeze
1099
- * and the next write would look like a content change — and the epoch
1100
- * would pay for a refresh it deliberately refuses to do on a prompt.
1101
- */
1102
- prompt: string;
1103
- at: string;
1104
- reason: "first" | "store_changed";
1105
- refs: MemoryRefs;
1106
- }
1107
- >();
1108
- // Latest user prompt per tracked session. A changed store is re-scored
1109
- // against it even when the change happened during a tool loop with no new
1110
- // prompt. It is evicted together with the epoch and session ledgers.
1111
- const latestPrompt = new Map<string, string>();
1112
- // Recomputes since server start: every one invalidated a prompt cache, so
1113
- // it is the honest cost number the surfaces show (status files / tools).
1114
- let epochRecomputes = 0;
1115
-
1116
- // Per-session ledger, incremented at the injection decision below, and the
1117
- // last measured prompt-cache usage per session (message.updated). The
1118
- // surfaces read these through flushed status files (TUI) or directly
1119
- // (memory_status, in-process).
1120
- const sessionStats = new Map<string, SessionStats>();
1121
- const measuredTurns = new Map<string, Measured>();
1122
- // Every map above is keyed by session and dropped together on eviction.
1123
- const sessions = new SessionLru(SESSION_CAP, (sid) => {
1124
- epoch.delete(sid);
1125
- latestPrompt.delete(sid);
1126
- sessionStats.delete(sid);
1127
- measuredTurns.delete(sid);
1128
- });
1129
- const statsFor = (sid: string): SessionStats => {
1130
- let st = sessionStats.get(sid);
1131
- if (!st) {
1132
- st = emptyStats();
1133
- sessionStats.set(sid, st);
1134
- }
1135
- return st;
1136
- };
1137
-
1138
- // Build the full status snapshot for one session, or null before its first
1139
- // epoch. Store counts are computed fresh so every flush is current.
1140
- const buildPayload = async (sid: string): Promise<StatusPayload | null> => {
1141
- const ep = epoch.get(sid);
1142
- if (!ep) return null;
1143
- const all = await loadAll();
1144
- const act = all.filter(isActive);
1145
- const led = await readLedger();
1146
- return {
1147
- at: ep.at,
1148
- sessionID: sid,
1149
- reason: ep.reason,
1150
- recomputes: epochRecomputes,
1151
- block: ep.block,
1152
- blockChars: ep.block.length,
1153
- sectionChars: ep.prefix.length,
1154
- budget,
1155
- store: {
1156
- active: act.length,
1157
- superseded: all.length - act.length,
1158
- open: act.filter((m) => m.status === "open").length,
1159
- scopes: new Set(act.map((m) => m.scope)).size,
1160
- malformed: malformedCount(),
1161
- neverRetrieved: neverRetrieved(act, led).length,
1162
- ledgerSince: led.since,
1163
- },
1164
- stats: statsFor(sid),
1165
- measured: measuredTurns.get(sid) ?? null,
1166
- attribution: attributeSession(callsFor(sid), ep.refs),
1167
- };
1168
- };
1169
- const flushStatus = (sid: string): Promise<void> =>
1170
- buildPayload(sid).then((p) => (p ? writeStatus(p) : undefined));
1171
-
1172
- // Called when a prompt arrives (to keep status surfaces current) and again
1173
- // at the injection decision on every model request. The latter keeps
1174
- // removals fail-closed: an out-of-band redaction or a block during a tool
1175
- // loop cannot ride one more request waiting for another user prompt.
1176
- // The caller's sid is resolved to an immutable Reader BEFORE the store
1177
- // read (#127): while loadAll awaits, another session's hooks may dispatch
1178
- // and move the ambient current; filtering with THAT leaks the other
1179
- // session's repo into this one's system prompt.
1180
- const injectableRows = async (sid?: string): Promise<Memory[]> => {
1181
- const reader = readerFromSid(sid);
1182
- return (await loadAll()).filter((m) => isActive(m) && isVisibleTo(m, reader));
1183
- };
1184
1255
  // Use ledger (#42). `query` is what retrieval was asked with; what gets
1185
1256
  // stored is the vocabulary the answer SHARES with the query, taken from the
1186
1257
  // memory side, so the ledger can never become a copy of user prompts.
@@ -1191,118 +1262,16 @@ const impl = {
1191
1262
  for (const m of rows) for (const t of sharedTerms(query, m)) if (!terms.includes(t)) terms.push(t);
1192
1263
  await recordHits(src, sid, rows, terms);
1193
1264
  };
1194
- // Render the COMPLETE memory section for one request: the standing digest,
1195
- // the open-thread frontier and the convergence line (all from systemDigest),
1196
- // followed by this epoch's relevance block. The parts are exactly what gets
1197
- // pushed onto `event.system`; their join is the byte key the epoch compares
1198
- // against, so "did the cache-critical prefix change?" is answered by the
1199
- // bytes the model would actually see and never by a proxy (issue #162).
1200
- const buildMemorySection = async (
1201
- sid: string | undefined,
1202
- mems: Memory[],
1203
- promptOverride?: string,
1204
- ): Promise<{ parts: string[]; block: string; prefix: string; rode: Memory[]; refs: MemoryRefs }> => {
1205
- const parts: string[] = [];
1206
- await systemDigest(
1207
- { sessionID: sid },
1208
- { system: parts },
1209
- { rows: mems, frontierBudget: openBudget },
1210
- );
1211
- const prompt = promptOverride ?? (sid === undefined ? "" : latestPrompt.get(sid) ?? "");
1212
- // Widen the candidate pool, then cap: the budget decides what rides.
1213
- const sel = await selectRelevant(prompt, 5, mems, await useSignals());
1214
- const block = sel.block ? capToBudget(sel.block, budget) : "";
1215
- // Refs the ACTUALLY-injected rows assert (paths + commands), the join key
1216
- // for attribution. Derived from the budget-surviving rows, not the wider
1217
- // candidate pool — crediting paths the model never saw would overclaim.
1218
- const rode = injectedRows(block, sel.selected);
1219
- const prefix = [...parts, block].join("\u0000");
1220
- return { parts, block, prefix, rode, refs: deriveMemoryRefs(rode) };
1221
- };
1222
- const refreshEpoch = async (sid: string, rows?: Memory[]): Promise<void> => {
1223
- if (!latestPrompt.has(sid)) return;
1224
- const mems = rows ?? (await injectableRows(sid));
1225
- const version = await storeVersion(mems);
1226
- const cached = epoch.get(sid);
1227
- // Cheap pre-check: no injectable row moved, so the frozen bytes still
1228
- // stand. Skips re-scoring and the use-ledger write on ordinary turns.
1229
- if (cached?.version === version) return;
1230
- const built = await buildMemorySection(sid, mems);
1231
- // The store moved. A write that changes nothing RENDERED — a row that is
1232
- // not relevant to this prompt, supersession elsewhere, a scope the reader
1233
- // never sees rendered identically — must not cost this session a prompt
1234
- // cache. Adopt the new fingerprint, keep riding the same bytes, emit
1235
- // nothing: an invalidation has to mean bytes actually moved.
1236
- if (cached && cached.prefix === built.prefix) {
1237
- epoch.set(sid, { ...cached, version });
1238
- return;
1239
- }
1240
- // Riding bytes (#165): a pure addition this session wrote itself is
1241
- // information it already has — the model produced it, it is in the
1242
- // transcript. Re-render the section with every row authored SINCE these
1243
- // bytes were frozen taken back out: if it comes back byte-identical, the
1244
- // entire difference is attributable to the session's own additions and
1245
- // the frozen bytes keep riding. Everything else survives into that render
1246
- // and still busts — a riding row removed or rewritten (blocklist,
1247
- // hand-redaction, forget, supersession, decay), another session's row, a
1248
- // viewer edit, an import, a moved convergence line.
1249
- if (cached) {
1250
- const mine = authoredFor(sid);
1251
- const extra = mems.filter((m) => mine.has(m.ts) && !cached.ownRows.has(m.ts));
1252
- if (extra.length) {
1253
- const back = await buildMemorySection(
1254
- sid,
1255
- mems.filter((m) => !extra.some((e) => e.ts === m.ts)),
1256
- cached.prompt,
1257
- );
1258
- if (back.prefix === cached.prefix) {
1259
- epoch.set(sid, { ...cached, version });
1260
- return;
1261
- }
1262
- }
1263
- }
1264
- const prompt = latestPrompt.get(sid) ?? "";
1265
- // Use ledger (#42): the rows that actually rode the block, credited with
1266
- // the terms the prompt and those rows shared (never the prompt itself).
1267
- // Only once the build is ADOPTED — a discarded rebuild must not credit
1268
- // rows that were already offered under the frozen epoch.
1269
- await noteHits("inject", sid, built.rode, prompt);
1270
- const at = new Date().toISOString();
1271
- const reason: "first" | "store_changed" = cached ? "store_changed" : "first";
1272
- epoch.set(sid, {
1273
- version,
1274
- parts: built.parts,
1275
- block: built.block,
1276
- prefix: built.prefix,
1277
- ownRows: new Set(mems.filter((m) => authoredFor(sid).has(m.ts)).map((m) => m.ts)),
1278
- prompt,
1279
- at,
1280
- reason,
1281
- refs: built.refs,
1282
- });
1283
- await record(
1284
- "epoch_recompute",
1285
- {
1286
- session: sid,
1287
- reason,
1288
- chars: built.block.length,
1289
- },
1290
- false,
1291
- );
1292
- epochRecomputes++;
1293
- // Ledger: a store_changed recompute of a live epoch is an
1294
- // invalidation (the first epoch of a session busts nothing). The
1295
- // epoch request count restarts with the new block.
1296
- const st = statsFor(sid);
1297
- st.epochRequests = 0;
1298
- if (reason === "store_changed") {
1299
- st.invalidations++;
1300
- st.lastInvalidation = { at, reason };
1301
- }
1302
- // Status hand-off for the terminal panel (src/tui.tsx) and any
1303
- // out-of-process surface. Best-effort; never breaks injection.
1304
- await flushStatus(sid);
1305
- };
1265
+ // The host listener owns measured usage; the epoch controller drops it
1266
+ // alongside its own maps when the shared session LRU evicts an entry.
1267
+ const measuredTurns = new Map<string, Measured>();
1268
+ const sessions = createInjectionEpochs({
1269
+ budget,
1270
+ frontierBudget: openBudget,
1271
+ measuredTurns,
1272
+ noteHits: (sid, rows, query) => noteHits("inject", sid, rows, query),
1273
+ });
1274
+ const flushStatus = sessions.flushStatus;
1306
1275
 
1307
1276
  // ---- hooks (all fail-closed) -------------------------------------------
1308
1277
  // Seam set by the auto-capture wiring below ONLY when the compaction
@@ -1367,39 +1336,7 @@ const impl = {
1367
1336
  // already bound firmly in production, so no host lookup belongs in
1368
1337
  // this hot path (#127).
1369
1338
  if (typeof sid === "string") bindSessionProvisional(sid, instanceDir);
1370
- const mems = await injectableRows(sid);
1371
- if (typeof sid === "string") await refreshEpoch(sid, mems);
1372
- // Deliver the FROZEN memory section. Every byte pushed onto the system
1373
- // prompt comes from the epoch, so between busts the provider sees an
1374
- // identical prefix and serves the conversation from cache (issue #162).
1375
- // A session with no epoch yet (no prompt recorded, or evicted from the
1376
- // LRU) still gets the standing digest, built fresh and uncached.
1377
- const ep = typeof sid === "string" ? epoch.get(sid) : undefined;
1378
- if (ep) {
1379
- for (const text of ep.parts) event?.system?.push?.({ type: "text", text });
1380
- } else {
1381
- const parts: string[] = [];
1382
- await systemDigest(
1383
- { sessionID: event?.sessionID },
1384
- { system: parts },
1385
- { rows: mems, frontierBudget: openBudget },
1386
- );
1387
- for (const text of parts) event?.system?.push?.({ type: "text", text });
1388
- }
1389
- // This epoch's relevance-ranked memory, also on the system channel —
1390
- // the UI never renders system parts, unlike appended prompt text.
1391
- const knowledge = ep?.block;
1392
- if (knowledge) event?.system?.push?.({ type: "text", text: knowledge });
1393
- // Count AT THE INJECTION DECISION so badge/panel numbers match exactly
1394
- // what rode this request (a later abort still rode the bytes — known
1395
- // and documented). Abstained = the epoch exists but its block is empty.
1396
- if (typeof sid === "string") {
1397
- const st = statsFor(sid);
1398
- st.requests++;
1399
- st.epochRequests++;
1400
- if (knowledge) st.cumChars += knowledge.length;
1401
- else if (epoch.has(sid)) st.abstained++;
1402
- }
1339
+ await sessions.deliver(sid, (text) => event?.system?.push?.({ type: "text", text }));
1403
1340
  }),
1404
1341
  );
1405
1342
 
@@ -1419,8 +1356,7 @@ const impl = {
1419
1356
  markTurn(sid);
1420
1357
  await checkNewSession(sid);
1421
1358
  await bindSessionIdentity(sid);
1422
- latestPrompt.set(sid, event?.prompt?.text ?? "");
1423
- await refreshEpoch(sid);
1359
+ await sessions.prompt(sid, event?.prompt?.text ?? "");
1424
1360
  }
1425
1361
  }),
1426
1362
  );
@@ -1443,8 +1379,7 @@ const impl = {
1443
1379
  if (typeof sid === "string") bindSessionProvisional(sid, instanceDir);
1444
1380
  await onCompacting({ sessionID: event?.sessionID });
1445
1381
  if (typeof event?.sessionID === "string") {
1446
- epoch.delete(event.sessionID);
1447
- latestPrompt.delete(event.sessionID);
1382
+ sessions.invalidate(event.sessionID);
1448
1383
  }
1449
1384
  const anchor = await compactionAnchor(12, sid);
1450
1385
  if (anchor) event?.system?.push?.({ type: "text", text: anchor });
@@ -1474,53 +1409,29 @@ const impl = {
1474
1409
  void (async () => {
1475
1410
  try {
1476
1411
  for await (const raw of eventApi.subscribe({ signal: measuredController.signal })) {
1477
- const ev = raw as Record<string, any>;
1478
1412
  // Session identity: created fires for new sessions, execution.started
1479
1413
  // every turn (covers sessions resumed across a restart), moved on a
1480
1414
  // workspace change. Stamps and visibility resolve through this.
1481
- if (
1482
- ev?.type === "session.created" ||
1483
- ev?.type === "session.execution.started" ||
1484
- ev?.type === "session.moved"
1485
- ) {
1486
- const d = ev.data ?? ev.properties ?? {};
1487
- const info = d.info ?? d;
1488
- const sid = info.sessionID ?? d.sessionID;
1489
- const dir =
1490
- info.location?.directory ?? d.location?.directory ?? ev.location?.directory ?? info.directory;
1491
- if (typeof sid === "string" && typeof dir === "string") rememberSessionDir(sid, dir);
1415
+ const identity = sessionIdentityEvent(raw);
1416
+ if (identity) {
1417
+ const { sessionID: sid, directory: dir } = identity;
1418
+ if (dir !== undefined) rememberSessionDir(sid, dir);
1492
1419
  // 2.1.4 serve sends execution.started with no location at all:
1493
1420
  // resolve the session row instead of leaving the session unbound.
1494
- else if (typeof sid === "string") void guarded("session bind (api)", () => bindSessionFromApi(sid));
1495
- continue;
1496
- }
1497
- // Token usage: v2 hosts (>=2.0.x) emit `session.usage.updated` with
1498
- // data.{sessionID, tokens}; older hosts carried the same TokenUsage
1499
- // on message.updated's assistant info. Accept both so `measured`
1500
- // populates regardless of host version.
1501
- let usid: unknown;
1502
- let ut: { input?: number; cache?: { read?: number; write?: number } } | undefined;
1503
- if (ev?.type === "session.usage.updated") {
1504
- usid = ev.data?.sessionID;
1505
- ut = ev.data?.tokens;
1506
- } else if (ev?.type === "message.updated") {
1507
- const info = ev.properties?.info ?? ev.info ?? ev.data?.info;
1508
- if (info && info.role === "assistant") {
1509
- usid = info.sessionID;
1510
- ut = info.tokens;
1511
- }
1512
- } else {
1421
+ else void guarded("session bind (api)", () => bindSessionFromApi(sid));
1513
1422
  continue;
1514
1423
  }
1515
- if (typeof usid !== "string" || !ut) continue;
1516
- sessions.touch(usid);
1517
- measuredTurns.set(usid, {
1424
+ const usage = sessionUsageEvent(raw);
1425
+ if (!usage) continue;
1426
+ const { sessionID, input, read, write } = usage;
1427
+ sessions.touch(sessionID);
1428
+ measuredTurns.set(sessionID, {
1518
1429
  at: new Date().toISOString(),
1519
- input: Number(ut.input) || 0,
1520
- read: Number(ut.cache?.read) || 0,
1521
- write: Number(ut.cache?.write) || 0,
1430
+ input,
1431
+ read,
1432
+ write,
1522
1433
  });
1523
- await guarded("status flush (measured)", () => flushStatus(usid));
1434
+ await guarded("status flush (measured)", () => flushStatus(sessionID));
1524
1435
  }
1525
1436
  } catch {
1526
1437
  // the subscription ended (abort or host error); nothing to do
@@ -1533,7 +1444,7 @@ const impl = {
1533
1444
  // measured-cache listener above does subscribe to the event stream by
1534
1445
  // default, but it is zero-model: pure bookkeeping of message usage.) When
1535
1446
  // enabled (options.autoCapture === true AND a valid captureModel), each
1536
- // session.idle event — and, unless captureOnCompact === false, each
1447
+ // supported turn-end event — and, unless captureOnCompact === false, each
1537
1448
  // compaction hook call too — runs ONE cheap ctx.generate.text call whose
1538
1449
  // reply is parsed into candidates that go through the SAME runWriteGate as
1539
1450
  // model-authored writes — capture can never bypass the moat, and it only
@@ -1642,7 +1553,17 @@ const impl = {
1642
1553
  ? `auto_capture_compaction_${outcome.action}`
1643
1554
  : `auto_capture_${outcome.action}`,
1644
1555
  // A blocked credential-shaped scope must not reach the evidence log either.
1645
- { session: sid, trigger, type: c.type, scope: redactSecrets(c.scope), reason: outcome.reason ?? "" },
1556
+ // The promoted line also carries the audit fault when the
1557
+ // write_promoted line fell (#155 review — capture has no
1558
+ // reply to caveat, so this line is the trail's only note).
1559
+ {
1560
+ session: sid,
1561
+ trigger,
1562
+ type: c.type,
1563
+ scope: redactSecrets(c.scope),
1564
+ reason: outcome.reason ?? "",
1565
+ audit_error: outcome.evidenceError,
1566
+ },
1646
1567
  false,
1647
1568
  );
1648
1569
  }
@@ -1652,12 +1573,9 @@ const impl = {
1652
1573
  void (async () => {
1653
1574
  try {
1654
1575
  for await (const raw of eventApi.subscribe({ signal: controller.signal })) {
1655
- const event = raw as Record<string, any>;
1656
- if (!captureTriggerFor(event)) continue;
1657
- // 2.x carries the session inside `data`; the other two shapes are
1658
- // kept because the measured listener sees both across host modes.
1659
- const sid = event.data?.sessionID ?? event.sessionID ?? event.properties?.sessionID;
1660
- if (typeof sid !== "string") continue;
1576
+ if (!captureTriggerFor(raw)) continue;
1577
+ const sid = captureSessionID(raw);
1578
+ if (sid === undefined) continue;
1661
1579
  setCurrent({ sessionID: sid });
1662
1580
  const now = Date.now();
1663
1581
  if (!captureCooldownPasses("idle", sid, now)) continue; // 5-min cooldown, shared across setups