opencode-self-improvement 0.20.0 → 0.22.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,47 @@
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 { setCurrent } from "../core/state.ts";
4
+ import { cmpTs } from "../core/cmp-ts.ts";
5
+ import { session, 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 {
30
+ advanceCaptureCursor,
31
+ captureCursor,
32
+ captureSignalSince,
33
+ deltaMessages,
34
+ guidedStatementInWindow,
35
+ prefixFingerprint,
36
+ transcriptReplaced,
37
+ } from "./policy.ts";
38
+ import { buildCapturePrompt } from "./prompt.ts";
39
+ import { type SessionModelRef, sessionModel } from "./session-model.ts";
40
+ import {
41
+ flattenTranscript,
42
+ splitTranscript,
43
+ userTurnText,
44
+ } from "./transcript.ts";
26
45
 
27
46
  interface CaptureHost {
28
47
  options?: Record<string, unknown>;
@@ -43,7 +62,18 @@ interface CaptureHost {
43
62
  interface CaptureDependencies {
44
63
  instanceDir: string | undefined;
45
64
  gateContext: (sid?: string) => GateContext;
46
- guarded: (name: string, fn: () => Promise<void>) => Promise<void>;
65
+ guarded: (
66
+ name: string,
67
+ fn: () => Promise<void>,
68
+ reportable?: () => boolean,
69
+ ) => Promise<void>;
70
+ /**
71
+ * Fix A (FINDINGS 2026-11-08 §4b): called after a guided row is promoted,
72
+ * so every tracked session recomputes its epoch and the NEXT request of
73
+ * each session carries the row. Absent (or failing) changes nothing: the
74
+ * row is stored either way and a later request re-reads the store.
75
+ */
76
+ onGuidedPromoted?: (sid: string) => void | Promise<void>;
47
77
  }
48
78
 
49
79
  // Tag on store rows captured by the COMPACTION trigger (issue #41). Rows keep
@@ -148,7 +178,7 @@ export function captureTriggerFor(event: unknown): boolean {
148
178
 
149
179
  export function configureAutoCapture(
150
180
  ctx: CaptureHost,
151
- { instanceDir, gateContext, guarded }: CaptureDependencies,
181
+ { instanceDir, gateContext, guarded, onGuidedPromoted }: CaptureDependencies,
152
182
  ) {
153
183
  let onCompactCapture: ((sid: string, messages: unknown) => void) | undefined;
154
184
  let captureCleanup: Cleanup | undefined;
@@ -164,7 +194,16 @@ export function configureAutoCapture(
164
194
  // the one the user typed is worse than the tax it replaces.
165
195
  const omitted = captureModelOpt === undefined;
166
196
  const captureMax = Number(ctx.options.captureMax) || 3;
197
+ // Deterministic guided-candidate pre-pass (POC): default OFF, the bench
198
+ // picks the default-on arm (FINDINGS 2026-11-08 §4.4).
199
+ const guidedRules = ctx.options?.captureGuidedRules === true;
167
200
  const captureOnCompact = ctx.options?.captureOnCompact !== false;
201
+ // #334: two cost levers, both OFF by default until the benchmark says which
202
+ // way to set them. `captureOnSignal` skips a capture whose turn produced
203
+ // nothing durable; `captureDelta` mines only the turns since the last
204
+ // capture instead of re-reading the whole session every time.
205
+ const captureOnSignal = ctx.options?.captureOnSignal === true;
206
+ const captureDelta = ctx.options?.captureDelta === true;
168
207
  const modelRef = omitted ? null : parseModelRef(captureModelOpt);
169
208
  if (!omitted && !modelRef) {
170
209
  // Invalid explicit model: skip registering the whole subscription
@@ -182,6 +221,39 @@ export function configureAutoCapture(
182
221
  );
183
222
  } else {
184
223
  const controller = new AbortController();
224
+ // #211 (LIFE-1): passes in flight, tracked so teardown can stop them.
225
+ // Aborting the subscription is not enough on its own: `generate.text`
226
+ // does not take the signal, so a pass parked mid-model-call when the
227
+ // host disposes this instance wakes up afterwards and used to run the
228
+ // whole write gate against a store its caller had already torn down —
229
+ // gate receipts, promoted rows, supersession. The contract is bounded
230
+ // and explicit:
231
+ // 1. cleanup aborts the subscription, so no NEW pass starts;
232
+ // 2. every pass checks the signal after the model call and between
233
+ // candidates, and stops BEFORE the next gate run — a gate already
234
+ // mutating is never cut in half, because a half-applied gate is
235
+ // worse than a late one;
236
+ // 3. cleanup then drains the tracked passes up to DRAIN_LIMIT_MS, so
237
+ // a caller that removes the store right after cleanup sees nothing
238
+ // straggling. A generate that outlives the bound is covered by (2),
239
+ // not by the drain: teardown never waits on the model.
240
+ const DRAIN_LIMIT_MS = 1000;
241
+ const inFlight = new Set<Promise<unknown>>();
242
+ function track<T>(pass: Promise<T>): Promise<T> {
243
+ const wrapped = pass.finally(() => inFlight.delete(wrapped));
244
+ inFlight.add(wrapped);
245
+ return wrapped;
246
+ }
247
+ async function drainInFlight(): Promise<void> {
248
+ if (!inFlight.size) return;
249
+ let timer: ReturnType<typeof setTimeout> | undefined;
250
+ const bound = new Promise<void>((resolve) => {
251
+ timer = setTimeout(resolve, DRAIN_LIMIT_MS);
252
+ });
253
+ await Promise.race([Promise.allSettled([...inFlight]), bound]).finally(
254
+ () => clearTimeout(timer),
255
+ );
256
+ }
185
257
  const eventApi = ctx.event;
186
258
  const generateApi = ctx.generate;
187
259
  // Arrow wrapper: keep the receiver bound. The harness fakes are closures,
@@ -290,11 +362,80 @@ export function configureAutoCapture(
290
362
  );
291
363
  return;
292
364
  }
365
+ // #334: the signal gate. The PORT moved it AFTER the context read
366
+ // (the POC ran it before): a user-stated spec with no tool activity
367
+ // is exactly the hint channel (#339) and must not be skipped, and
368
+ // detecting it needs the messages. The read is a local host call;
369
+ // the expensive artifact the gate saves — the capture model call —
370
+ // is still saved.
371
+ const cursor = captureCursor(sid);
372
+ // The turn this pass DESCRIBES. Completion must advance to this number,
373
+ // not to whatever the session has reached by then: a turn delivered
374
+ // while the model call is in flight was never in the prompt, and
375
+ // consuming it leaves that work unmined with nothing left to ask for it
376
+ // (#366 review).
377
+ const turnAtStart = session(sid).turns;
293
378
  let transcript = seeded;
294
379
  let msgs = seededMsgs;
380
+ // The array AS READ, before any delta slice: the cursor's fingerprint
381
+ // covers the consumed prefix of that array, not of the window.
382
+ let readMsgs = seededMsgs;
383
+ // A seeded compaction payload is the pre-compaction window the hook
384
+ // deliberately handed over (the Compaction Cliff: one round retains 53%
385
+ // of exact-wording rules), so it is mined whole and the cursor is not
386
+ // consulted — which also means the cursor advances TO its length, never
387
+ // past it by the old count.
388
+ const minedWhole = seededMsgs !== undefined;
389
+ // True when the context is no longer the array the cursor counted
390
+ // (#366 review): the offset names a transcript that does not exist, so
391
+ // the window below is the whole context, mined from the beginning.
392
+ let deltaRestart = false;
295
393
  if (transcript.length < 200) {
296
394
  msgs = await contextFn({ sessionID: sid });
395
+ // #211: disposed while the host was answering. The drain in cleanup()
396
+ // waits a bound, not forever, so this is the normal outcome of a
397
+ // teardown during a slow context read — and everything below writes:
398
+ // the thin-transcript receipt below, then the model call. Silent, for
399
+ // the same reason the post-model check is.
400
+ if (controller.signal.aborted) return;
401
+ readMsgs = msgs;
297
402
  transcript = flattenTranscript(msgs);
403
+ // Told in BOTH modes. With the delta off the pass mines the whole
404
+ // context anyway, and the guidance window further down has to follow
405
+ // the same array the pass reads.
406
+ deltaRestart = transcriptReplaced(msgs, cursor);
407
+ if (captureDelta && !deltaRestart) {
408
+ const before = msgs;
409
+ msgs = deltaMessages(msgs, cursor.msgs);
410
+ if (msgs !== before) transcript = flattenTranscript(msgs);
411
+ }
412
+ }
413
+ if (captureOnSignal) {
414
+ let verdict = captureSignalSince(session(sid), cursor.turn);
415
+ if (
416
+ !verdict.ok &&
417
+ guidedStatementInWindow(
418
+ msgs,
419
+ captureDelta || deltaRestart ? 0 : cursor.msgs,
420
+ )
421
+ )
422
+ verdict = { ok: true, why: "guidedStatement" };
423
+ if (!verdict.ok) {
424
+ await record(
425
+ "auto_capture_skipped",
426
+ {
427
+ session: sid,
428
+ trigger,
429
+ reason: verdict.why,
430
+ since_turn: cursor.turn,
431
+ ...(modelTag ? { model: modelTag } : {}),
432
+ },
433
+ true,
434
+ sid,
435
+ captureGate.evidenceContext,
436
+ );
437
+ return; // nothing durable this window; the cursor does NOT advance
438
+ }
298
439
  }
299
440
  if (transcript.length < 200) {
300
441
  // This return used to be silent, and that silence is why a dead
@@ -331,6 +472,15 @@ export function configureAutoCapture(
331
472
  const partitioned = split.work.length >= 200;
332
473
  const work = partitioned ? split.work : transcript;
333
474
  const userProse = partitioned ? split.user : "";
475
+ // The user's turns, decoded from the message array rather than read back
476
+ // out of rendered text (#364 review). Everything that vouches for "these
477
+ // are the user's own words" goes through this.
478
+ const userTurns = userTurnText(msgs);
479
+ // Hoisted out of the prompt literal so the disposal check below runs
480
+ // BEFORE the model call: this read is awaited, so it is its own window
481
+ // into a teardown (#211).
482
+ const knownRows = await knownRowsFor(captureReader);
483
+ if (controller.signal.aborted) return;
334
484
  const out = await generateApi.text({
335
485
  model,
336
486
  // Redact the COMPLETE transcript, THEN apply the character budget
@@ -342,12 +492,105 @@ export function configureAutoCapture(
342
492
  redactSecrets(work).slice(-7000),
343
493
  captureMax,
344
494
  redactSecrets(userProse).slice(-1500),
345
- await knownRowsFor(captureReader),
495
+ knownRows,
346
496
  ),
347
497
  });
348
498
  const text = typeof out === "string" ? out : (out?.text ?? "");
349
- const candidates = parseCandidates(text, captureMax);
499
+ // #211: disposed while the model call was in flight. Stop here — the
500
+ // gate, the rows and the receipts below all write to a store the
501
+ // caller may already have removed. Silent on purpose: a receipt here
502
+ // is the ENOENT teardown noise this check exists to eliminate, and
503
+ // the drain in cleanup means the pass is finished, not lost mid-air.
504
+ if (controller.signal.aborted) return;
505
+ let candidates = parseCandidates(text, captureMax);
506
+ // Deterministic guided pre-pass (POC, FINDINGS 2026-11-08 §4, option
507
+ // `captureGuidedRules`): the user's own lines decide what is guided —
508
+ // the model phrases it but cannot veto it, and a quote the user never
509
+ // wrote is refused at the write boundary (retriable, not silent).
510
+ // The scanned text is the structured USER turns and nothing else
511
+ // (#364 review): assistant output never enters the haystack, so a stored
512
+ // quote can only be what the user said. Filtering rendered lines by a
513
+ // `user:` prefix did not do this — it accepted a `user:` label quoted
514
+ // INSIDE an assistant message as provenance.
515
+ if (guidedRules) {
516
+ const ruleUserText = redactSecrets(userTurns);
517
+ if (!ruleUserText.trim()) {
518
+ // No user turn in what was mined (a seeded transcript with no message
519
+ // array, or a session that has only said nothing). Fail closed: with
520
+ // no roles there is nothing to vouch for, so the lane stays shut
521
+ // rather than minting a row from prose of unknown origin.
522
+ //
523
+ // #364 review round 2: the receipt alone does not shut it. A guided
524
+ // candidate the MODEL supplied would still have been stored with its
525
+ // unverified quote, so with no user turn nothing is attributable and
526
+ // the guided flag plus the quote come off. The distilled prose stays:
527
+ // an ordinary capture row is what the same model output produces with
528
+ // the option off, and dropping the row would trade a provenance fix
529
+ // for a recall loss the plugin has no licence to make here.
530
+ let withheld = 0;
531
+ for (const c of candidates) {
532
+ if (c.guided !== true) continue;
533
+ c.guided = false;
534
+ c.original = undefined;
535
+ withheld++;
536
+ }
537
+ await record(
538
+ "auto_capture_rules",
539
+ {
540
+ session: sid,
541
+ trigger,
542
+ quotes: 0,
543
+ refused: 0,
544
+ withheld,
545
+ skipped: "no_user_turn",
546
+ model: modelTag,
547
+ },
548
+ false,
549
+ sid,
550
+ captureGate.evidenceContext,
551
+ );
552
+ } else {
553
+ const quotes = findGuidedQuotes(ruleUserText);
554
+ const checked = validateGuidedQuotes(candidates, ruleUserText);
555
+ candidates = mergeGuidedCandidates(quotes, checked.kept);
556
+ await record(
557
+ "auto_capture_rules",
558
+ {
559
+ session: sid,
560
+ trigger,
561
+ quotes: quotes.length,
562
+ refused: checked.refused.length,
563
+ model: modelTag,
564
+ },
565
+ false,
566
+ sid,
567
+ captureGate.evidenceContext,
568
+ );
569
+ }
570
+ } else {
571
+ // Lenient check (default): a guided "original" must appear in the
572
+ // user's own turns. The prompt asks for a quote "copied VERBATIM from
573
+ // a user: line or the REQUESTS block", so the haystack is exactly that
574
+ // (#364 review: the mined WORK text used to be in here too, which
575
+ // vouched for a quote lifted out of assistant output). Whitespace is
576
+ // normalised — the model may collapse runs of spaces. A failed check
577
+ // drops the field, never the row: the distilled prose still
578
+ // deserved storage, it just cannot be vouched for as the user's
579
+ // own words.
580
+ const quoteHay = redactSecrets(userTurns).replace(/\s+/g, " ");
581
+ for (const c of candidates) {
582
+ if (
583
+ c.original !== undefined &&
584
+ !quoteHay.includes(normWs(c.original))
585
+ )
586
+ c.original = undefined;
587
+ }
588
+ }
350
589
  for (const c of candidates) {
590
+ // Between candidates, never inside a gate run: a supersession that
591
+ // half-applied is a store the next session cannot trust.
592
+ if (controller.signal.aborted) return;
593
+ const original = c.original;
351
594
  const durable: string[] = [];
352
595
  let outcome: Awaited<ReturnType<typeof runWriteGate>>;
353
596
  try {
@@ -361,6 +604,10 @@ export function configureAutoCapture(
361
604
  ...(c.ref ? { ref: c.ref } : {}),
362
605
  ...(c.claim ? { claim: c.claim } : {}),
363
606
  ...(c.klass ? { klass: c.klass } : {}),
607
+ // Verified verbatim utterance (see quoteHay above): injection
608
+ // renders it so the user's exact words ride the next session's
609
+ // request bytes.
610
+ ...(original ? { original } : {}),
364
611
  tags: [
365
612
  AUTO_CAPTURE_TAG,
366
613
  ...(trigger === "compaction" ? [CAPTURE_COMPACT_TAG] : []),
@@ -415,11 +662,32 @@ export function configureAutoCapture(
415
662
  : "absent",
416
663
  }
417
664
  : {}),
665
+ // Stage telemetry (mystery 2): the row's identity and guided
666
+ // standing at the moment of storage, so a later L6h miss can be
667
+ // joined to the exact row that did or did not enter the hint
668
+ // channel, and to whether its verbatim quote survived the
669
+ // substring check.
670
+ ...(outcome.action === "promoted" ? { row: outcome.ts } : {}),
671
+ ...(c.guided ? { guided: true } : {}),
672
+ ...(original ? { orig: true } : {}),
418
673
  },
419
674
  false,
420
675
  sid,
421
676
  captureGate.evidenceContext,
422
677
  );
678
+ // Fix A (FINDINGS 2026-11-08 §4b): a guided row promoted after a
679
+ // session froze its bytes could never enter the hint lane (bench
680
+ // run 5: capture landed 9 min into pass 2, epoch never moved).
681
+ // Recompute every tracked epoch now, so the next request of each
682
+ // session carries the row. Fail-soft: the row is stored either way,
683
+ // and a later request re-reads the store on its own.
684
+ if (c.guided && outcome.action === "promoted" && onGuidedPromoted) {
685
+ try {
686
+ await onGuidedPromoted(sid);
687
+ } catch {
688
+ /* fail-soft — see above */
689
+ }
690
+ }
423
691
  }
424
692
  await recordCaptureLag(
425
693
  sid,
@@ -428,6 +696,27 @@ export function configureAutoCapture(
428
696
  captureGate.evidenceContext,
429
697
  modelTag,
430
698
  );
699
+ // #334: the window is consumed. Advance when a capture RAN, whatever it
700
+ // found — zero candidates is an answer, and re-mining an answered
701
+ // window every turn is precisely the cost this cursor exists to remove.
702
+ // A skip returns early and leaves the cursor where it was, so the next
703
+ // signal-bearing turn still mines everything since the last real pass.
704
+ if (captureDelta || captureOnSignal) {
705
+ // A window is consumed by the pass that mined it. A seeded payload or
706
+ // a replaced transcript IS the whole window, so the cursor becomes its
707
+ // length; an ordinary delta window sits AFTER what was mined before.
708
+ const total = !Array.isArray(msgs)
709
+ ? cursor.msgs
710
+ : minedWhole || deltaRestart || !captureDelta
711
+ ? msgs.length
712
+ : cursor.msgs + msgs.length;
713
+ advanceCaptureCursor(
714
+ sid,
715
+ total,
716
+ turnAtStart,
717
+ prefixFingerprint(readMsgs, total),
718
+ );
719
+ }
431
720
  }
432
721
 
433
722
  void (async () => {
@@ -449,8 +738,12 @@ export function configureAutoCapture(
449
738
  let opGate: GateContext | undefined;
450
739
  try {
451
740
  opGate = bindCapture(sid);
452
- await captureSession(sid, "", "idle", undefined, opGate);
741
+ await track(captureSession(sid, "", "idle", undefined, opGate));
453
742
  } catch (err) {
743
+ // Teardown is not a capture failure: after cleanup the store may
744
+ // be gone, and a receipt here would be the ENOENT noise #211
745
+ // reports. The abort check inside captureSession is the signal.
746
+ if (controller.signal.aborted) return;
454
747
  // Fail-closed for the SESSION, never silent in the store: the
455
748
  // same silence that hid the 2.2.5 shape break would make a
456
749
  // throwing capture indistinguishable from one that never ran.
@@ -474,7 +767,10 @@ export function configureAutoCapture(
474
767
  // the subscription itself ended (abort or host error); nothing to do
475
768
  }
476
769
  })();
477
- captureCleanup = () => controller.abort();
770
+ captureCleanup = async () => {
771
+ controller.abort();
772
+ await drainInFlight();
773
+ };
478
774
 
479
775
  // The compaction trigger needs no extra subscription: the session
480
776
  // compaction hook (registered above) calls through this seam. The
@@ -490,13 +786,24 @@ export function configureAutoCapture(
490
786
  // Same freeze as the idle trigger, and for the same reason: sync,
491
787
  // before guarded() starts awaiting.
492
788
  const opGate = bindCapture(sid);
493
- void guarded("session.compaction (auto-capture)", () =>
494
- captureSession(
495
- sid,
496
- flattenTranscript(messages),
497
- "compaction",
498
- messages,
499
- opGate,
789
+ // Tracked, not just fired: cleanup must be able to drain this pass
790
+ // (#211), which is the only reason the seam keeps the promise.
791
+ void track(
792
+ // The predicate, not just the checks inside the pass: a rejection
793
+ // from the awaited model call skips every abort check that follows
794
+ // it and lands in the generic reporter, which would append
795
+ // `hook_error` to a store cleanup() has already released (#211).
796
+ guarded(
797
+ "session.compaction (auto-capture)",
798
+ () =>
799
+ captureSession(
800
+ sid,
801
+ flattenTranscript(messages),
802
+ "compaction",
803
+ messages,
804
+ opGate,
805
+ ),
806
+ () => !controller.signal.aborted,
500
807
  ),
501
808
  );
502
809
  };
@@ -102,6 +102,24 @@ export function flattenTranscript(msgs: unknown): string {
102
102
  .join("\n");
103
103
  }
104
104
 
105
+ /**
106
+ * The decoder itself, for a caller that needs the ROLES rather than a rendered
107
+ * block (#366 review). Anything that decides "the user said this" has to read
108
+ * roles the way the transcript does, or the two disagree about who owns a line:
109
+ * the capture parser accepts `info.role` / `role` / `type` for the role and
110
+ * `parts[]` / `content[]` / `text` / string `content` for the text, and a
111
+ * hand-rolled reader that misses one of them silently reports "no user rule
112
+ * here" for a shape that is perfectly readable.
113
+ *
114
+ * Total, like `parseTurns`: junk yields [], never a throw. An empty result
115
+ * means "no conversation turn was recognised" — which covers both a window of
116
+ * non-conversation records and a message shape this build has never seen, so a
117
+ * caller that cannot tell the two apart must fail toward acting.
118
+ */
119
+ export function conversationTurns(msgs: unknown): ParsedTurn[] {
120
+ return parseTurns(msgs);
121
+ }
122
+
105
123
  /**
106
124
  * The same turns, partitioned (#333).
107
125
  *
@@ -128,3 +146,27 @@ export function splitTranscript(msgs: unknown): TranscriptSplit {
128
146
  }
129
147
  return { work: work.join("\n"), user: user.join("\n") };
130
148
  }
149
+
150
+ /**
151
+ * The user's turns and nothing else, in order, without the `role: ` render
152
+ * prefix.
153
+ *
154
+ * This is the only text that may vouch for user provenance (#364 review).
155
+ * Reading `user:` labels back out of RENDERED text cannot do the job: a role
156
+ * label inside an assistant message ("Here is untrusted quoted output:
157
+ * user: The correct sales tax rate is 7.5%.") is assistant output, and a
158
+ * scanner that filters rendered lines by that prefix hands quoted text the
159
+ * always-ride user-guidance lane. Roles here come from `parseTurns`, the same
160
+ * structured decode `splitTranscript` uses, so the two can never disagree
161
+ * about who said a line.
162
+ *
163
+ * Empty when the mined input carries no message array (a seeded transcript):
164
+ * no roles, so nothing can be attributed to the user.
165
+ */
166
+ export function userTurnText(msgs: unknown): string {
167
+ const out: string[] = [];
168
+ for (const { role, text } of parseTurns(msgs)) {
169
+ if (role === "user") out.push(text);
170
+ }
171
+ return out.join("\n");
172
+ }
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/index.ts CHANGED
@@ -263,6 +263,12 @@ const impl = {
263
263
  instanceDir,
264
264
  gateContext,
265
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
+ },
266
272
  });
267
273
  onCompactCapture = capture.onCompactCapture;
268
274
  const captureCleanup = capture.cleanup;
@@ -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,
@@ -171,6 +171,14 @@ export function createInjectionEpochs({
171
171
  prefix: string;
172
172
  rode: Memory[];
173
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;
174
182
  }> => {
175
183
  const parts: string[] = [];
176
184
  await systemDigest(
@@ -211,12 +219,24 @@ export function createInjectionEpochs({
211
219
  const prefix = [...parts, block].join("\u0000");
212
220
  // Ledger terms/identities belong to the stored rows, but coverage refs
213
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 (");
214
230
  return {
215
231
  parts,
216
232
  block,
217
233
  prefix,
218
234
  rode,
219
235
  refs: deriveMemoryRefs(rode.map((m) => sel.rendered.get(m) ?? m)),
236
+ guidedIds,
237
+ guidedRodeIds,
238
+ guidedSeen,
239
+ conflict,
220
240
  };
221
241
  };
222
242
  const refreshEpoch = async (sid: string, rows?: Memory[]): Promise<void> => {
@@ -305,6 +325,20 @@ export function createInjectionEpochs({
305
325
  session: sid,
306
326
  reason,
307
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 } : {}),
308
342
  },
309
343
  false,
310
344
  sid,
@@ -374,6 +408,18 @@ export function createInjectionEpochs({
374
408
  latestPrompt.set(sid, text);
375
409
  await refreshEpoch(sid);
376
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
+ },
377
423
  deliver,
378
424
  invalidate(sid: string): void {
379
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
  }