opencode-self-improvement 0.33.8 → 0.33.10

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
@@ -152,7 +152,7 @@ A write that cites code references builds one tree index — a single recursive
152
152
 
153
153
  The plugin keeps a use ledger — a due-date card for every row: who looked at it, when, and how it reached them. It is append-only, never ingested as a memory, and reported in `memory_status` and the `/memory` panel.
154
154
 
155
- - **Use has three distinct sources** — the row rode the injected block, `memory_recall` returned it, or a grep/read pull appended it — because "the model asked" and "the harness offered" are different facts. No prompt content is stored: the ledger keeps a scan-truncated string from the *memory* side, never your message.
155
+ - **Use has three sources.** Injection offers a row to the model. `memory_recall` returns a requested row. A tool pull earns credit when the plugin sees the row’s complete line in the matching tool result during `session.context`. The ledger records matching terms from memory and omits prompt text.
156
156
  - **Reinforcement is a tie-break only** (`useBoost ≤ 1.0`): a recently used row wins a tie and can never outrank a real score gap.
157
157
  - **`never retrieved` is stated, not acted on.** Pruning is your decision.
158
158
  - **Aggregate STORE counts are machine-wide by decision (#213 B)** — they describe the store on this machine, not your slice of it. Privacy applies to the content surfaces instead: `memory_evidence` and the recent-blocked-writes list follow each reader's repository visibility (#306).
@@ -34,10 +34,51 @@ harness offered" are different facts:
34
34
  be credited here for something the model had not asked about yet
35
35
  (`pullOutputChars` in [docs/reference/options.md](../reference/options.md) dials it back).
36
36
 
37
- Credit is recorded only when the bytes were actually placed on the result. When a
38
- pull computed rows and found nowhere to write them, the evidence log gets a
39
- `pull_undelivered` line instead — a host that changes its result shape should show
40
- up as a failure, not as a quieter ledger.
37
+ A pull is credited when the next request carries it, not when it is placed.
38
+ Another plugin's `tool.execute.after` hook can run after this one and shorten the
39
+ result, so placing the block proves nothing about what the model receives
40
+ ([#462](https://github.com/abogartz/opencode-self-improvement/issues/462)). The
41
+ plugin holds the placed rows until the next `session.context` request for the same
42
+ session. It matches the tool name, call ID and a fresh 16-character identifier
43
+ in the header. The rendering budget includes this identifier. A row earns credit
44
+ when its complete line survives after that placement’s header. If
45
+ several rows render to the same line and fewer copies survive, none of those row
46
+ IDs is credited, because the request cannot say which one rode. Each placement is
47
+ credited at most once. If a matching call ID occurs without the placement header,
48
+ the placement stays pending. A later request can confirm it. Expiry, eviction or
49
+ replacement records a single final loss for a placement that stayed unconfirmed.
50
+ When a formatter repeats a placement header within a result or the host repeats the result, each copy must independently contain enough matching lines to identify a row. If the process exits while a placement is pending, there is no final loss entry.
51
+ The ledger timestamp is the time of observation in the context hook.
52
+ A gate earlier in the tool batch therefore cannot count as following retrieval. The
53
+ hourly throttle and turn identity still come from placement. The `terms` come from
54
+ the query the pull searched.
55
+
56
+ The evidence log records placement and confirmation failures by tool and row count.
57
+ Ledger throttling, write failures, or process shutdown can also leave a row without
58
+ a receipt. Pull receipts share a 50 ms lock-wait budget per request, including
59
+ conversion of a legacy lock database on first use. A skipped
60
+ attempt after this budget expires emits `pull_credit_skipped reason=budget`.
61
+ A failed ledger write emits `pull_credit_skipped reason=write_failed` with the
62
+ placement’s scope and row count. A throttled duplicate produces neither event.
63
+ Lock acquisition uses a monotonic clock, including cold journal conversion.
64
+ On Windows, pull receipts attempt rotation once. A reader that prevents
65
+ replacement leaves the existing ledger intact. Filesystem I/O can still add latency.
66
+
67
+ - `pull_undelivered` (no `stage`): the pull computed rows and found nowhere to
68
+ write them. A host that changes its result shape should show up as a failure,
69
+ not as a quieter ledger.
70
+ - `pull_undelivered stage=request`: the request carried the placement header, but these rows
71
+ were missing or cut.
72
+ - `pull_unconfirmed reason=expired|evicted|no_call|replaced`: no request settled the
73
+ placement. Expiry is checked on later context activity, after 30 minutes. The
74
+ 256-placement cap also applies when there is no further context activity.
75
+ Reusing a pending call ID in the same session retires the earlier placement.
76
+
77
+ The receipt checks the messages as this plugin's `session.context` hook sees them.
78
+ A context hook that another plugin runs later can still change the request, and
79
+ provider-side truncation is not visible. The credit is one step closer to the
80
+ provider than placement, but it is not the provider's own bytes. A pull that is
81
+ never followed by a request is not credited, so pull counts are a floor.
41
82
 
42
83
  The writer throttles identical sets of retrieved rows to one successful line
43
84
  per session and source per hour. A row can appear in multiple sets.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.33.8",
3
+ "version": "0.33.10",
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": {
@@ -0,0 +1,168 @@
1
+ // attest — decides whether a guided candidate has earned the hint channel.
2
+ //
3
+ // `user-guided` is not a description, it is a grant: the newest guided rows ride
4
+ // EVERY later session's injection prefix whether or not that session's prompt
5
+ // mentions them, ahead of the lexically-relevant picks, and exempt from the
6
+ // budget demotion applied to rows the working tree already states. Every later
7
+ // session pays for the slot in prompt bytes and in a prompt-cache miss.
8
+ //
9
+ // What grants it today — the capture model emitted `guided: true` and the row's
10
+ // verbatim quote occurs in one of the user's turns — admits every sentence a
11
+ // session contains, because a task brief IS a user turn. Boilerplate written for
12
+ // a harness ("trust the code's invariants over the docs") passes it unchanged:
13
+ // the user did type those words, and no later session can check them against
14
+ // anything. Provenance that nothing can contradict is exactly the shape a wrong
15
+ // row needs in order to always ride.
16
+ //
17
+ // So the tag is earned by CHECKABILITY, not by attribution. A guided row keeps
18
+ // it when it carries a handle a later session can verify outside the prose:
19
+ //
20
+ // - a value. A number, in the user's own words or in the declared claim. The
21
+ // contradiction surface already code-checks these against the tree, and a
22
+ // rate, a limit or a requirement is the kind of thing only the user can
23
+ // supply.
24
+ // - a name the session used. One of the candidate's declared retrieval
25
+ // keywords appears in the tool ledger, so the convention was exercised, not
26
+ // merely asserted. "we use bun here" is confirmable by a `bun` command;
27
+ // "trust the code over the docs" is confirmable by nothing, which is the
28
+ // reason it should not hold a slot every later session pays for.
29
+ //
30
+ // Undecidable means kept, in both directions:
31
+ // - a candidate that declared no keywords cannot be disproved, and keywords
32
+ // are optional in the capture contract, so demanding them would demote every
33
+ // row whose wording the model judged self-explanatory;
34
+ // - a keyword that happens to appear in an unrelated tool call keeps a tag it
35
+ // did not earn, which is today's behaviour, not a new defect.
36
+ // The asymmetry is deliberate. A wrong demotion costs one row its always-ride
37
+ // lane; the row is still stored, still recalled by relevance, and the next pass
38
+ // can grant the tag again. A wrong grant costs every later session and puts an
39
+ // unchecked sentence in the lane this store has measured being obeyed over the
40
+ // code.
41
+ import type { CaptureCandidate } from "./prompt.ts";
42
+
43
+ /** One ledger entry, as the session state records it. */
44
+ export interface LedgerEntry {
45
+ tool: string;
46
+ cmd?: string;
47
+ arg?: string;
48
+ }
49
+
50
+ /**
51
+ * The ledger as one lower-cased haystack: the tool that ran, the command, and
52
+ * the argument that identified its target. Output text is deliberately absent —
53
+ * a tool that READ a file containing the sentence would otherwise vouch for the
54
+ * sentence, and reading is not exercising a convention.
55
+ *
56
+ * Total: junk entries are skipped, never a throw.
57
+ */
58
+ export function ledgerText(calls: readonly LedgerEntry[]): string {
59
+ if (!Array.isArray(calls)) return "";
60
+ const parts: string[] = [];
61
+ for (const c of calls) {
62
+ if (!c || typeof c !== "object") continue;
63
+ for (const v of [c.tool, c.cmd, c.arg]) {
64
+ if (typeof v === "string" && v.trim()) parts.push(v.trim().toLowerCase());
65
+ }
66
+ }
67
+ return parts.join(" ");
68
+ }
69
+
70
+ /** A stated number: the user supplied a value, which is checkable by definition. */
71
+ export function statesValue(text: string): boolean {
72
+ return /\d/.test(text);
73
+ }
74
+
75
+ // Word-boundary test on a haystack with no `\b`: `_` is a word character here
76
+ // but a path separator in `src/pricing_test.ts`, and `pricing_test` must not
77
+ // attest a keyword `test`. A hit is a whole path segment or whole word.
78
+ function wholeTerm(hay: string, term: string): boolean {
79
+ if (!term) return false;
80
+ let from = hay.indexOf(term);
81
+ while (from >= 0) {
82
+ const before = from === 0 ? " " : hay[from - 1];
83
+ const after = from + term.length;
84
+ const next = after >= hay.length ? " " : hay[after];
85
+ if (!/[\w-]/.test(before) && !/[\w-]/.test(next)) return true;
86
+ from = hay.indexOf(term, from + 1);
87
+ }
88
+ return false;
89
+ }
90
+
91
+ /**
92
+ * The declared keyword that the ledger corroborates, or null. Keywords shorter
93
+ * than three characters are skipped: they match too much of a command line to
94
+ * establish that the session used the thing they name.
95
+ */
96
+ export function corroboratedKeyword(
97
+ keywords: readonly string[] | undefined,
98
+ ledger: string,
99
+ ): string | null {
100
+ if (!keywords || !keywords.length || !ledger) return null;
101
+ for (const raw of keywords) {
102
+ if (typeof raw !== "string") continue;
103
+ const term = raw.trim().toLowerCase();
104
+ if (term.length < 3) continue;
105
+ if (wholeTerm(ledger, term)) return term;
106
+ }
107
+ return null;
108
+ }
109
+
110
+ export type AttestVerdict =
111
+ | { attested: true; via: "value" | "ledger" | "undecidable" }
112
+ | { attested: false };
113
+
114
+ /**
115
+ * Whether a guided candidate keeps the hint-channel tag. Non-guided candidates
116
+ * are outside this decision and come back `undecidable`, so a caller can run
117
+ * the whole candidate list through it and act only on `attested: false`.
118
+ */
119
+ export function guidedAttestation(
120
+ candidate: CaptureCandidate,
121
+ ledger: string,
122
+ ): AttestVerdict {
123
+ if (candidate.guided !== true) return { attested: true, via: "undecidable" };
124
+ // A value is a NUMBER. `claim` is contractually the user's value, but it
125
+ // arrives from the model, so it earns the grant only by stating a figure the
126
+ // contradiction surface can actually compare — prose in that field is the same
127
+ // unchecked sentence as prose anywhere else.
128
+ const words = `${candidate.claim ?? ""} ${candidate.original ?? ""} ${candidate.content}`;
129
+ if (statesValue(words)) return { attested: true, via: "value" };
130
+ if (!candidate.kw || !candidate.kw.length)
131
+ return { attested: true, via: "undecidable" };
132
+ // No ledger means no window into what the session did, not a session that did
133
+ // nothing: the tail is capped and a caller may hold no state for this id. With
134
+ // nothing to compare against there is no evidence either way, so the grant
135
+ // stands rather than resting on an absence.
136
+ if (!ledger) return { attested: true, via: "undecidable" };
137
+ if (corroboratedKeyword(candidate.kw, ledger))
138
+ return { attested: true, via: "ledger" };
139
+ return { attested: false };
140
+ }
141
+
142
+ /**
143
+ * Clears the guided standing of every candidate the ledger cannot corroborate.
144
+ * The verbatim quote goes with it: injection renders it as "user said", which is
145
+ * the attribution this decision just refused. The comparison fields ride guided
146
+ * rows only, so they are cleared for the same reason. The prose stays — this
147
+ * removes a privilege, never a fact.
148
+ *
149
+ * Returns the number of rows demoted so the caller can record it; a demotion
150
+ * that leaves no trace is the failure mode the evidence line exists for.
151
+ */
152
+ export function withholdUngroundedGuidance(
153
+ candidates: CaptureCandidate[],
154
+ ledger: string,
155
+ ): number {
156
+ let withheld = 0;
157
+ for (const c of candidates) {
158
+ if (c.guided !== true) continue;
159
+ if (guidedAttestation(c, ledger).attested) continue;
160
+ c.guided = false;
161
+ c.original = undefined;
162
+ c.ref = undefined;
163
+ c.claim = undefined;
164
+ c.klass = undefined;
165
+ withheld++;
166
+ }
167
+ return withheld;
168
+ }
@@ -24,8 +24,14 @@ import {
24
24
  import { quarantineCandidate } from "../store/quarantine/quarantine.ts";
25
25
  import { flattenMemoryText } from "../store/sanitize.ts";
26
26
  import { redactSecrets } from "../store/secrets.ts";
27
- import { record, recordCaptureLag, recordSync } from "../telemetry/record.ts";
27
+ import {
28
+ recordBestEffort,
29
+ recordCaptureLagBestEffort,
30
+ recordSyncBestEffort,
31
+ safeErrorMessage,
32
+ } from "../telemetry/record.ts";
28
33
  import { type AvailabilityIndex, availabilityIndex } from "./available.ts";
34
+ import { ledgerText, withholdUngroundedGuidance } from "./attest.ts";
29
35
  import { parseCandidates, parseModelRef } from "./candidates.ts";
30
36
  import { claimVerdictFromContent } from "./checked.ts";
31
37
  import {
@@ -434,7 +440,7 @@ export function configureAutoCapture(
434
440
  // store refuses. Skip BEFORE the model call — no tokens spent on a
435
441
  // capture that cannot be stored — and leave the reason in evidence.
436
442
  if (!writeTarget(sid).ok) {
437
- await record(
443
+ await recordBestEffort(
438
444
  "auto_capture_refused",
439
445
  { session: sid, trigger, ...(modelTag ? { model: modelTag } : {}) },
440
446
  true,
@@ -451,7 +457,7 @@ export function configureAutoCapture(
451
457
  "[opencode-self-improvement] autoCapture is on but captureModel is omitted and neither session.context nor the host default names a model; capture skipped (warned once).",
452
458
  );
453
459
  }
454
- await record(
460
+ await recordBestEffort(
455
461
  "auto_capture_refused",
456
462
  { session: sid, trigger, reason: "no_model" },
457
463
  true,
@@ -518,7 +524,7 @@ export function configureAutoCapture(
518
524
  )
519
525
  verdict = { ok: true, why: "guidedStatement" };
520
526
  if (!verdict.ok) {
521
- await record(
527
+ await recordBestEffort(
522
528
  "auto_capture_skipped",
523
529
  {
524
530
  session: sid,
@@ -540,7 +546,7 @@ export function configureAutoCapture(
540
546
  // thin to mine" and "the host never emitted the event" produced
541
547
  // byte-identical stores. Record the skip with its size so the two
542
548
  // are distinguishable from the evidence file alone.
543
- await record(
549
+ await recordBestEffort(
544
550
  "auto_capture_skipped",
545
551
  {
546
552
  session: sid,
@@ -639,27 +645,21 @@ export function configureAutoCapture(
639
645
  // and found nothing." The cost of that placement: a pass cut DURING the
640
646
  // context read or the known-rows read, before this line, still leaves no
641
647
  // trace, so that band is silent by design (see the evidence doc). The
642
- // write is guarded like the disposal flush: an unwritable evidence log
643
- // (read-only mount, foreign owner, ENOSPC) must never abort the pass
644
- // before its model call — observability cannot be allowed to cause the
645
- // loss it exists to detect.
648
+ // write is best-effort: an unwritable evidence log (read-only mount,
649
+ // foreign owner, ENOSPC) must never abort the pass before its model
650
+ // call — observability cannot be allowed to cause the loss it exists to
651
+ // detect.
646
652
  passesStarted++;
647
- try {
648
- recordSync(
649
- "auto_capture_start",
650
- {
651
- trigger,
652
- ...(modelTag ? { model: modelTag } : {}),
653
- },
654
- true,
655
- sid,
656
- captureGate.evidenceContext,
657
- );
658
- } catch {
659
- // The receipt is best-effort. A failed write here must not stop the
660
- // model call or tear down the subscription; the pass simply runs
661
- // without leaving its start line.
662
- }
653
+ recordSyncBestEffort(
654
+ "auto_capture_start",
655
+ {
656
+ trigger,
657
+ ...(modelTag ? { model: modelTag } : {}),
658
+ },
659
+ true,
660
+ sid,
661
+ captureGate.evidenceContext,
662
+ );
663
663
  const out = await generateApi.text({
664
664
  model,
665
665
  prompt: capturePrompt,
@@ -686,7 +686,7 @@ export function configureAutoCapture(
686
686
  // store left to write to. Its tokens therefore go unbilled here, which
687
687
  // undercounts by one call at teardown rather than throwing ENOENT out
688
688
  // of a receipt path that must never break a session.
689
- await record(
689
+ await recordBestEffort(
690
690
  "capture_cost",
691
691
  {
692
692
  session: sid,
@@ -733,7 +733,7 @@ export function configureAutoCapture(
733
733
  c.original = undefined;
734
734
  withheld++;
735
735
  }
736
- await record(
736
+ await recordBestEffort(
737
737
  "auto_capture_rules",
738
738
  {
739
739
  session: sid,
@@ -752,7 +752,7 @@ export function configureAutoCapture(
752
752
  const quotes = findGuidedQuotes(ruleUserText);
753
753
  const checked = validateGuidedQuotes(candidates, ruleUserText);
754
754
  candidates = mergeGuidedCandidates(quotes, checked.kept);
755
- await record(
755
+ await recordBestEffort(
756
756
  "auto_capture_rules",
757
757
  {
758
758
  session: sid,
@@ -785,6 +785,32 @@ export function configureAutoCapture(
785
785
  c.original = undefined;
786
786
  }
787
787
  }
788
+ // The hint channel is granted, not inherited. A quote found in a user
789
+ // turn establishes that the user typed the words; it cannot establish
790
+ // that the words are about THIS repository, because the task brief is a
791
+ // user turn and a brief carries instructions written for the harness as
792
+ // well as facts about the code. A row that always rides every later
793
+ // session has to carry something a later session can check — a value, or
794
+ // a name the session actually used — so the ledger decides here, the
795
+ // same way it decides what a failure lesson may be about.
796
+ const echoes = withholdUngroundedGuidance(
797
+ candidates,
798
+ ledgerText(session(sid).calls),
799
+ );
800
+ if (echoes)
801
+ await record(
802
+ "auto_capture_brief_echo",
803
+ {
804
+ session: sid,
805
+ trigger,
806
+ withheld: echoes,
807
+ candidates: candidates.length,
808
+ ...(modelTag ? { model: modelTag } : {}),
809
+ },
810
+ false,
811
+ sid,
812
+ captureGate.evidenceContext,
813
+ );
788
814
  // availability before authority. A candidate that restates a
789
815
  // tracked file, or names a command the project already declares, is
790
816
  // readable by the next session without a row — and capture costs about a
@@ -846,7 +872,7 @@ export function configureAutoCapture(
846
872
  return false;
847
873
  });
848
874
  if (lessonsKept || lessonsRefused)
849
- await record(
875
+ await recordBestEffort(
850
876
  "auto_capture_lessons",
851
877
  {
852
878
  session: sid,
@@ -881,7 +907,7 @@ export function configureAutoCapture(
881
907
  const avail = availability().check(c.content);
882
908
  if (avail) {
883
909
  availVerdicts++;
884
- await record(
910
+ await recordBestEffort(
885
911
  "auto_capture_restatable",
886
912
  {
887
913
  session: sid,
@@ -937,7 +963,7 @@ export function configureAutoCapture(
937
963
  );
938
964
  const verdict = claim.verdict;
939
965
  if (verdict === "contradicts") {
940
- await record(
966
+ await recordBestEffort(
941
967
  "auto_capture_contradiction",
942
968
  {
943
969
  session: sid,
@@ -991,7 +1017,7 @@ export function configureAutoCapture(
991
1017
  } catch (err) {
992
1018
  // A refused write must not disappear into the hook's fail-soft
993
1019
  // wrapper. Preserve any earlier gate retirements in the receipt.
994
- await record(
1020
+ await recordBestEffort(
995
1021
  durable.length ? "auto_capture_partial" : "auto_capture_refused",
996
1022
  {
997
1023
  session: sid,
@@ -1012,7 +1038,7 @@ export function configureAutoCapture(
1012
1038
  // nothing and `collapsed` folds into an existing row whose tags are not
1013
1039
  // these, so only `promoted` can carry `restatable` into the store.
1014
1040
  if (avail && outcome.action === "promoted") restatements++;
1015
- await record(
1041
+ await recordBestEffort(
1016
1042
  trigger === "compaction"
1017
1043
  ? `auto_capture_compaction_${outcome.action}`
1018
1044
  : `auto_capture_${outcome.action}`,
@@ -1071,7 +1097,7 @@ export function configureAutoCapture(
1071
1097
  // milliseconds.
1072
1098
  if (availableIndex) {
1073
1099
  const scan = availableIndex.scanned();
1074
- await record(
1100
+ await recordBestEffort(
1075
1101
  "auto_capture_scan",
1076
1102
  {
1077
1103
  session: sid,
@@ -1094,7 +1120,7 @@ export function configureAutoCapture(
1094
1120
  captureGate.evidenceContext,
1095
1121
  );
1096
1122
  }
1097
- await recordCaptureLag(
1123
+ await recordCaptureLagBestEffort(
1098
1124
  sid,
1099
1125
  lagMs,
1100
1126
  candidates.length ? "candidates" : "empty",
@@ -1129,27 +1155,36 @@ export function configureAutoCapture(
1129
1155
  for await (const raw of eventApi.subscribe({
1130
1156
  signal: controller.signal,
1131
1157
  })) {
1132
- if (!captureTriggerFor(raw)) continue;
1133
- // The turn-end event reached this subscription. Counted before
1134
- // the session-id and cooldown checks so a delivered-but-cooled event
1135
- // still proves the event arrived — only a zero here means no turn-end
1136
- // event reached this instance, the only case the disposal flush records.
1137
- turnEndSeen++;
1138
- const sid = captureSessionID(raw);
1139
- if (sid === undefined) continue;
1140
- setCurrent({ sessionID: sid });
1141
- const now = Date.now();
1142
- if (!captureCooldownPasses("idle", sid, now)) continue; // 5-min cooldown, shared across setups
1158
+ // One event's failure stays that event's failure. The guard covers
1159
+ // the whole body, including the receipt that reports a failure,
1160
+ // because this loop is the only thing that hands capture every later
1161
+ // turn: a throw that reaches it ends auto-capture for the life of
1162
+ // the process, and the log that would say so is the thing that
1163
+ // broke. Only the subscription ending may leave the loop.
1164
+ // Named in the outer scope because the catch reports it: a failure
1165
+ // before the id is read has no session to name.
1166
+ let sid: string | undefined;
1143
1167
  // Freeze the operation's evidence context before its first await.
1144
1168
  // The catch below runs after the model call, where a
1145
1169
  // `session.moved` may already have re-pointed this session at
1146
1170
  // another repository; resolving it there would stamp the failure
1147
1171
  // receipt of repo A's capture as repo B's evidence.
1148
1172
  let opGate: GateContext | undefined;
1149
- // Created before the first await so cleanup can see this pass in the
1150
- // window before the model call, still applies in full.
1151
- const phase = newPhase();
1152
1173
  try {
1174
+ if (!captureTriggerFor(raw)) continue;
1175
+ // The turn-end event reached this subscription. Counted before
1176
+ // the session-id and cooldown checks so a delivered-but-cooled event
1177
+ // still proves the event arrived — only a zero here means no turn-end
1178
+ // event reached this instance, the only case the disposal flush records.
1179
+ turnEndSeen++;
1180
+ sid = captureSessionID(raw);
1181
+ if (sid === undefined) continue;
1182
+ setCurrent({ sessionID: sid });
1183
+ const now = Date.now();
1184
+ if (!captureCooldownPasses("idle", sid, now)) continue; // 5-min cooldown, shared across setups
1185
+ // Created before the first await so cleanup can see this pass in the
1186
+ // window before the model call, still applies in full.
1187
+ const phase = newPhase();
1153
1188
  opGate = bindCapture(sid);
1154
1189
  await track(
1155
1190
  captureSession(sid, "", "idle", undefined, opGate, phase),
@@ -1160,18 +1195,26 @@ export function configureAutoCapture(
1160
1195
  // be gone, and a receipt here would be the ENOENT noise
1161
1196
  // reports. The abort check inside captureSession is the signal.
1162
1197
  if (controller.signal.aborted) return;
1198
+ // The console line is the primary trace and the receipt is the
1199
+ // copy: when the evidence log is the broken channel, the receipt
1200
+ // below cannot land and the underlying failure would vanish with
1201
+ // it — the counter names only the receipt event, not its cause.
1202
+ // ONE rendering feeds both, so the two channels of this one
1203
+ // failure cannot diverge in what they expose.
1204
+ const failure = safeErrorMessage(err);
1205
+ console.warn(
1206
+ `[opencode-self-improvement] auto-capture (idle) hook failed (ignored): ${failure}`,
1207
+ );
1163
1208
  // Fail-closed for the SESSION, never silent in the store: the
1164
1209
  // same silence that hid the 2.2.5 shape break would make a
1165
1210
  // throwing capture indistinguishable from one that never ran.
1166
- await record(
1211
+ await recordBestEffort(
1167
1212
  "auto_capture_refused",
1168
1213
  {
1169
- session: sid,
1214
+ session: sid ?? "?",
1170
1215
  trigger: "idle",
1171
1216
  reason: "capture_threw",
1172
- error: redactSecrets(
1173
- String((err as Error)?.message ?? err),
1174
- ).slice(0, 200),
1217
+ error: failure,
1175
1218
  },
1176
1219
  true,
1177
1220
  sid,
@@ -1197,26 +1240,23 @@ export function configureAutoCapture(
1197
1240
  // turn-end event reaches the subscription in every measured run, and an
1198
1241
  // idle instance restarted between turns produces it too — so it names the
1199
1242
  // state the original report inferred, never an accusation of where a
1200
- // dispatched event went. Guarded and existence-checked: a disposed
1243
+ // dispatched event went. Best-effort and existence-checked: a disposed
1201
1244
  // instance must not resurrect a store its caller removed (the teardown
1202
- // contract), and a failed heartbeat must never turn cleanup into a throw.
1245
+ // contract), and a failed heartbeat must never turn cleanup into a
1246
+ // throw.
1203
1247
  if (turnEndSeen === 0 && passesStarted === 0) {
1204
- try {
1205
- if (existsSync(evidenceDir()))
1206
- await record(
1207
- "auto_capture_dispose",
1208
- {
1209
- armed: true,
1210
- turn_end_events: 0,
1211
- passes: 0,
1212
- reason: "no_turn_end_observed",
1213
- subscribed: `[${CAPTURE_EVENT_TYPES.join(",")}]`,
1214
- },
1215
- false,
1216
- );
1217
- } catch {
1218
- // observability must not break teardown
1219
- }
1248
+ if (existsSync(evidenceDir()))
1249
+ await recordBestEffort(
1250
+ "auto_capture_dispose",
1251
+ {
1252
+ armed: true,
1253
+ turn_end_events: 0,
1254
+ passes: 0,
1255
+ reason: "no_turn_end_observed",
1256
+ subscribed: `[${CAPTURE_EVENT_TYPES.join(",")}]`,
1257
+ },
1258
+ false,
1259
+ );
1220
1260
  }
1221
1261
  };
1222
1262