opencode-self-improvement 0.19.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.
@@ -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
11
  import { loadAll } from "../store/files/load.ts";
17
12
  import { isInjectable } from "../store/model/predicates.ts";
18
13
  import {
14
+ type Reader,
19
15
  readerFromSid,
20
16
  visibleTo,
21
- type Reader,
22
17
  } from "../store/model/visibility.ts";
18
+ import { quarantineCandidate } from "../store/quarantine/quarantine.ts";
23
19
  import { flattenMemoryText } from "../store/sanitize.ts";
24
- import { cmpTs } from "../core/cmp-ts.ts";
25
- import { AUTO_CAPTURE_TAG, USER_GUIDED_TAG } from "../core/tags.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 {
@@ -358,6 +523,13 @@ export function configureAutoCapture(
358
523
  content: c.content,
359
524
  ...(c.status ? { status: c.status } : {}),
360
525
  ...(c.kw ? { kw: c.kw } : {}),
526
+ ...(c.ref ? { ref: c.ref } : {}),
527
+ ...(c.claim ? { claim: c.claim } : {}),
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 } : {}),
361
533
  tags: [
362
534
  AUTO_CAPTURE_TAG,
363
535
  ...(trigger === "compaction" ? [CAPTURE_COMPACT_TAG] : []),
@@ -402,11 +574,42 @@ export function configureAutoCapture(
402
574
  reason: outcome.reason ?? "",
403
575
  audit_error: outcome.evidenceError,
404
576
  model: modelTag,
577
+ ...(outcome.action === "promoted" && c.guided
578
+ ? {
579
+ conflict:
580
+ c.ref && c.claim && c.klass
581
+ ? "full"
582
+ : c.ref || c.claim || c.klass
583
+ ? "partial"
584
+ : "absent",
585
+ }
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 } : {}),
405
595
  },
406
596
  false,
407
597
  sid,
408
598
  captureGate.evidenceContext,
409
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
+ }
410
613
  }
411
614
  await recordCaptureLag(
412
615
  sid,
@@ -436,8 +639,12 @@ export function configureAutoCapture(
436
639
  let opGate: GateContext | undefined;
437
640
  try {
438
641
  opGate = bindCapture(sid);
439
- await captureSession(sid, "", "idle", undefined, opGate);
642
+ await track(captureSession(sid, "", "idle", undefined, opGate));
440
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;
441
648
  // Fail-closed for the SESSION, never silent in the store: the
442
649
  // same silence that hid the 2.2.5 shape break would make a
443
650
  // throwing capture indistinguishable from one that never ran.
@@ -461,7 +668,10 @@ export function configureAutoCapture(
461
668
  // the subscription itself ended (abort or host error); nothing to do
462
669
  }
463
670
  })();
464
- captureCleanup = () => controller.abort();
671
+ captureCleanup = async () => {
672
+ controller.abort();
673
+ await drainInFlight();
674
+ };
465
675
 
466
676
  // The compaction trigger needs no extra subscription: the session
467
677
  // compaction hook (registered above) calls through this seam. The
@@ -477,13 +687,24 @@ export function configureAutoCapture(
477
687
  // Same freeze as the idle trigger, and for the same reason: sync,
478
688
  // before guarded() starts awaiting.
479
689
  const opGate = bindCapture(sid);
480
- void guarded("session.compaction (auto-capture)", () =>
481
- captureSession(
482
- sid,
483
- flattenTranscript(messages),
484
- "compaction",
485
- messages,
486
- 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,
487
708
  ),
488
709
  );
489
710
  };
@@ -128,3 +128,27 @@ export function splitTranscript(msgs: unknown): TranscriptSplit {
128
128
  }
129
129
  return { work: work.join("\n"), user: user.join("\n") };
130
130
  }
