opencode-self-improvement 0.20.0 → 0.21.0

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
@@ -72,6 +72,7 @@ Zero configuration is the default. To tune, use the object form of the plugin en
72
72
  | `captureModel` | — | `"provider/id"` model used for auto-capture. Required when `autoCapture` is on; missing or invalid disables capture with a startup warning. |
73
73
  | `captureMax` | `3` | Maximum candidates proposed per capture pass. |
74
74
  | `captureOnCompact` | `true` | When `autoCapture` is on, also mine the transcript at compaction, before the summarizer replaces it. Its 5-minute cooldown is separate from the turn-end one, so the two triggers' hit-rates stay measurable. Setting it while `autoCapture` is off does nothing and reports a startup warning. |
75
+ | `captureGuidedRules` | `false` | POC: deterministic guided-candidate pre-pass. The user's own lines decide which stated values or rules are guided (numbers, rates, currency, explicit rule assertions) and attach the verbatim quote; the capture model may phrase such a row but cannot clear the flag or the quote, and a guided quote the user never wrote is refused at the write boundary instead of silently stripped. Fires alongside the model pass only — no extra model calls. |
75
76
  | `notifyBlocked` | `true` | Terminal (TUI) only: toast when a write gate blocks a write. Blocks are always in `memory_evidence` either way. |
76
77
 
77
78
  ### Environment variables
@@ -99,6 +100,8 @@ What is established, from tests and fixtures (no live store involved):
99
100
  - **The path runs under simulated host traffic** — unit tests hand the plugin the recorded envelopes and assert a candidate lands through the write gate, including conservation (a near-duplicate collapses at the gate instead of writing a second row): `test/capture.test.ts`, `test/capture-compaction.test.ts`. No terminal e2e scenario covers the trigger, so the simulated envelope is the strongest evidence that exists — and fabricating the envelope is exactly what passed while this feature was dead.
100
101
  - **Identity triggers have their own recording check.** `test/event-fidelity.test.ts` checks `IDENTITY_EVENT_TYPES` against the original 2.1.4 recording plus `test/fixtures/host-session-move.json`, a normalized one-frame extract from a separate 2.2.2 move capture. The extract must declare nonempty provenance and its retained envelopes must round-trip through the lockfile-pinned `@opencode/schema` 2.0.32 decoder. These checks reject missing metadata and malformed envelopes; they do not authenticate the capture. The identity replay uses the plugin subscription, but live plugin rebinding remains unverified. The recording version is distinct from the CI host pin (2.0.26).
101
102
 
103
+ - **Teardown stops work that is still in flight.** `generate.text` does not take the abort signal, so a capture parked mid-model-call used to wake up after the host disposed the plugin and run the whole write gate against a store its caller had already removed. Cleanup now aborts the subscription, every pass re-checks the signal after the model call and between candidates (a gate already mutating is never cut in half), and cleanup drains the tracked passes under a one-second bound — teardown never waits on the model. `test/capture-dispose-drain.test.ts` parks a capture, disposes, releases, and asserts that no row and no evidence line carries a timestamp after disposal (#211).
104
+
102
105
  What is not established:
103
106
 
104
107
  - That a live host emits those events in the shape the subscription reads, end to end. No `auto_capture_*` line and no `capture_lag` line exists anywhere in the maintainer's evidence history (checked 2026-10-26 through 2026-10-29); a live trial armed on 2026-10-26 was stood down on 2026-10-29 without ever firing, so it answered nothing.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.20.0",
3
+ "version": "0.21.0",
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": {
@@ -116,12 +116,25 @@ export function parseCandidates(raw: string, max: number): CaptureCandidate[] {
116
116
  : {}),
117
117
  }
118
118
  : {};
119
+ // Verbatim user utterance: shape-checked here, substring-verified by the
120
+ // runtime against the transcript the model saw. A failed verification
121
+ // drops the field, never the row.
122
+ const original =
123
+ guided && typeof o.original === "string"
124
+ ? (() => {
125
+ const s = o.original.trim();
126
+ return s && s.length <= 300 && flattenMemoryText(s) === s
127
+ ? s
128
+ : undefined;
129
+ })()
130
+ : undefined;
119
131
  out.push({
120
132
  ...(status
121
133
  ? { type, scope, content, status }
122
134
  : { type, scope, content }),
123
135
  ...(kw ? { kw } : {}),
124
136
  ...(guided ? { guided: true, ...conflict } : {}),
137
+ ...(original ? { original } : {}),
125
138
  });
