Repository navigation
fix(capture): evidence writes are best-effort; the subscription survives them - #482
Conversation
…ion alive An unwritable evidence log ended the auto-capture event subscription for the rest of the process. Only the start receipt was guarded; every other receipt could still throw into the for-await loop, and the receipt that would report the failure could not be written either. Evidence writes on the capture path now go through one best-effort policy in the telemetry module: a failed line is counted in process memory and dropped, never thrown. memory_status reports the count under AUTO-CAPTURE, with the caveat that the log-derived health lines above it under-count. The subscription guard now covers a whole event, including the receipt that reports a failure, so one turn cannot end capture.
There was a problem hiding this comment.
Verdict: request changes — one blocker, three nits
The architecture is right and I am not asking for rework: the whole-event-body guard is what ticket item 3 ("the loop survives every handler failure") actually requires, the cursor advance on a failed completion receipt is the policy's mandated consequence, and the counter scope matches the ticket. One of the new tests turns the test-windows job red; that is the only thing between this PR and an approve.
Blocker
test/telemetry/evidence-write-policy.test.ts:103assertstoContain("EACCES"). On Windows the chmod-0400 append fails with a different error code, so the informationaltest-windowsjob fails on this PR; it was green on the most recent PR CI before it (fix/461at952d471, all checks success).
Evidence:gh pr checks 482→test-windows fail; job log:The policy itself works on Windows — line 101 (103 | expect(String(lost?.lastError)).toContain("EACCES"); error: expect(received).toContain(expected) Expected to contain: "EACCES" (fail) a failed async evidence write is counted and never throwndropped === 1) passed, so the write failed and was counted; only the error-code name is wrong.
Not blocking once: the assertion tolerates the platform code (e.g.toMatch(/EACCES|EPERM/)) or the test is skipped on Windows the way the repo's other chmod tests do (test.skipIf(process.platform === "win32")attest/init/init.test.ts:469,describe.skipIfattest/store/store-permissions.test.ts:41).
Nits (do not hold merge)
src/capture/runtime.ts:1165— the loop's catch swallows the error with noconsole.warn.guarded()treats the console line as the primary trace precisely because the log can be the broken channel (src/core/hooks.ts:37-40); with the log down, acapture_threwmessage is lost entirely and the counter names only the failed receipt event, not the underlying failure.src/telemetry/record.ts:344—lastErrorstores the raw error message andmemory_statusrenders it. Repo precedent redacts mirrored error text (src/index.ts:126-127"never the message, which can carry conversation content";src/capture/runtime.ts:1179runsredactSecretson thecapture_threwerror). fs errors carry paths, but a throw frombuildEvidenceLinecould carry field values.src/telemetry/record.ts:344—String(err)throws on a Symbol rejection and escapes the wrapper, defeating the policy for that case; the comment directly above considered messageless Errors and non-Error rejections but not this one.
What I measured
- Bug reproduces on
374a0cf: exported the commit, ran the ticket's shape (log0400before turn 1, two turns, counted model calls):REPRO turn1_reached=true turn2_reached=false - Fix confirmed on
0b43ee6, same script:REPRO turn1_reached=true turn2_reached=true. - Fail-before verified: the committed
test/capture/capture-unwritable-log.test.tsrun against the374a0cfexport fails at:134:7and:166:7,Expected: true Received: false— the third turn never dispatches, the claimed reason. - Branch: the 9 new tests pass;
bun test test/capture/→ 263 pass / 0 fail;bun test test/telemetry/→ 0 fail (1 skip, pre-existing Windows-only rotation test, also skipped on the374a0cfexport). - Strict-site claims hold:
src/events.ts:169is insideguarded("tool.execute.after")(src/events.ts:113);src/index.ts:362is insideguarded("plugin_load heartbeat")(src/index.ts:309); thehook_errorreporter (src/index.ts:129-141) self-swallows with.catch(() => {}); everyrecordinsrc/capture/triggers.ts(:195, :212, :238, :272, :293, :382) is reached only throughguardedcallers (src/events.ts:132, :219, :243). gate.tsstrictness is consistent, not an oversight: every capture-pathrunWriteGatesits in the try atsrc/capture/runtime.ts:960whose catch (:989) records best-effort and continues, so a gate-side write failure costs one candidate and the loop survives; the strict audit line keeps its contract for non-capture callers.- 17 best-effort call sites in
src/capture/runtime.ts(grep count); README 4028 words; no.skip/.onlyin the new tests; no existing test file touched by the diff; added comments and shipped strings carry no issue numbers or dates.
Why the contested choices are accepted
- Whole-event-body guard: with a writable log a logic error still surfaces exactly as before — the
capture_threwreceipt lands viarecordBestEffort. With a broken log the old code died permanently and silently; the new code counts the loss and keeps capturing. Nothing escapes the loop: the inner catch takes body errors, the outer catch takes iterator errors, and the abort check (src/capture/runtime.ts:1169) still leaves on teardown. - Cursor advance on a failed completion receipt: ticket item 1 says a failed write must never propagate into the code the line describes; the advance is that code. The old behavior did not merely re-mine —
capture_cost(:684) precedes the store write (:960), so the throw also skipped writing the durable rows and re-paid the model call. Disclosed in "What is NOT fixed" item 5. - Counter scope: the ticket says a counter checked by
memory_statusis enough, andmemory_statusruns in the plugin's process. The TUI-panel and restart gaps are real, disclosed, and need a different channel — ticket them, do not block on them.
What merging this will NOT mean
Capture is not reliably observable: the terminal panel cannot see the counter, a restart clears it, a store that lost writes in an earlier process reports nothing, and guarded()'s hook_error mirror drops stay invisible to the counter. The report line is honest about all of it ("by this process"), but silence means "this process lost nothing", not "the log is fine".
Follow-up tickets to file
- Carry the dropped-writes count in the status file the terminal panel reads — a channel independent of the broken evidence log; closes both the TUI blind and the restart-forgets gap.
- Count
guarded()'shook_errormirror drops (PR "NOT fixed" item 4).
…scrub the kept error A read-only evidence file reports EACCES on POSIX and EPERM on Windows, so the counter test now matches either name instead of pinning one. The capture loop's catch now writes the console line that guarded() treats as the primary trace: when the evidence log is the broken channel the receipt cannot land and the underlying failure would disappear with it. The kept error text is scrubbed at the same boundary as every other mirrored error, and the rejection-to-text conversion no longer trusts String() to be total — a rejection whose own toString throws would otherwise raise from inside the handler that exists to swallow it.
|
Round 2 done — Blocker — matched, not skipped. Confirmed the code from the job log rather than guessing:
Nit 1 — fixed. The loop's catch now writes the console line before the receipt, in Your point is right and the comment says why: the counter names only the receipt event that failed, never the cause, so with the log down the cause had no trace at all. Nit 2 — fixed. Nit 3 — your Symbol claim is wrong, but there is a real hazard on that line, and I fixed that one.
What does escape it is a rejection whose own function describeError(err: unknown): string {
if (err instanceof Error && err.message) return err.message;
try {
return String(err);
} catch {
return `unprintable ${typeof err}`;
}
}No test for it: a throwing Checks. The two touched files: 10 pass / 0 fail. |
There was a problem hiding this comment.
Verdict: approve
Round-2 delta verified against 0b43ee6..7a75c83; all four items hold. CI at 7a75c83: lint, test, smoke, test-windows all pass.
Item-by-item
- Blocker.
test/telemetry/evidence-write-policy.test.ts:106is nowtoMatch(/EACCES|EPERM/), noskipIf, Windows coverage retained —test-windowsgreen at this head.git diff 0b43ee6..7a75c83 -- test/shows only that assertion and the new scrub test; nothing weakened. - Nit 1.
src/capture/runtime.ts:1170-1177warns before the receipt, inguarded()'s shape ("[opencode-self-improvement] auto-capture (idle) hook failed (ignored):", matchingsrc/core/hooks.ts:37-40), after the abort check so teardown stays quiet. - Nit 2.
src/telemetry/record.ts:359—redactSecrets(describeError(err))runs at store time insidenoteDroppedWrite, so the raw value never enters the map thatmemory_statusrenders. The new test injectssk-...into the store path and asserts bothnot.toContain(token)andtoContain("[redacted]"); passes locally. - Nit 3 — I concede. My claim was wrong:
String(Symbol("boom"))returns"Symbol(boom)"—String()is the explicit conversion the spec allows; only implicit coercion throws. Measured:bun -e 'console.log(String(Symbol("boom")))'→Symbol(boom). The substituted hazard is real and I had it backwards:String(err)does propagate atoStringthat throws (TypeErrormeasured), andnoteDroppedWriteruns inside the wrapper's own catch, so that throw would have escaped the policy.describeError()is total — measuredSymbol(boom)/unprintable object/Error/42for symbol, throwing-toString, messageless Error, and number. The no-test call is accepted: I cannot name an injection point either —appendLogrejects with fsErrorinstances and line-building throwsErrors, so the branch is defensive-only and testing it would require exporting a private helper for an unreachable path.
Branch run at 7a75c83: bun test test/telemetry/ test/capture/capture-unwritable-log.test.ts → 72 pass / 1 skip (pre-existing Windows rotation test) / 0 fail. Added lines carry no issue refs, dates, or narration; README untouched at 4028 words.
What this merge does NOT fix
- The terminal panel cannot see the counter until the count rides the status file; only the chat surface reports a broken log.
- A restart clears the count; silence after a restart means "this process lost nothing", not "the log is fine".
gate.tsevidence writes stay strict by design — the audit line is the write's contract; a gate-side write failure during capture costs one candidate and the loop survives it.guarded()'shook_errormirror drops remain invisible to the counter.- Verification is unit-level; no e2e scenario drives this failure mode through the real host.
Follow-up tickets
- Carry the dropped-writes count in the status file the terminal panel reads — a channel independent of the broken evidence log; closes the TUI blind and the restart-forgets gap together.
- Count
guarded()'shook_errormirror drops (PR "NOT fixed" item 4).
WhollyMindless
left a comment
There was a problem hiding this comment.
Note
🤖 GPT-6.2 Astra responding on behalf of WhollyMindless
Could the new idle-capture warning use the same redacted, length-limited message as the evidence receipt? At 7a75c83, src/capture/runtime.ts passes the original err object to console.warn, then redacts its message for auto_capture_refused a few lines below. The two outputs therefore have different privacy guarantees for the same failure.
In the Windows capture test I saw the injected provider error message and its stack in the console. The fixture used an ordinary error, and all ten focused tests passed. Computing the safe message once and using it for both outputs would preserve the warning when the evidence file is unwritable. A console assertion alongside the existing redaction test would pin that behavior.
…nels The console warning printed the original error object while the evidence receipt a few lines below printed a redacted, length-limited message, so the same failure had two privacy guarantees on two channels and the console line carried the credential-bearing message and the stack. One function now renders every mirror of a capture failure: message only, credential-scrubbed, capped at the length the receipt already used. The counter's stored error text goes through it too, so all three channels agree.
|
Fixed in One computation site. export function safeErrorMessage(err: unknown): string {
return redactSecrets(describeError(err)).slice(0, MIRRORED_ERROR_MAX);
}
The outer iterator catch has no such asymmetry. It binds nothing ( Tests. Line 272 is the one that pins your point: the console tail and the receipt field must be the same string, so a cap or scrub change lands on both or the test fails. Console output is captured with Fail before. The console assertion run against Raw token, no cap, and Checks. Touched files 12 pass / 0 fail. |
There was a problem hiding this comment.
Verdict: approve at head 9f4d3b3 (supersedes my 7a75c83 approval)
Delta 7a75c83..9f4d3b3 verified item by item. CI at this head: lint, test, smoke, test-windows all pass.
- Single computation site.
safeErrorMessage()(src/telemetry/record.ts:358-360) isredactSecrets(describeError(err)).slice(0, MIRRORED_ERROR_MAX),MIRRORED_ERROR_MAX = 200.src/capture/runtime.ts:1176computesconst failure = safeErrorMessage(err)once and feeds both the console line and the receipt'serror; the counter'slastError(src/telemetry/record.ts:374) calls the same function. Cap claim verified against the old head, not trusted:git show 7a75c83:src/capture/runtime.tsline 1189 already applied.slice(0, 200)to theauto_capture_refusedreceipt, so the named constant preserves the existing value. - No Error object to console. The warn is now one template string with no second argument, so neither channel can format the raw error or its stack. My own repro of the old shape:
bun -e 'const err=new Error("provider rejected sk-AbCdEfGhIjKlMnOpQrSt"); console.warn("[opencode-self-improvement] auto-capture (idle) hook failed (ignored):", err)'printed the token and a stack frame — exactly the maintainer's finding; the new shape cannot. - New assertions.
test/telemetry/evidence-write-policy.test.ts:268-273pins token absence,[redacted], the:272equality between the console tail and the receipt'serror, and the 200 cap;:281-290pinssafeErrorMessagedirectly (scrub, cap, throwingtoString, Symbol). Fail-before at7a75c83measured: the console line carriedError: provider rejected sk-AbCdEfGhIjKlMnOpQrSt yyy…and:268failed. One honest caveat: the committed file as a whole cannot run at7a75c83— thesafeErrorMessageimport is a module-levelSyntaxErrorthere — so the behavioural fail-before needs the new unit test stripped first. That is inherent to pinning a new export and not a defect. - Untouched surfaces. The outer iterator catch is unchanged and still writes nothing (
git diff 7a75c83..9f4d3b3contains nocatch {hunk; the region reads// the subscription itself ended … nothing to do). The otherconsole.warncalls inruntime.ts(:227, :235, :455, :1279) take static/config strings, no error objects.guarded()is not in the diff. - Scope. Three files, 103 added lines, all on the finding; no assertion weakened (the test-file diff is imports plus two new tests); added prose carries no issue refs, dates, or narration; README untouched at 4028 words.
Suite at this head: bun test test/telemetry/ → 73 pass / 1 skip (pre-existing Windows rotation test) / 0 fail.
What this merge does NOT fix
- The terminal panel cannot see the dropped-writes counter until it rides the status file; only the chat surface reports a broken log.
- A restart clears the count; silence after a restart means "this process lost nothing", not "the log is fine".
gate.tsevidence writes stay strict by design — the audit line is the write's contract.guarded()'shook_errormirror drops remain invisible to the counter.guarded()'s ownconsole.warn(src/core/hooks.ts:37-40) still passes the raw error object — the same stack-and-credentials channel this commit closed for the capture loop is open there for every other hook.- Verification is unit-level; no e2e scenario drives this failure mode through the real host.
Follow-up tickets
- Carry the dropped-writes count in the status file the terminal panel reads — a channel independent of the broken evidence log; closes the TUI blind and the restart-forgets gap together.
- Count
guarded()'shook_errormirror drops (PR "NOT fixed" item 4). - Route
guarded()'s warn throughsafeErrorMessage()— same finding, one channel wider.
|
🎉 This PR is included in version 0.33.10 🎉 The release is available on: Your semantic-release bot 📦🚀 |
What was broken, measured
One subscription, turn-end events dispatched to three different sessions, the day
file set
0400after the first healthy pass. Countedgenerate.textcalls.374a0cf, log breaks mid-sessioncapture_costwrite then throws into thefor awaitand the loop ends; turn 3 never dispatches374a0cf, log breaks and the model call also failsauto_capture_refusedreceipt inside the pass-error handler throws, same endThe failure receipt that would report this (
capture_threw) is itself an evidencewrite, so it cannot land either: the channel that breaks is the channel that would
tell you.
The policy
An evidence write that fails has lost one diagnostic line and nothing else: the
failure is counted in process memory and dropped, and it never propagates into the
code the line describes.
It lives in one place —
src/telemetry/record.ts— asrecordBestEffort,recordSyncBestEffort,recordCaptureLagBestEffortover thesame
record/recordSyncprimitives, plusdroppedEvidenceWrites(). The capturepath imports only the best-effort names, so a receipt added later cannot forget the
policy the way a per-site
trycan.The guard on the subscription moved too: it now covers a whole event body,
including the receipt that reports a failure. See Where I disagree below.
The one place deliberately NOT caught
runWriteGate(src/gate/gate.ts) keeps its strictrecord/recordWriteBlocked.A gate audit line is not a footnote on a completed operation — it is part of the
write's own contract:
write_promotedis what makes a promoted row provable andwrite_blockedis what makes a refusal reviewable. Swallowing those would turn anunprovable write into a reported success, which is the failure the
evidenceErrorfield exists to kill. This is also the boundary the ticket draws itself: the write
gate's verdict behaviour is not this ticket. Nothing is lost by leaving it strict —
every
runWriteGatecall in the capture pass already sits inside a handler whosereceipt is now best-effort, so a gate-side write failure costs one candidate and
the loop survives it.
The same reasoning keeps
record/recordSyncstrict for every non-capture caller:a viewer edit or a tool write that cannot write its audit line is a failed operation
the operator must see.
Sites swept
Every evidence write reachable from the capture handler — 17 in
src/capture/runtime.ts, all now best-effort:src/capture/runtime.ts:441auto_capture_refused(no write target)src/capture/runtime.ts:458auto_capture_refused(no_model)src/capture/runtime.ts:525auto_capture_skipped(no signal)src/capture/runtime.ts:547auto_capture_skipped(transcript_too_thin)src/capture/runtime.ts:651auto_capture_start(recordSync; its localtry/catchis gone — the wrapper replaced it and now counts too)src/capture/runtime.ts:687capture_costsrc/capture/runtime.ts:734auto_capture_rules(no_user_turn)src/capture/runtime.ts:753auto_capture_rulessrc/capture/runtime.ts:847auto_capture_lessonssrc/capture/runtime.ts:882auto_capture_restatablesrc/capture/runtime.ts:938auto_capture_contradictionsrc/capture/runtime.ts:992auto_capture_partial/auto_capture_refused(gate threw)src/capture/runtime.ts:1013auto_capture_<action>/auto_capture_compaction_<action>src/capture/runtime.ts:1072auto_capture_scansrc/capture/runtime.ts:1095capture_lag(recordCaptureLagBestEffort)src/capture/runtime.ts:1173auto_capture_refused(capture_threw, in the loop's catch)src/capture/runtime.ts:1213auto_capture_dispose(its localtry/catchis gone; theexistsSyncteardown guard stays)Checked and left alone, with the reason:
src/events.ts(its only awaited writealready runs through
guarded()),src/index.ts(theplugin_loadheartbeat isguarded(), thehook_errorreporter is fire-and-forget),src/capture/triggers.ts(every entry point is
guarded()),src/gate/gate.ts(above),src/telemetry/ledger.ts(already fail-soft with its own counter).Where the counter lives and what memory_status says
droppedEvidenceWrites()insrc/telemetry/record.ts: a per-process map keyed bythe evidence directory, so one store's broken log is not another store's report.
memory_statusreads it and renders it under AUTO-CAPTURE:The second line is the point. Without it a reader weighs a missing receipt as proof
the pass never ran, when the health lines above are read back out of the log that is
dropping them. The line is absent when this process lost nothing.
Fail before
Both regression tests fail on
374a0cffor the contract they pin, verified byrunning the committed file against an export of that commit:
Both pass on this branch.
Tests
9 new tests, no existing test weakened, skipped or widened.
test/capture/capture-unwritable-log.test.ts— 2: the loop survives a failedcompletion receipt and a failed failure receipt; a later turn still dispatches.
test/telemetry/evidence-write-policy.test.ts— 7: async, sync and lag wrapperscount and do not throw; the strict writer still throws and stays out of the
counter; the counter is scoped per store; the report line names the loss, states
the under-count and truncates an unbounded error;
memory_statusshows the lossafter a broken log.
Full suite
bun run test: 1644 pass / 21 skip / 0 fail, 14398 expects.bun run typecheckclean.bun run lintexit 0, noFound N error.bun run lint:comments:comment-lint: clean(123 added comment lines).No e2e run was made for this change — delivery timing is unchanged and the contract
is unit-level. The pre-push merge gate ran the e2e suite on the way up: 39 pass /
0 fail, 317 expects.
What is NOT fixed
memory_statusruns there; the TUI reads status files, which do not carry it.Only the chat surface reports a broken log.
the channel that is broken. The counter reports the current process only.
guarded()'shook_errormirror is not counted. It already swallows its ownwrite failure with
.catch(() => {}), so nothing breaks — but that loss isinvisible to the new counter. Counting it would widen this change past the
capture handler for a channel that still has
console.warn.fails now advances the capture cursor. Before, the throw aborted the pass before
the advance, so the same window was mined again on the next pass and paid for
twice. Advancing is the correct reading of "a window is consumed by the pass that
mined it", but it is a behaviour change beyond the crash fix and belongs in the
open.
Where I disagree
The ticket asks for the catch at the call boundary and, separately, for the loop to
survive every handler failure. The call-boundary catch alone does not deliver
the second:
captureTriggerFor,captureSessionID,setCurrentandcaptureCooldownPassesall run outside the existing innertry, so a throw fromany of them still ended the subscription, and the catch that reports a failure was
itself inside the danger zone. The guard therefore moved to cover the whole event
body — wider than the ticket named, which is the only way item 3 is actually true.
The abort check (
if (controller.signal.aborted) return) is preserved inside it, soteardown still leaves the loop rather than reporting through a removed store.
The ticket calls the counter "enough". It is enough for the chat surface and it is
the only mechanism that can work, for the reason the ticket gives. It is not enough
for a user who restarts, or for the terminal panel — limits 1 and 2 above state what
that costs rather than pretending it is covered.
Closes #479