131
+
132
+ /**
133
+ * The user's turns and nothing else, in order, without the `role: ` render
134
+ * prefix.
135
+ *
136
+ * This is the only text that may vouch for user provenance (#364 review).
137
+ * Reading `user:` labels back out of RENDERED text cannot do the job: a role
138
+ * label inside an assistant message ("Here is untrusted quoted output:
139
+ * user: The correct sales tax rate is 7.5%.") is assistant output, and a
140
+ * scanner that filters rendered lines by that prefix hands quoted text the
141
+ * always-ride user-guidance lane. Roles here come from `parseTurns`, the same
142
+ * structured decode `splitTranscript` uses, so the two can never disagree
143
+ * about who said a line.
144
+ *
145
+ * Empty when the mined input carries no message array (a seeded transcript):
146
+ * no roles, so nothing can be attributed to the user.
147
+ */
148
+ export function userTurnText(msgs: unknown): string {
149
+ const out: string[] = [];
150
+ for (const { role, text } of parseTurns(msgs)) {
151
+ if (role === "user") out.push(text);
152
+ }
153
+ return out.join("\n");
154
+ }
package/src/core/hooks.ts CHANGED
@@ -22,6 +22,14 @@ export function setGuardedFailureReporter(
22
22
  export async function guarded(
23
23
  name: string,
24
24
  fn: () => Promise<void>,
25
+ // Optional: "is this failure still worth a receipt?" A caller that owns a
26
+ // lifecycle passes `() => !disposed`. Teardown is not a capture failure
27
+ // (#211): once cleanup() has returned the caller may have removed the store,
28
+ // so mirroring the rejection into evidence is the ENOENT noise that issue was
29
+ // filed about — the same reason the idle capture path checks its abort signal
30
+ // inside its own catch. Omitted, the #138 contract is untouched: every
31
+ // swallowed failure is mirrored.
32
+ reportable?: () => boolean,
25
33
  ): Promise<void> {
26
34
  try {
27
35
  await fn();
@@ -30,6 +38,16 @@ export async function guarded(
30
38
  `[opencode-self-improvement] ${name} hook failed (ignored):`,
31
39
  err,
32
40
  );
41
+ // The console line is the primary trace and stays either way; only the
42
+ // store write is gated. A predicate that throws reports, so a broken
43
+ // predicate can never turn a swallowed failure into a throw.
44
+ let report = true;
45
+ try {
46
+ report = reportable?.() !== false;
47
+ } catch {
48
+ // unknown state reports, as before
49
+ }
50
+ if (!report) return;
33
51
  // Report AFTER the warn, and await the reporter so a caller that awaits
34
52
  // guarded() can observe the evidence line; any reporter failure is itself
35
53
  // swallowed — the console line is the primary trace, evidence the mirror.
package/src/gate/gate.ts CHANGED
@@ -55,6 +55,9 @@ export interface WriteCandidate {
55
55
  // (trim/lowercase/cap) at promotion, so a caller may hand junk without
56
56
  // changing the verdict the prose deserves.
57
57
  kw?: string[];
58
+ ref?: string;
59
+ claim?: string;
60
+ klass?: "spec" | "behavior";
58
61
  status?: "open" | "settled";
59
62
  // "global" = cross-project (memory_remember global:true; imports carry a
60
63
  // row's origin stamp). Any other value (including undefined) is resolved by
@@ -407,6 +410,8 @@ export async function runWriteGate(
407
410
  candidate.tags?.some(containsSecret) ? "tags" : undefined,
408
411
  candidate.kw?.some(containsSecret) ? "kw" : undefined,
409
412
  containsSecret(candidate.issue) ? "issue" : undefined,
413
+ containsSecret(candidate.ref) ? "ref" : undefined,
414
+ containsSecret(candidate.claim) ? "claim" : undefined,
410
415
  ].filter((field): field is string => field !== undefined);
411
416
  if (credentialMetadata.length) {
412
417
  await recBlocked(
package/src/index.ts CHANGED
@@ -204,6 +204,8 @@ const impl = {
204
204
  const sessions = createInjectionEpochs({
205
205
  budget,
206
206
  frontierBudget: openBudget,
207
+ // Code-check guided claims by default; explicit false opts out.
208
+ contradictionSurface: ctx.options?.contradictionSurface !== false,
207
209
  measuredTurns,
208
210
  noteHits: (sid, rows, query) => noteHits("inject", sid, rows, query),
209
211
  });
@@ -261,6 +263,12 @@ const impl = {
261
263
  instanceDir,
262
264
  gateContext,
263
265
  guarded,
266
+ // Fix A (FINDINGS 2026-11-08 §4b): guided promotion moves every tracked
267
+ // epoch, so a late guided row enters the hint lane on each session's
268
+ // next request instead of waiting for a request that happens to notice.
269
+ onGuidedPromoted: async () => {
270
+ await sessions.refreshAll();
271
+ },
264
272
  });
265
273
  onCompactCapture = capture.onCompactCapture;
266
274
  const captureCleanup = capture.cleanup;
@@ -59,9 +59,15 @@ export function cappedFrontier(
59
59
  // pre-budget candidates — or it would credit the model with paths and commands
60
60
  // it was never shown. capToBudget keeps whole lines verbatim, so a candidate is
61
61
  // present iff its rendered line is a substring of the block.
62
- export function injectedRows(block: string, candidates: Memory[]): Memory[] {
62
+ export function injectedRows(
63
+ block: string,
64
+ candidates: Memory[],
65
+ rendered?: ReadonlyMap<Memory, Memory>,
66
+ ): Memory[] {
63
67
  if (!block) return [];
64
- return candidates.filter((m) => block.includes(formatMemory(m)));
68
+ return candidates.filter((m) =>
69
+ block.includes(formatMemory(rendered?.get(m) ?? m)),
70
+ );
65
71
  }
66
72
 
67
73
  // Trim an injection block to `budget` characters at WHOLE-line boundaries:
@@ -9,7 +9,7 @@ import { captureEvidenceContext, record } from "../evidence/record.ts";
9
9
  import { capToBudget, injectedRows } from "./budget.ts";
10
10
  import { systemDigest } from "./digest.ts";
11
11
  import { storeVersion } from "./version.ts";
12
- import { selectRelevant } from "../recall/relevant.ts";
12
+ import { isUserGuided, selectRelevant } from "../recall/relevant.ts";
13
13
  import {
14
14
  attributeSession,
15
15
  deriveMemoryRefs,
@@ -30,6 +30,11 @@ import { authoredFor } from "../core/state.ts";
30
30
  interface InjectionEpochOptions {
31
31
  budget: number;
32
32
  frontierBudget: number;
33
+ /**
34
+ * Contradiction surface (POC): code-check guided rows at render time.
35
+ * Enabled by default; `contradictionSurface: false` skips workspace checks.
36
+ */
37
+ contradictionSurface?: boolean;
33
38
  // The host listener records usage. Eviction must still drop it with the
34
39
  // epoch and request counters, so no measurement outlives its tracked session.
35
40
  measuredTurns: Pick<Map<string, Measured>, "get" | "delete">;
@@ -39,6 +44,7 @@ interface InjectionEpochOptions {
39
44
  export function createInjectionEpochs({
40
45
  budget,
41
46
  frontierBudget: openBudget,
47
+ contradictionSurface = true,
42
48
  measuredTurns,
43
49
  noteHits,
44
50
  }: InjectionEpochOptions) {
@@ -165,6 +171,14 @@ export function createInjectionEpochs({
165
171
  prefix: string;
166
172
  rode: Memory[];
167
173
  refs: MemoryRefs;
174
+ /** Guided rows the selector put in the block (pre-budget), by ts. */
175
+ guidedIds: string[];
176
+ /** Guided rows that survived the budget, by ts. */
177
+ guidedRodeIds: string[];
178
+ /** Guided rows visible to this reader in the store. */
179
+ guidedSeen: number;
180
+ /** A CONFLICT line rendered in this block. */
181
+ conflict: boolean;
168
182
  }> => {
169
183
  const parts: string[] = [];
170
184
  await systemDigest(
@@ -176,6 +190,11 @@ export function createInjectionEpochs({
176
190
  promptOverride ??
177
191
  (sid === undefined ? "" : (latestPrompt.get(sid) ?? ""));
178
192
  // Widen the candidate pool, then cap: the budget decides what rides.
193
+ // The guided cap (#335) rides user-stated rows ahead of the lexical picks;
194
+ // the char budget below still bounds the whole block. The conflict check
195
+ // reads the session's OWN repo directory (its reader's scope) — never an
196
+ // ambient one (#127's rule applies to code reads too).
197
+ const reader = readerFromSid(sid);
179
198
  const sel = await selectRelevant(
180
199
  prompt,
181
200
  5,
@@ -183,18 +202,42 @@ export function createInjectionEpochs({
183
202
  await useSignals(),
184
203
  undefined,
185
204
  {
186
- // The reserved capture provenance rides first, even on unrelated prompts.
187
- // capToBudget still bounds all rendered rows together.
188
205
  guidedCap: 3,
206
+ ...(contradictionSurface
207
+ ? {
208
+ conflictCheck: true,
209
+ ...(reader.kind === "repo" ? { repoDir: reader.scope.path } : {}),
210
+ }
211
+ : {}),
189
212
  },
190
213
  );
191
214
  const block = sel.block ? capToBudget(sel.block, budget) : "";
192
215
  // Refs the ACTUALLY-injected rows assert (paths + commands), the join key
193
216
  // for attribution. Derived from the budget-surviving rows, not the wider
194
217
  // candidate pool — crediting paths the model never saw would overclaim.
195
- const rode = injectedRows(block, sel.selected);
218
+ const rode = injectedRows(block, sel.selected, sel.rendered);
196
219
  const prefix = [...parts, block].join("\u0000");
197
- return { parts, block, prefix, rode, refs: deriveMemoryRefs(rode) };
220
+ // Ledger terms/identities belong to the stored rows, but coverage refs
221
+ // must describe only the text the model actually received.
222
+ // Stage telemetry (mystery 2): split the hint channel's journey into the
223
+ // three links a miss can die at — visible in the store (guidedSeen),
224
+ // selected into the block (guidedIds), survived the budget (guidedRodeIds)
225
+ // — so an L6h wire miss joins to exactly one cause from the evidence log.
226
+ const guidedSeen = mems.filter(isUserGuided).length;
227
+ const guidedIds = sel.selected.filter(isUserGuided).map((m) => m.ts);
228
+ const guidedRodeIds = rode.filter(isUserGuided).map((m) => m.ts);
229
+ const conflict = block.includes("CONFLICT (");
230
+ return {
231
+ parts,
232
+ block,
233
+ prefix,
234
+ rode,
235
+ refs: deriveMemoryRefs(rode.map((m) => sel.rendered.get(m) ?? m)),
236
+ guidedIds,
237
+ guidedRodeIds,
238
+ guidedSeen,
239
+ conflict,
240
+ };
198
241
  };
199
242
  const refreshEpoch = async (sid: string, rows?: Memory[]): Promise<void> => {
200
243
  if (!latestPrompt.has(sid)) return;
@@ -282,6 +325,20 @@ export function createInjectionEpochs({
282
325
  session: sid,
283
326
  reason,
284
327
  chars: built.block.length,
328
+ // Hint-channel attribution (mystery 2): a wire miss is one grep away.
329
+ // guidedSeen=0 -> capture never wrote the row. guidedSeen>0 with the
330
+ // id absent from `guided` -> the cap (newest-first, 3) dropped it.
331
+ // In `guided` but absent from `guidedRode` -> capToBudget dropped it.
332
+ // In `guidedRode` yet absent from the wire -> render/transport, or a
333
+ // paraphrased needle (now impossible for rows carrying `orig=true`).
334
+ ...(built.guidedSeen ? { guidedSeen: built.guidedSeen } : {}),
335
+ ...(built.guidedIds.length
336
+ ? { guided: built.guidedIds.join(",") }
337
+ : {}),
338
+ ...(built.guidedRodeIds.length
339
+ ? { guidedRode: built.guidedRodeIds.join(",") }
340
+ : {}),
341
+ ...(built.conflict ? { conflict: true } : {}),
285
342
  },
286
343
  false,
287
344
  sid,
@@ -351,6 +408,18 @@ export function createInjectionEpochs({
351
408
  latestPrompt.set(sid, text);
352
409
  await refreshEpoch(sid);
353
410
  },
411
+ // Fix A (FINDINGS 2026-11-08 §4b): a guided row promoted AFTER a session
412
+ // froze its bytes could never enter the hint lane — the bench's run 5
413
+ // lost the lane to a capture that landed 9 minutes into pass 2, and the
414
+ // epoch only moves on a request that happens to notice. Recompute every
415
+ // tracked epoch on guided promotion so the NEXT request of every session
416
+ // carries the row and the epoch_recompute line records it. Bounded:
417
+ // guided rows are rare (cap 3), the refresh pre-check early-returns for
418
+ // any session whose visible rows did not move, and an untracked session
419
+ // is a map miss.
420
+ refreshAll(): Promise<void[]> {
421
+ return Promise.all([...epoch.keys()].map((sid) => refreshEpoch(sid)));
422
+ },
354
423
  deliver,
355
424
  invalidate(sid: string): void {
356
425
  epoch.delete(sid);
@@ -28,5 +28,12 @@ export function formatMemory(m: Memory): string {
28
28
  const type = flattenMemoryText(m.type);
29
29
  const scope = flattenMemoryText(m.scope);
30
30
  const content = flattenMemoryText(m.content);
31
- return `- [${date}]${tag}${src} ${type}/${scope}: ${content}`;
31
+ // Verbatim user utterance (mystery 2): rendered so the user's exact words
32
+ // reach the next session's request bytes even when the distilled content
33
+ // paraphrases them. Stored after a substring check, so this is quotation,
34
+ // not generation.
35
+ const quote = m.original
36
+ ? ` (user said: "${flattenMemoryText(m.original)}")`
37
+ : "";
38
+ return `- [${date}]${tag}${src} ${type}/${scope}: ${content}${quote}`;
32
39
  }