126
139
  }
127
140
  return out;
@@ -0,0 +1,198 @@
1
+ // guided-rules — deterministic guided-candidate pre-pass (POC, FINDINGS
2
+ // 2026-11-08 §4). Plugin option `captureGuidedRules`, default OFF.
3
+ //
4
+ // Mystery 2's last stochastic link is capture EMISSION: the capture model
5
+ // flagged the user-stated fact guided in 5 of 7 runs (attr + ARM F). The
6
+ // field's convergent fix is "LLM proposes, rules dispose" (arXiv 2604.27906
7
+ // schema-grounded memory; neuro-symbolic extraction, Nat. Comm. Med. 2025;
8
+ // MEDIQA-SYNUR 2026 exact-evidence grounding): decide WHAT must be guided
9
+ // deterministically from the user's own lines, let the model only PHRASE it,
10
+ // and validate the quote on the write path so a miss becomes a retriable
11
+ // event, not a silent omission.
12
+ //
13
+ // Contract:
14
+ // - findGuidedQuotes scans user text (the REQUESTS prose plus transcript
15
+ // user: lines) sentence by sentence; a sentence stating a value or a rule
16
+ // yields its VERBATIM text (whitespace-normalised, capped).
17
+ // - mergeGuidedCandidates lets the model phrase a pre-pass quote (matched by
18
+ // its own verbatim original or by numeric overlap) but never clear the
19
+ // guided flag or drop the quote: an unmatched quote gets a deterministic
20
+ // fallback row.
21
+ // - All functions are TOTAL like the rest of capture: junk input yields
22
+ // []/passthrough, never a throw.
23
+ import type { CaptureCandidate } from "./prompt.ts";
24
+
25
+ /** Same normalisation the runtime quote check uses. */
26
+ export function normWs(s: string): string {
27
+ return s.replace(/\s+/g, " ").trim();
28
+ }
29
+
30
+ /** Cap mirrors the store's original field; a quote is a substring, so a
31
+ * truncation at a space boundary stays verbatim. */
32
+ export const GUIDED_QUOTE_CHARS = 300;
33
+
34
+ // Decidable stated-fact shapes (the class the bench's guidance lives in):
35
+ // a number/rate/currency, or an explicit rule assertion. Deliberately
36
+ // narrow — the guided lane is capped and budgeted, but a rule that flags
37
+ // ordinary prose would still be noise by construction.
38
+ const VALUE_RE = /\d+(?:[.,]\d+)?\s*%|\d+\.\d+|[$€£]\s*\d/;
39
+ const RULE_RE =
40
+ /\b(must be|must equal|must include|has to be|is set to|is exactly|the correct\b|is inclusive|not only\b|always|never|the rule is)\b/i;
41
+
42
+ /**
43
+ * Verbatim sentences from the user's own text that state a value or a rule.
44
+ * `userText` is the REQUESTS prose plus the transcript's user: lines — never
45
+ * assistant output, so a stored quote can only be what the user said.
46
+ */
47
+ export function findGuidedQuotes(userText: string): string[] {
48
+ const out: string[] = [];
49
+ for (const raw of userText.split(/(?<=[.!?])\s+|\n/)) {
50
+ const s = normWs(raw.replace(/^\s*user:\s*/i, ""));
51
+ if (s.length < 12 || s.length > 2000) continue;
52
+ if (!VALUE_RE.test(s) && !RULE_RE.test(s)) continue;
53
+ // Imperatives scoping THIS job are instructions, not stated facts
54
+ // ("do not create tests"); the capture contract expires them with the task.
55
+ if (/^(do|don't|dont|never create|only touch)\b/i.test(s)) continue;
56
+ const quote =
57
+ s.length > GUIDED_QUOTE_CHARS
58
+ ? normWs(s.slice(0, GUIDED_QUOTE_CHARS).replace(/\s\S*$/, ""))
59
+ : s;
60
+ if (quote.length >= 12 && !out.includes(quote)) out.push(quote);
61
+ // Bound the lane the way injection bounds it (GUIDED_INJECT_CAP): a user
62
+ // message that states five facts is a fixture, not a session.
63
+ if (out.length === 3) break;
64
+ }
65
+ return out;
66
+ }
67
+
68
+ const NUMBERS_RE = /\d+(?:[.,]\d+)?/g;
69
+
70
+ function numbers(s: string): Set<string> {
71
+ return new Set(s.match(NUMBERS_RE) ?? []);
72
+ }
73
+
74
+ // The connective prose a guidance sentence is full of. Kept small on purpose:
75
+ // the point is only to stop a sentence's grammar from counting as topical
76
+ // overlap with everything else in the store.
77
+ const WORD_STOP = new Set([
78
+ "the",
79
+ "and",
80
+ "for",
81
+ "with",
82
+ "that",
83
+ "this",
84
+ "from",
85
+ "have",
86
+ "has",
87
+ "was",
88
+ "were",
89
+ "are",
90
+ "not",
91
+ "only",
92
+ "must",
93
+ "should",
94
+ "would",
95
+ "could",
96
+ "will",
97
+ "shall",
98
+ "then",
99
+ "than",
100
+ "per",
101
+ "via",
102
+ "its",
103
+ ]);
104
+
105
+ /** Content words (length >= 3, letter-initial, so "5.0" never qualifies). */
106
+ function topicWords(s: string): Set<string> {
107
+ return new Set(
108
+ (s.toLowerCase().match(/[a-z][a-z0-9_-]{2,}/g) ?? []).filter(
109
+ (w) => !WORD_STOP.has(w),
110
+ ),
111
+ );
112
+ }
113
+
114
+ function sharesTopic(a: Set<string>, b: Set<string>): boolean {
115
+ for (const w of a) if (b.has(w)) return true;
116
+ return false;
117
+ }
118
+
119
+ /**
120
+ * One row per pre-pass quote. A model candidate that already carries the
121
+ * verbatim quote keeps its phrasing; one that states the same numbers keeps
122
+ * its phrasing and gains the quote + the guided flag EVEN IF the model left
123
+ * the flag off — clearing guidance by omission is exactly the measured miss
124
+ * mode. An unmatched quote becomes a deterministic fallback row, so the
125
+ * emission the model skipped still lands.
126
+ */
127
+ export function mergeGuidedCandidates(
128
+ quotes: string[],
129
+ candidates: CaptureCandidate[],
130
+ ): CaptureCandidate[] {
131
+ const out = [...candidates];
132
+ for (const quote of quotes) {
133
+ const nums = numbers(quote);
134
+ const topics = topicWords(quote);
135
+ // Two boundaries the first version lacked (#364 review):
136
+ // - ONE quote per candidate. Re-matching a candidate that already carries a
137
+ // quote overwrote the first fact, so three user sentences all stating
138
+ // 10.0 stored a single row.
139
+ // - a shared number plus a shared CONTENT word. A number alone matches a
140
+ // version label as happily as a measurement, which marked an unrelated
141
+ // "Release 5.0" row with a refill-threshold quote.
142
+ // The cost is deliberate: a model phrasing that shares no word with the
143
+ // user's sentence now yields an extra fallback row instead of a merge. The
144
+ // fact survives either way; a merge that quotes the wrong fact does not.
145
+ const match = out.find((c) => {
146
+ if (c.original !== undefined) return normWs(c.original) === quote;
147
+ if (normWs(c.content) === quote) return true;
148
+ return (
149
+ nums.size > 0 &&
150
+ [...numbers(c.content)].some((n) => nums.has(n)) &&
151
+ sharesTopic(topicWords(c.content), topics)
152
+ );
153
+ });
154
+ if (match) {
155
+ match.guided = true;
156
+ match.original = quote;
157
+ continue;
158
+ }
159
+ const content = `User-stated guidance: "${quote}"`.slice(0, 600);
160
+ out.push({
161
+ type: "context",
162
+ scope: "user-guidance",
163
+ content,
164
+ guided: true,
165
+ original: quote,
166
+ });
167
+ }
168
+ return out;
169
+ }
170
+
171
+ /**
172
+ * The write-path validator (design §4.3): a guided candidate carrying a
173
+ * quote the user never wrote is refused, not silently stripped — the
174
+ * deterministic pre-pass re-offers the fact with the true quote on the same
175
+ * pass, which makes the miss a retriable event. A guided candidate with NO
176
+ * quote is the model's own judgment and passes (unchanged behavior).
177
+ * Returns the survivors plus the refused quotes for evidence.
178
+ */
179
+ export function validateGuidedQuotes(
180
+ candidates: CaptureCandidate[],
181
+ userText: string,
182
+ ): { kept: CaptureCandidate[]; refused: string[] } {
183
+ const hay = normWs(userText);
184
+ const kept: CaptureCandidate[] = [];
185
+ const refused: string[] = [];
186
+ for (const c of candidates) {
187
+ if (c.guided === true && c.original !== undefined) {
188
+ const q = normWs(c.original);
189
+ if (!hay.includes(q)) {
190
+ refused.push(q);
191
+ continue;
192
+ }
193
+ c.original = q;
194
+ }
195
+ kept.push(c);
196
+ }
197
+ return { kept, refused };
198
+ }
@@ -9,7 +9,17 @@ export function lagSince(messages: unknown, now = Date.now()): number | null {
9
9
  let newest = 0;
10
10
  for (const raw of Array.isArray(messages) ? messages : []) {
11
11
  const m = raw as Record<string, any>;
12
- const at = m?.time?.updated ?? m?.createdAt ?? m?.created ?? m?.timestamp;
12
+ // The real 2.2.x session context carries time.created/time.completed
13
+ // (fixtures/host-session-context-2.2.5.json); time.updated was the only
14
+ // time.* field read, so every live capture_lag line recorded no lag at
15
+ // all. Read the whole family; the legacy flat names stay for old shapes.
16
+ const at =
17
+ m?.time?.updated ??
18
+ m?.time?.completed ??
19
+ m?.time?.created ??
20
+ m?.createdAt ??
21
+ m?.created ??
22
+ m?.timestamp;
13
23
  const ms =
14
24
  typeof at === "number"
15
25
  ? at
@@ -21,6 +21,14 @@ export interface CaptureCandidate {
21
21
  ref?: string;
22
22
  claim?: string;
23
23
  klass?: "spec" | "behavior";
24
+ /**
25
+ * Verbatim user utterance behind a guided row (bench mystery 2, candidate
26
+ * 4): the capture model's paraphrase of a hint made the bench's exact-text
27
+ * needle miss a row that actually rode. The runtime verifies this against
28
+ * the transcript the model saw — a quote that is not a substring is dropped,
29
+ * so a stored original is the user's own words.
30
+ */
31
+ original?: string;
24
32
  }
25
33
 
26
34
  // Keywords are the vocabulary bridge for the strict-paraphrase wall, mined from
@@ -65,6 +73,13 @@ export function buildCapturePrompt(
65
73
  '- Worked example (only when the user actually states this requirement): user says "The constant TAX_RATE in src/pricing.ts must be 0.0825." Emit:',
66
74
  '{"type":"context","scope":"pricing","content":"The constant TAX_RATE in src/pricing.ts must be 0.0825.","kw":["TAX_RATE","sales tax"],"guided":true,"ref":"TAX_RATE","claim":"0.0825","klass":"spec"}',
67
75
  "- A guided row states the user's value or rule and NOTHING more: never claim what hidden tests, graders or suites 'encode' — you cannot see them, and the claim makes the row impossible to check.",
76
+ // Mystery 2 (FINDINGS §3): the guided hint reached pass 2 on the wire in
77
+ // 3 of 4 t3 runs, and the miss could not be attributed — capture may have
78
+ // paraphrased the hint, so the bench's exact-text needle missed a row that
79
+ // actually rode. Storing the user's verbatim words makes the needle match
80
+ // deterministic; the runtime drops any quote that is not a transcript
81
+ // substring, so this field can only ever carry what the user actually said.
82
+ '- When guided, also output "original": the user\'s own words for this fact, copied VERBATIM from a user: line or the REQUESTS block — no paraphrase, no reordering, at most 300 characters. Omit original when no single user line states the fact.',
68
83
  "- Keep: decisions made, working commands, user preferences, blockers hit, durable context, conventions.",
69
84
  "- Skip: anything derivable from the code or git history, small talk, and details that only mattered inside this conversation.",
70
85
  ...(knownList
@@ -1,28 +1,38 @@
1
1
  // Opt-in capture configuration and dispatch (#168). Cooldowns remain process-wide;
2
2
  // subscriptions and dispatch closures belong to one setup instance.
3
3
  import type { Cleanup } from "@opencode/plugin/promise/plugin";
4
+ import { cmpTs } from "../core/cmp-ts.ts";
4
5
  import { setCurrent } from "../core/state.ts";
6
+ import { AUTO_CAPTURE_TAG, USER_GUIDED_TAG } from "../core/tags.ts";
5
7
  import { record, recordCaptureLag } from "../evidence/record.ts";
6
8
  import { type GateContext, runWriteGate } from "../gate/gate.ts";
7
9
  import { captureSessionID } from "../identity/host-events.ts";
8
10
  import { bindSessionProvisional, writeTarget } from "../identity/repokey.ts";
9
- import { quarantineCandidate } from "../store/quarantine/quarantine.ts";
10
- import { redactSecrets } from "../store/secrets.ts";
11
- import { parseCandidates, parseModelRef } from "./candidates.ts";
12
- import { lagSince } from "./lag.ts";
13
- import { buildCapturePrompt } from "./prompt.ts";
14
- import { type SessionModelRef, sessionModel } from "./session-model.ts";
15
- import { flattenTranscript, splitTranscript } from "./transcript.ts";
16
- import { AUTO_CAPTURE_TAG, USER_GUIDED_TAG } from "../core/tags.ts";
17
11
  import { loadAll } from "../store/files/load.ts";
18
12
  import { isInjectable } from "../store/model/predicates.ts";
19
13
  import {
14
+ type Reader,
20
15
  readerFromSid,
21
16
  visibleTo,
22
- type Reader,
23
17
  } from "../store/model/visibility.ts";
18
+ import { quarantineCandidate } from "../store/quarantine/quarantine.ts";
24
19
  import { flattenMemoryText } from "../store/sanitize.ts";
25
- import { cmpTs } from "../core/cmp-ts.ts";
20
+ import { redactSecrets } from "../store/secrets.ts";
21
+ import { parseCandidates, parseModelRef } from "./candidates.ts";
22
+ import {
23
+ findGuidedQuotes,
24
+ mergeGuidedCandidates,
25
+ normWs,
26
+ validateGuidedQuotes,
27
+ } from "./guided-rules.ts";
28
+ import { lagSince } from "./lag.ts";
29
+ import { buildCapturePrompt } from "./prompt.ts";
30
+ import { type SessionModelRef, sessionModel } from "./session-model.ts";
31
+ import {
32
+ flattenTranscript,
33
+ splitTranscript,
34
+ userTurnText,
35
+ } from "./transcript.ts";
26
36
 
27
37
  interface CaptureHost {
28
38
  options?: Record<string, unknown>;
@@ -43,7 +53,18 @@ interface CaptureHost {
43
53
  interface CaptureDependencies {
44
54
  instanceDir: string | undefined;
45
55
  gateContext: (sid?: string) => GateContext;
46
- guarded: (name: string, fn: () => Promise<void>) => Promise<void>;
56
+ guarded: (
57
+ name: string,
58
+ fn: () => Promise<void>,
59
+ reportable?: () => boolean,
60
+ ) => Promise<void>;
61
+ /**
62
+ * Fix A (FINDINGS 2026-11-08 §4b): called after a guided row is promoted,
63
+ * so every tracked session recomputes its epoch and the NEXT request of
64
+ * each session carries the row. Absent (or failing) changes nothing: the
65
+ * row is stored either way and a later request re-reads the store.
66
+ */
67
+ onGuidedPromoted?: (sid: string) => void | Promise<void>;
47
68
  }
48
69
 
49
70
  // Tag on store rows captured by the COMPACTION trigger (issue #41). Rows keep
@@ -148,7 +169,7 @@ export function captureTriggerFor(event: unknown): boolean {
148
169
 
149
170
  export function configureAutoCapture(
150
171
  ctx: CaptureHost,
151
- { instanceDir, gateContext, guarded }: CaptureDependencies,
172
+ { instanceDir, gateContext, guarded, onGuidedPromoted }: CaptureDependencies,
152
173
  ) {
153
174
  let onCompactCapture: ((sid: string, messages: unknown) => void) | undefined;
154
175
  let captureCleanup: Cleanup | undefined;
@@ -164,6 +185,9 @@ export function configureAutoCapture(
164
185
  // the one the user typed is worse than the tax it replaces.
165
186
  const omitted = captureModelOpt === undefined;
166
187
  const captureMax = Number(ctx.options.captureMax) || 3;
188
+ // Deterministic guided-candidate pre-pass (POC): default OFF, the bench
189
+ // picks the default-on arm (FINDINGS 2026-11-08 §4.4).
190
+ const guidedRules = ctx.options?.captureGuidedRules === true;
167
191
  const captureOnCompact = ctx.options?.captureOnCompact !== false;
168
192
  const modelRef = omitted ? null : parseModelRef(captureModelOpt);
169
193
  if (!omitted && !modelRef) {
@@ -182,6 +206,39 @@ export function configureAutoCapture(
182
206
  );
183
207
  } else {
184
208
  const controller = new AbortController();
209
+ // #211 (LIFE-1): passes in flight, tracked so teardown can stop them.
210
+ // Aborting the subscription is not enough on its own: `generate.text`
211
+ // does not take the signal, so a pass parked mid-model-call when the
212
+ // host disposes this instance wakes up afterwards and used to run the
213
+ // whole write gate against a store its caller had already torn down —
214
+ // gate receipts, promoted rows, supersession. The contract is bounded
215
+ // and explicit:
216
+ // 1. cleanup aborts the subscription, so no NEW pass starts;
217
+ // 2. every pass checks the signal after the model call and between
218
+ // candidates, and stops BEFORE the next gate run — a gate already
219
+ // mutating is never cut in half, because a half-applied gate is
220
+ // worse than a late one;
221
+ // 3. cleanup then drains the tracked passes up to DRAIN_LIMIT_MS, so
222
+ // a caller that removes the store right after cleanup sees nothing
223
+ // straggling. A generate that outlives the bound is covered by (2),
224
+ // not by the drain: teardown never waits on the model.
225
+ const DRAIN_LIMIT_MS = 1000;
226
+ const inFlight = new Set<Promise<unknown>>();
227
+ function track<T>(pass: Promise<T>): Promise<T> {
228
+ const wrapped = pass.finally(() => inFlight.delete(wrapped));
229
+ inFlight.add(wrapped);
230
+ return wrapped;
231
+ }
232
+ async function drainInFlight(): Promise<void> {
233
+ if (!inFlight.size) return;
234
+ let timer: ReturnType<typeof setTimeout> | undefined;
235
+ const bound = new Promise<void>((resolve) => {
236
+ timer = setTimeout(resolve, DRAIN_LIMIT_MS);
237
+ });
238
+ await Promise.race([Promise.allSettled([...inFlight]), bound]).finally(
239
+ () => clearTimeout(timer),
240
+ );
241
+ }
185
242
  const eventApi = ctx.event;
186
243
  const generateApi = ctx.generate;
187
244
  // Arrow wrapper: keep the receiver bound. The harness fakes are closures,
@@ -294,6 +351,12 @@ export function configureAutoCapture(
294
351
  let msgs = seededMsgs;
295
352
  if (transcript.length < 200) {
296
353
  msgs = await contextFn({ sessionID: sid });
354
+ // #211: disposed while the host was answering. The drain in cleanup()
355
+ // waits a bound, not forever, so this is the normal outcome of a
356
+ // teardown during a slow context read — and everything below writes:
357
+ // the thin-transcript receipt below, then the model call. Silent, for
358
+ // the same reason the post-model check is.
359
+ if (controller.signal.aborted) return;
297
360
  transcript = flattenTranscript(msgs);
298
361
  }
299
362
  if (transcript.length < 200) {
@@ -331,6 +394,15 @@ export function configureAutoCapture(
331
394
  const partitioned = split.work.length >= 200;
332
395
  const work = partitioned ? split.work : transcript;
333
396
  const userProse = partitioned ? split.user : "";
397
+ // The user's turns, decoded from the message array rather than read back
398
+ // out of rendered text (#364 review). Everything that vouches for "these
399
+ // are the user's own words" goes through this.
400
+ const userTurns = userTurnText(msgs);
401
+ // Hoisted out of the prompt literal so the disposal check below runs
402
+ // BEFORE the model call: this read is awaited, so it is its own window
403
+ // into a teardown (#211).
404
+ const knownRows = await knownRowsFor(captureReader);
405
+ if (controller.signal.aborted) return;
334
406
  const out = await generateApi.text({
335
407
  model,
336
408
  // Redact the COMPLETE transcript, THEN apply the character budget
@@ -342,12 +414,105 @@ export function configureAutoCapture(
342
414
  redactSecrets(work).slice(-7000),
343
415
  captureMax,
344
416
  redactSecrets(userProse).slice(-1500),
345
- await knownRowsFor(captureReader),
417
+ knownRows,
346
418
  ),
347
419
  });
348
420
  const text = typeof out === "string" ? out : (out?.text ?? "");
349
- const candidates = parseCandidates(text, captureMax);
421
+ // #211: disposed while the model call was in flight. Stop here — the
422
+ // gate, the rows and the receipts below all write to a store the
423
+ // caller may already have removed. Silent on purpose: a receipt here
424
+ // is the ENOENT teardown noise this check exists to eliminate, and
425
+ // the drain in cleanup means the pass is finished, not lost mid-air.
426
+ if (controller.signal.aborted) return;
427
+ let candidates = parseCandidates(text, captureMax);
428
+ // Deterministic guided pre-pass (POC, FINDINGS 2026-11-08 §4, option
429
+ // `captureGuidedRules`): the user's own lines decide what is guided —
430
+ // the model phrases it but cannot veto it, and a quote the user never
431
+ // wrote is refused at the write boundary (retriable, not silent).
432
+ // The scanned text is the structured USER turns and nothing else
433
+ // (#364 review): assistant output never enters the haystack, so a stored
434
+ // quote can only be what the user said. Filtering rendered lines by a
435
+ // `user:` prefix did not do this — it accepted a `user:` label quoted
436
+ // INSIDE an assistant message as provenance.
437
+ if (guidedRules) {
438
+ const ruleUserText = redactSecrets(userTurns);
439
+ if (!ruleUserText.trim()) {
440
+ // No user turn in what was mined (a seeded transcript with no message
441
+ // array, or a session that has only said nothing). Fail closed: with
442
+ // no roles there is nothing to vouch for, so the lane stays shut
443
+ // rather than minting a row from prose of unknown origin.
444
+ //
445
+ // #364 review round 2: the receipt alone does not shut it. A guided
446
+ // candidate the MODEL supplied would still have been stored with its
447
+ // unverified quote, so with no user turn nothing is attributable and
448
+ // the guided flag plus the quote come off. The distilled prose stays:
449
+ // an ordinary capture row is what the same model output produces with
450
+ // the option off, and dropping the row would trade a provenance fix
451
+ // for a recall loss the plugin has no licence to make here.
452
+ let withheld = 0;
453
+ for (const c of candidates) {
454
+ if (c.guided !== true) continue;
455
+ c.guided = false;
456
+ c.original = undefined;
457
+ withheld++;
458
+ }
459
+ await record(
460
+ "auto_capture_rules",
461
+ {
462
+ session: sid,
463
+ trigger,
464
+ quotes: 0,
465
+ refused: 0,
466
+ withheld,
467
+ skipped: "no_user_turn",
468
+ model: modelTag,
469
+ },
470
+ false,
471
+ sid,
472
+ captureGate.evidenceContext,
473
+ );
474
+ } else {
475
+ const quotes = findGuidedQuotes(ruleUserText);
476
+ const checked = validateGuidedQuotes(candidates, ruleUserText);
477
+ candidates = mergeGuidedCandidates(quotes, checked.kept);
478
+ await record(
479
+ "auto_capture_rules",
480
+ {
481
+ session: sid,
482
+ trigger,
483
+ quotes: quotes.length,
484
+ refused: checked.refused.length,
485
+ model: modelTag,
486
+ },
487
+ false,
488
+ sid,
489
+ captureGate.evidenceContext,
490
+ );
491
+ }
492
+ } else {
493
+ // Lenient check (default): a guided "original" must appear in the
494
+ // user's own turns. The prompt asks for a quote "copied VERBATIM from
495
+ // a user: line or the REQUESTS block", so the haystack is exactly that
496
+ // (#364 review: the mined WORK text used to be in here too, which
497
+ // vouched for a quote lifted out of assistant output). Whitespace is
498
+ // normalised — the model may collapse runs of spaces. A failed check
499
+ // drops the field, never the row: the distilled prose still
500
+ // deserved storage, it just cannot be vouched for as the user's
501
+ // own words.
502
+ const quoteHay = redactSecrets(userTurns).replace(/\s+/g, " ");
503
+ for (const c of candidates) {
504
+ if (
505
+ c.original !== undefined &&
506
+ !quoteHay.includes(normWs(c.original))
507
+ )
508
+ c.original = undefined;
509
+ }
510
+ }
350
511
  for (const c of candidates) {
512
+ // Between candidates, never inside a gate run: a supersession that
513
+ // half-applied is a store the next session cannot trust.
514
+ if (controller.signal.aborted) return;
515
+ const original = c.original;
351
516
  const durable: string[] = [];
352
517
  let outcome: Awaited<ReturnType<typeof runWriteGate>>;
353
518
  try {
@@ -361,6 +526,10 @@ export function configureAutoCapture(
361
526
  ...(c.ref ? { ref: c.ref } : {}),
362
527
  ...(c.claim ? { claim: c.claim } : {}),
363
528
  ...(c.klass ? { klass: c.klass } : {}),
529
+ // Verified verbatim utterance (see quoteHay above): injection
530
+ // renders it so the user's exact words ride the next session's
531
+ // request bytes.
532
+ ...(original ? { original } : {}),
364
533
  tags: [
365
534
  AUTO_CAPTURE_TAG,
366
535
  ...(trigger === "compaction" ? [CAPTURE_COMPACT_TAG] : []),
@@ -415,11 +584,32 @@ export function configureAutoCapture(
415
584
  : "absent",
416
585
  }
417
586
  : {}),
587
+ // Stage telemetry (mystery 2): the row's identity and guided
588
+ // standing at the moment of storage, so a later L6h miss can be
589
+ // joined to the exact row that did or did not enter the hint
590
+ // channel, and to whether its verbatim quote survived the
591
+ // substring check.
592
+ ...(outcome.action === "promoted" ? { row: outcome.ts } : {}),
593
+ ...(c.guided ? { guided: true } : {}),
594
+ ...(original ? { orig: true } : {}),
418
595
  },
419
596
  false,
420
597
  sid,
421
598
  captureGate.evidenceContext,
422
599
  );
600
+ // Fix A (FINDINGS 2026-11-08 §4b): a guided row promoted after a
601
+ // session froze its bytes could never enter the hint lane (bench
602
+ // run 5: capture landed 9 min into pass 2, epoch never moved).
603
+ // Recompute every tracked epoch now, so the next request of each
604
+ // session carries the row. Fail-soft: the row is stored either way,
605
+ // and a later request re-reads the store on its own.
606
+ if (c.guided && outcome.action === "promoted" && onGuidedPromoted) {
607
+ try {
608
+ await onGuidedPromoted(sid);
609
+ } catch {
610
+ /* fail-soft — see above */
611
+ }
612
+ }
423
613
  }
424
614
  await recordCaptureLag(
425
615
  sid,
@@ -449,8 +639,12 @@ export function configureAutoCapture(
449
639
  let opGate: GateContext | undefined;
450
640
  try {
451
641
  opGate = bindCapture(sid);
452
- await captureSession(sid, "", "idle", undefined, opGate);
642
+ await track(captureSession(sid, "", "idle", undefined, opGate));
453
643
  } catch (err) {
644
+ // Teardown is not a capture failure: after cleanup the store may
645
+ // be gone, and a receipt here would be the ENOENT noise #211
646
+ // reports. The abort check inside captureSession is the signal.
647
+ if (controller.signal.aborted) return;
454
648
  // Fail-closed for the SESSION, never silent in the store: the
455
649
  // same silence that hid the 2.2.5 shape break would make a
456
650
  // throwing capture indistinguishable from one that never ran.
@@ -474,7 +668,10 @@ export function configureAutoCapture(
474
668
  // the subscription itself ended (abort or host error); nothing to do
475
669
  }
476
670
  })();
477
- captureCleanup = () => controller.abort();
671
+ captureCleanup = async () => {
672
+ controller.abort();
673
+ await drainInFlight();
674
+ };
478
675
 
479
676
  // The compaction trigger needs no extra subscription: the session
480
677
  // compaction hook (registered above) calls through this seam. The
@@ -490,13 +687,24 @@ export function configureAutoCapture(
490
687
  // Same freeze as the idle trigger, and for the same reason: sync,
491
688
  // before guarded() starts awaiting.
492
689
  const opGate = bindCapture(sid);
493
- void guarded("session.compaction (auto-capture)", () =>
494
- captureSession(
495
- sid,
496
- flattenTranscript(messages),
497
- "compaction",
498
- messages,
499
- opGate,
690
+ // Tracked, not just fired: cleanup must be able to drain this pass
691
+ // (#211), which is the only reason the seam keeps the promise.
692
+ void track(
693
+ // The predicate, not just the checks inside the pass: a rejection
694
+ // from the awaited model call skips every abort check that follows
695
+ // it and lands in the generic reporter, which would append
696
+ // `hook_error` to a store cleanup() has already released (#211).
697
+ guarded(
698
+ "session.compaction (auto-capture)",
699
+ () =>
700
+ captureSession(
701
+ sid,
702
+ flattenTranscript(messages),
703
+ "compaction",
704
+ messages,
705
+ opGate,
706
+ ),
707
+ () => !controller.signal.aborted,
500
708
  ),
501
709
  );
502
710
  };