Skip to content

fix(opencode): make repetition-guard recovery run-wide, visible and typed (Refs #738) - #757

Closed
agenteinstinct1-max wants to merge 11 commits into
dev-vibecodedfrom
arena/d8d7b08b-silvercode
Closed

agenteinstinct1-max wants to merge 11 commits into
dev-vibecodedfrom
arena/d8d7b08b-silvercode

Conversation

@agenteinstinct1-max

Copy link
Copy Markdown
Collaborator

Issue for this PR

Refs #738

Replacement for the draft #747 (its branch is not pushable from this repair
session; #747 stays open and untouched).

Type of change

  • Bug fix
  • New feature
  • Refactor / code improvement
  • Documentation

What does this PR do?

Adds bounded automatic recovery at the processor/run-loop level for #738, then
repairs the four failures found by independent runtime qualification of #747.

The feature (kept): when RepetitionDetectedError ends a generation, the turn
auto-continues once with a synthetic user message that states the response was
cut off by the repetition guard, carries the repeated-fragment detail, says the
pre-cutoff text is preserved in the transcript while the repeated fragment was
discarded, and asks the model to proceed without repeating it. The guard stays
armed; a second trip surfaces the error and stops deterministically.
REPETITION_RECOVERY_MAX = 1.

Repair:

  1. Erased errored content. MessageV2.toModelMessages dropped every
    assistant message with error, so the recovery request lost the persisted
    text and any completed bash/tool call from the aborted generation, and the
    model re-issued a finished call. The guard abort is now the one errored
    shape whose persisted parts stay visible. This replays transcript state only:
    completed calls keep their recorded output, pending/running calls keep the
    existing [Tool execution was interrupted] rendering, and nothing executes
    again.
  2. Run-wide bounded budget. The feat(opencode): recover the turn after the repetition guard trips (Refs #738) #747 budget was a runLoop local, so a
    queued prompt that made its caller re-enter through a fresh runLoop reset
    it - a third request and a second trip away from the original prompt. The
    budget is now derived from the persisted continuation lineage
    (metadata.repetitionRecovery.promptID), so every re-entry sees the same
    spent budget; a recovery whose own generation tripped the guard is terminal
    at the top of the loop, and a run that ends on an unrecovered trip returns to
    every joined caller instead of starting another run.
  3. Recognised continuation lineage. subagent-result only treated the
    finish/stagnation nudges as prompt continuations, so the assistant after a
    recovery did not continue the prompt (continuesPrompt false, breaking
    provenance and subagent success). The recovery message is now an explicit
    runner continuation of the prompt it names; a stale declaration (a real user
    prompt landed in between) remains a boundary.
  4. Typed guard identity. Recovery used to match REPETITION_MESSAGE in any
    stored error, so a provider HTTP 400 that only quoted the guard text
    recovered the turn. MessageV2.fromError now stamps the persistent error
    with a stable guard marker (UnknownError.data.ref); name and message text
    are unchanged, and an APIError can never carry it.

Guard thresholds/defaults, the error message text, the retry exclusion,
fence suppression and the doom-loop detector are unchanged. No production
revert of the accepted #735 tui base. The four inherited win-owner-death test
seeds were dropped because they are neither in the accepted base nor part of
this work.

How did you verify your code works?

Real mock runtime with counter controls (llm.calls, llm.inputs, llm.misses,
llm.pending), plus a queued-prompt join and a completion-gated SSE tool call:

  • recovery issues exactly one synthetic message, with fragment detail and
    metadata.repetitionRecovery = { promptID, attempt: 1 }, and continues
  • the aborted generation's persisted text is present in the second request
  • a completed bash call from the aborted generation stays visible in the
    recovery request (call id + output) and executes exactly once
  • a second trip stops with the error surfaced and only two requests
  • a prompt queued while the guard trips cannot reset the budget: two requests,
    one recovery, no third request, no second recovery
  • an HTTP 400 carrying the guard text does not recover (one request, APIError)
  • lineage unit tests: recovery continues its prompt; a stale lineage does not;
    other synthetic messages remain boundaries

Results:

  • bun test test/session/prompt.test.ts test/session/repetition-guard.test.ts test/session/subagent-result.test.ts test/session/message-v2.test.ts:
    245 pass, 1 pre-existing skip, 0 fail (246 tests, 889 expect calls)
  • bun test test/session/llm.test.ts test/tool/task.test.ts: 127 pass, 0 fail
  • bun test test/session/{processor-effect,processor-child-write-race,retry, session-schema,schema-decoding}.test.ts: 124 pass; the structured-json retry
    test hit its pre-existing 5s deadline under parallel load and passes alone
  • tsc --noEmit in packages/opencode (its typecheck script): exit 0, 0 errors
  • mutation checks: dropping the visibility carve-out fails the recovery and
    tool-marker tests; restoring text matching fails the HTTP-400 test; removing
    the terminal checks fails the queued-prompt test; ignoring the lineage marker
    fails the continuation test

Head: d53ccb46e5865e1321c9974ce87112a0950ea482 on
arena/d8d7b08b-silvercode.

Screenshots / recordings

Not a UI change.

Checklist

  • I have tested my changes locally
  • I have not included unrelated changes in this PR

arena-agent and others added 11 commits October 31, 2026 09:38
…#442)

win32-gated integration coverage that runs on the existing windows-latest
matrix leg and exercises the real spawn path bound to the Job Object: the
owner is force-killed with TerminateProcess and the worker tree is then
verified gone through real process inspection (OpenProcess + tasklist),
with both listening ports probed for release.

Two properties are covered:

- happy path: a force-killed owner takes the worker tree and its listening
  ports with it; incremental identity capture off the Bun.spawn handle
  (worker -> child -> child-port -> ready) means every PID is known as soon
  as it is created, so cleanup can reap a tree that never finished starting.
- stall path: the grandchild binds its port but never writes its ready line
  (SILVERCODE_TEST_GRANDCHILD_SILENT=1), so the bounded identity wait must
  fail at the deadline rather than hang, and the half-built tree must still
  leave nothing behind. Anti-vacuous-pass guards assert both PIDs were
  captured and grandchildPort stayed undefined, so a slow startup cannot
  masquerade as the stall.

All waits are hard-bounded (tasklist capped to the remaining budget, socket
probes 2s, cleanup raced against its own budget). The stall test sets its own
per-test timeout; the package default --timeout 30000 is unchanged.

Tests and fixtures only - no production or workflow changes. Existing #561
and #568 unit tests are untouched.

Co-authored-by: arena-agent <[email protected]>
unit (windows) failed at 366f0a9. The stall test's identity wait consumes
STALL_BUDGET_MS by design - `ready` is suppressed, so the bounded promise
never settles - which left the original `deadline` in the past for every
phase that followed:

  tasklistHasPid(pid, deadline)
    -> Math.max(1, Math.min(15000, negative)) = 1ms allowance
    -> exitedDueToTimeout, so it throws instead of reporting the pid
  bounded(owner.exited, ..., deadline)
    -> Math.max(0, negative) = 0ms allowance
    -> rejects with "the owner never exited after TerminateProcess"
       before the owner has had time to die

Reproduced directly: after the identity wait the remainder is -1ms, and a
0ms bounded rejects a promise that settles 30ms later, while the same
promise resolves against a fresh deadline.

The happy-path test was never affected because its bounded(treeReady)
resolves early and leaves most of the budget intact. Local verification
missed this because the Linux harness substitutes process.kill(pid, 0) for
tasklist and already used fresh deadlines.

Every phase after the identity wait now runs on its own fresh deadline:
STALL_PROBE_MS (15s) for pre-kill liveness and the owner's exit, and
STALL_VERIFY_MS (20s) for post-kill verification. STALL_BUDGET_MS is raised
15s -> 40s to match the budget already proven comfortable on windows-latest,
so a slow cold start cannot make the anti-vacuous-pass guards fire. The
per-test timeout follows the arithmetic: 40 + 15 + 20 + 5 cleanup = 80s,
so STALL_TEST_TIMEOUT_MS = 90_000. The package default --timeout 30000 is
still untouched. No assertion was weakened or reordered.

Co-authored-by: arena-agent <[email protected]>
…t await throws

unit (windows) at 34d8f92 failed the stall test at
win-owner-death.integration.test.ts:507:102 - inside `.rejects.toThrow(` -
with `Received message: "The user aborted a request"`.

That line was the first statement of the `try`. Asserting the bounded
identity wait inline means ANY rejection there throws straight out of the
test, so every post-timeout assertion is skipped and the "leaves nothing
behind" property - the whole point of the test - is never verified.

Reproduced both halves locally:

- before: injecting that rejection makes the test bail immediately with
  zero assertions executed and no cleanup verification
- after: 7 cleanup/safety assertions run and pass (no survivors, both PIDs
  gone, both absent from the process list, worker port closed and
  rebindable), and only then does the diagnostic assertion report
  `Received: "The user aborted a request"`

Structure is now capture -> kill -> verify -> clean up -> assert. The
outcome of the identity wait is captured instead of asserted inline; probes
are wrapped so a wedged one yields its message (which then fails the
assertion consuming it) rather than either throwing early or being silently
read as "absent"; `settled()` is the non-throwing form of `until()`. Cleanup
runs before the assertions, so no failed assertion can leave a live process
on the runner.

The FETCH_ABORTED itself is not produced by this test. Verified: there is no
fetch, AbortController or abort signal anywhere in the four files;
make-fetch-happen, minipass-fetch and npm-registry-fetch are absent from the
entire repository; and bounded(treeReady, ...) can only ever reject with its
own message, because treeReady has no reject path. Locally the identity wait
rejects with exactly "the worker never reported its identity" and the
assertion passes. So this commit does not claim to fix the source of that
error - it makes the test survive it, verify what it exists to verify, and
report the unexpected message precisely.

No budget or timeout changed: STALL_BUDGET_MS stays 40_000,
STALL_TEST_TIMEOUT_MS stays 90_000, and the package default
(--timeout 30000) is untouched. No assertion was removed or weakened.

Co-authored-by: arena-agent <[email protected]>
…, harden deadlines

Applies the independent review verdict on 34d8f92.

Budget envelope. The 90s per-test timeout was a consequence of raising
STALL_BUDGET_MS from 15s to 40s, not of the negative-allowance fix. With a
fresh deadline per phase the fix stands on its own, so the raise is
reverted: STALL_BUDGET_MS 40_000 -> 15_000 and STALL_TEST_TIMEOUT_MS
90_000 -> 45_000, back inside the previously accepted 40/50 envelope. No
new deviation. Verified locally on a Linux-runnable copy of the real file:
the stall test now completes in 15.09s and both tests pass.

The timeout comment claimed 40+15+20+5=80s and omitted the `finally`
reapTree. It now gives the arithmetic by case instead of one sum: nominal
~21s, worst single-phase-failure 15+3+20+5=43s which fits, and the one
path that does not fit - probe AND verify phases both exhausting their
ceilings, 55s - where the timeout fires and the test fails loudly rather
than hanging.

Deadline guards. `bounded` and `tasklistHasPid` no longer clamp a spent
deadline to 0ms/1ms, which reported "the thing never happened" when the
real cause was "the caller's budget was already gone". Both now throw a
distinct "deadline already expired" error. Covered by a test that asserts
the exact messages, so the guard cannot rot silently.

PID-recycling guard. `reapTree` now takes the set of PIDs this test already
proved dead and skips them: a recycled PID would otherwise be signalled,
killing something the runner needs. The survivor check applies the same
guard, so a reused PID cannot be reported as a false survivor. Survivors
are also now computed BEFORE the manual reap, so the assertion proves the
job took the tree down rather than that our own cleanup did.

Positive log control. The adopter only logs on failure, so a clean run
produces no `log:` messages at all - which let the "(#442)"-free assertion
pass vacuously if IPC forwarding broke. The owner fixture now sends a
`log:owner-log-channel-ok` sentinel and both tests assert it arrived, so an
empty log is a failure rather than a pass.

No assertion removed or weakened; the package default --timeout 30000 is
untouched.

Co-authored-by: arena-agent <[email protected]>
…next commit)

Temporary, deliberately broken commit. `adoptWorkerProcess` no longer calls
the adopter, so a spawned worker is never put into the owner's kill-on-close
Job Object - i.e. the state #561/#568 exist to prevent.

Expected: unit (windows) goes RED on the owner-death tests' survivor
assertion, because a force-killed owner no longer takes the worker tree
down. If those tests still passed with the binding disabled they would be
proving nothing.

win-job's own 21 unit tests still pass under this mutation because they
drive `createOwnerJobAdopter` directly rather than `adoptWorkerProcess`, so
the red signal is isolated to the integration coverage.

Reverted in the next commit.

Co-authored-by: arena-agent <[email protected]>
Review item (b) covered the happy path's `owner.exited` as well as the stall
test's, and only the stall test had been converted. The happy path still
passed its original `deadline` to ten calls - `tasklistHasPid` four times,
`bounded(owner.exited)`, `until` four times and `bounded(canBind)` twice.
Those were tolerable while a spent deadline merely clamped to a 1ms/0ms
allowance; once the distinct expiry guard landed, every one of them became a
hard throw as soon as the budget was spent.

Both tests now use `deadline` for exactly one thing - the identity wait - and
take a fresh `PROBE_BUDGET_MS` (15s) for the pre-kill liveness and owner exit
and a fresh `VERIFY_BUDGET_MS` (20s) for everything after the kill. The two
constants were renamed out of their stall-specific names because both tests
use them; their values are unchanged, so no budget was raised.

Verified on a Linux-runnable copy of the real file with the Job Object
contract emulated: both tests pass, the stall test completing in 15.10s, 33
expect() calls.

Co-authored-by: arena-agent <[email protected]>
After RepetitionDetectedError trips a generation, the run loop injects a
single synthetic recovery user message (bounded at REPETITION_RECOVERY_MAX
= 1 per turn) stating that the response was cut off by the repetition guard
with the repeated-fragment detail, that text produced before the cutoff is
preserved in the transcript, and instructing the model not to repeat the
fragment and to proceed with the task. The guard stays armed during recovery;
a second trip surfaces the error and stops. The message never claims
'nothing happened' since earlier tool calls may have executed.

One bounded recovery nudge cannot trip the doom-loop detector, which only
fires on three identical completed tool calls.

Refs #738
Takes the accepted dev-vibecoded tip 2e94981 that 65efb5b merged into the
feature branch (including the accepted #735 tui work) and the feature's
prompt/run-loop change. Drops the four inherited win-owner-death test seeds,
which are not in the accepted base and are not part of this repair.

Co-authored-by: arena-agent <[email protected]>
…Refs #738)

Repairs the #738 recovery patch taken over from #747. The feature itself is
kept: one bounded synthetic continuation after a repetition-guard trip, the
guard still armed, a second trip surfaced. Four qualification failures fixed:

- Erased errored content: MessageV2.toModelMessages dropped every errored
  assistant message, so the recovery request lost the text and the completed
  bash call persisted before the guard aborted - the model re-issued a
  finished call. The guard abort is now the one errored shape whose persisted
  parts stay visible. Only transcript state is replayed; completed calls keep
  their recorded output and still-pending ones keep the existing
  "[Tool execution was interrupted]" rendering, so nothing re-executes.

- Local budget: the per-runLoop counter reset when a queued prompt made its
  caller re-enter through a fresh runLoop, which produced a third request and
  a second trip. Recovery is now counted from the persisted continuation
  lineage (metadata.repetitionRecovery.promptID), the recovery's own guard
  trip is terminal at the top of the loop, and a run that ends on an
  unrecovered trip returns to every caller instead of starting another one.

- Provenance: subagent-result only treated the finish/stagnation nudges as
  continuations, so the assistant after a recovery did not continue the
  prompt. The recovery message is now a recognised runner continuation of the
  prompt it names, and a stale lineage (a real prompt landed in between) stays
  a boundary.

- False positive: recovery matched REPETITION_MESSAGE in any stored error, so
  an HTTP 400 that merely quoted the guard text recovered the turn.
  MessageV2.fromError now stamps UnknownError.data.ref with a stable guard
  identity; the name and message text are unchanged, and an APIError can
  never carry the marker.

Verified:
- bun test test/session/{prompt,repetition-guard,subagent-result,message-v2}.test.ts
  -> 245 pass, 1 pre-existing skip, 0 fail (246 run, 889 expects)
- bun test test/session/llm.test.ts test/tool/task.test.ts -> 127 pass, 0 fail
- bun test test/session/{processor-effect,processor-child-write-race,retry,
  session-schema,schema-decoding}.test.ts -> 124 pass; the structured-json
  retry test hit its 5s budget under parallel load and passes alone (4.8s,
  pre-existing tight deadline)
- tsc --noEmit in packages/opencode (the package typecheck script) -> exit 0,
  0 errors
- mutation checks: dropping the visibility carve-out fails the recovery and
  tool-marker tests; restoring text matching fails the HTTP-400 test; removing
  the terminal checks fails the queued-prompt test; ignoring the lineage
  marker fails the continuation test

Co-authored-by: arena-agent <[email protected]>
@github-actions

Copy link
Copy Markdown

Thanks for your contribution!

This PR doesn't have a linked issue. All PRs must reference an existing issue.

Please:

  1. Open an issue describing the bug/feature (if one doesn't exist)
  2. Add Fixes #<number> or Closes #<number> to this PR description

See CONTRIBUTING.md for details.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants