# The graph: nodes, recovery and timeouts
Conventions for this area of magi. `AGENTS.md` indexes these files: read this
one before changing the code it covers.
## The graft phase: best-effort, label-only, rolled back on any doubt
`[graph] graft_runner_up` (default on) runs `graph::Runner::graft` in
`finish_after_tally`, **before `fold_losers`** (the losers' branches are what the
fixer may read; fold deletes them) and before `sync_to_base` / the review loop.
A fixer round ports the strengths the judges attributed to the losing
candidates onto the winner. Decisions are pure and live in `src/graft.rs`.
- **Skips are visible and leave the winner alone.** `graft::plan` returns a
`Skip` (off, fewer than two candidates, no tally, no quorum, no strengths,
already done); the reason becomes a `graft` run event (`skipped: ...`, once).
The input is only `Judgement::strengths` (`verdict::Ranking::strengths`,
`#[serde(default)]`, asked for in the judge prompt's JSON example; the
heading `independent judges` that the mock greps is unchanged): labels of
non-winning, unfolded candidates, deduplicated across judges and passed
through `blind::sanitize_prose`. Reasons are never mined for strengths.
- **Blindness.** `prompt::graft` (heading `# Graft the runner-up strengths`,
which `tests/common/mod.rs` greps) names the task, labels, branches and the
strengths, never an agent id. The seat is `graft`, never the winner's
`impl-<label>` (`fixer::graft_attempts`), so the conversation that wrote the
winner is not reused.
- **Chain.** It uses `ask_fixer_among` over `fixer::graft_attempts`; handovers
are recorded under exactly `"graft"`, which is in `fixer::FIX_NODES`. A
consequence accepted on purpose: a graft handover is sticky for the later
fix, gate-fix, land and rebase rounds of the same run. Between agents the
worktree is restored to the pre-graft commit.
- **Recovery and measurement.** `RunState::graft` (`GraftRecord`,
`#[serde(default)]`, so `run::SCHEMA` is unchanged) saves `pre` and `Running` *before* the fixer is
called. After it: a failure, a dropped stream, quota, an unusable reply, no
change restores `pre` (`git::restore_to`: `reset --hard` plus `clean -fd`,
never `-x`, so setup products survive) and the run goes on as if graft were
off. Changed lines (numstat added + removed) are measured for observability
only: there is no size limit, and binary or unmeasurable changes are allowed
with `lines: None`. `GraftRecord::limit` is retained only for historical
records; new records use `None`, and reports do not display a limit. A
quota hit pushes `QuotaLoss { node: "graft" }` like other fixer nodes; the
refund rule (`Verdict::quota_hit`) is unchanged and graft never stalls or
blocks the run. A record found `Running` on re-entry is restored to `pre` and
becomes `RolledBack("interrupted")`; a settled record, or a run that already
has reviews, is never grafted again.
- **The one thing that blocks.** A rollback is settled only after the restore
is confirmed (`graft_restore`: `reset` succeeded and `HEAD == pre`). If it is
not (a stale `index.lock`, say), the record stays `Running`, the run becomes
`Blocked` and is resumable, and a resume retries the restore - the rejected
commit is never reviewed, gated or merged.
- Everything after is unchanged: the review loop and `verify.gate` see the
grafted tree like any other.
## An agent's timeout starts at spawn; waiting for infrastructure is not the agent
`agent::invoke` starts `Invocation::timeout` only once the CLI is spawned, and
nothing before that may be charged to it. The old `graph::wave` carved the shared
cache lease wait out of every job (`timeout.saturating_sub(waited)`), so a
contended cache left the agent zero time, read as `timed out`, and walked the
fixer chain (graft: sonnet -> sol -> astra) over a wait that was not the agent's.
- **Two clocks.** An agent's `timeout_*` is its running time. The pre-spawn waits
have their own bound, `[graph] timeout_resource_wait` (default 1800 s): the
wave's cache lease and, as `resource + longest timeout x jobs`, a parallelism
permit. The lease wait polls `Pause` every 5 s, so a park is honoured at once.
- **Expiry is `AgentOutcome::ResourceBlocked`, not `Failed`.** No agent was
spawned, so it never enters `FailClass`, `seat_history`, `QuotaLoss` or a
handover; `ask_fixer_among` and `ask_json_wave` do not advance on it. A wave
never runs a writing seat without the lease (no unmanaged cache writes).
- **The run stops resumably.** `RunState::resource_block` (`#[serde(default)]`,
`run::SCHEMA` unchanged) makes the node return before it records anything
(the review round, graft record and judgements are not written, so the resume
repeats exactly that step with the same agent and seat); the run is `Blocked`.
`daemon::settle_and_diagnose` refunds the attempt and holds the task with a
machine hold prefixed `cache::RESOURCE_HOLD` (`[resource] `); `triage` releases
it when the lease is free. A park request outranks it (the run stays parked).
- **Visible.** `RunState::resource_wait` is set while seats wait; `report::active_seats`
(and so the web run page) says "waiting for the shared build cache (holder)" and
prints no countdown. A seat's `started_at` is re-stamped at spawn
(`seats_spawning`, `seat_spawned`).
- **Separate wall-clock budgets on purpose**: the node/run budgets, `verify.e2e` /
`gate` (`with_cache_lease` bounds acquisition by `timeout_resource_wait`, then
gives commands their full verification budget; acquisition expiry is
`CommandOutcome::resource_blocked`), `dupes` / `github_text` `JUDGE_BUDGET`
(an overall 15 s for a whole check), `retry_budget` (a nudge's quarter),
`talk_wait_bound`, `land::WAIT_CEILING`. `land`, `rebase`, `bump`, talk, deputy,
waiter and conduct invoke without waiting for anything before spawn.
- Known gaps: a parallelism-slot wait still shows the seat as running; an operator-
requested fix records a resource block as an unreported fix instead of holding.
## A takeover inherits evidence, never results
`src/recovery.rs`. A task whose earlier run stopped on a failed verification
used to reopen its branch as a context-free review. `Runner::inherit` (called
from `open_review`) reads the newest earlier attempt that reviewed the branch
and `recovery::assess` (pure) records on `RunState::recovery`
(`#[serde(default)]`, `run::SCHEMA` unchanged) what was inherited and why.
- **Two modes.** `VerifyRepair` only when every condition holds: the last
earlier round had zero blocking findings and every seat answered; a failed
`e2e` (or a `gate` with no gate fix after it) is recorded with a command, a
non-empty output and a `verified_head` equal to that round's head; the branch
tip *is* that head (git `is_ancestor`, never the old record's say-so); the
base did not move; `generation <= MAX_GENERATION`. Anything else is
`FullReview`, and each failed condition is a line in `reasons` (shown in the
event log and `magi show`). A timed-out seat is never a clean panel.
- **Evidence is prompt text.** It is scrubbed and clipped, and is never copied
into a `ReviewRound`: round 1 always runs `verify.e2e` on the head it
reviews, and the gate on the commit that lands. `recovery::recheck`
downgrades a `VerifyRepair` whose branch moved (a base sync) before the
repair starts.
- **One repair, outside `review_rounds`, saved first.** `recovery_repair`
records `Repair::Started` before the fixer (`fix` chain, stem
`fix-recovery`) is called; a start found on re-entry is rolled back and
settled, never retried. A failed fixer's edits are restored; a restore that
cannot be confirmed blocks the run. Its prompt (`prompt::recovery_fix`) keeps
the `Your patch was reviewed` heading and puts the failure ahead of the task.
- **The task's statement survives.** `Takeover::task_instruction` replaces the
commit-log stand-in only when an earlier review was found
(`criteria_inherited`). Round 1 reviewers get `prompt::recovery_review`:
a scoped diff since the reviewed commit for `VerifyRepair`, "review the whole
patch" with the reasons otherwise.
- The earlier run is only read: ownership of its worktree stays with
`handover`.
## A reviewer seat remembers who failed it across review rounds
`RunState::seat_history` (`run::SeatHistory`, `#[serde(default)]`, so
`run::SCHEMA` is not bumped) records per `review-N` seat the roster ids that
failed it (`failed`), the agent that last answered (`last_ok`) and the class of
the last failure (`last_fail`, `run::FailClass`). Only the review loop carries
it (`WaveCtx::carry_seats`; every other node passes `false`). Sessions stay
keyed by seat, and an agent change always takes a fresh `SeatState`.
- **Start of a round.** `pick_start_spec`: `last_ok` if still on the roster and
not failed, else the spec's own agent unless failed, else the next roster
agent that has not failed, else the spec's agent (the whole roster failed).
Ids no longer on the roster are ignored.
- **Two sets, on purpose.** `failed` is only a *priority*. The bound is the
per-round `tried` set in `ask_json_wave`, which starts empty every round, so
an agent that answered is never locked out and a seat can always hand over.
Persisting `tried` itself would shut a seat once everyone had been tried.
- **Handover inside a round** is `next_for_seat`: forward from the seat's
start, never wrapping, over ids neither tried this round nor failed earlier.
Only when that is exhausted does it *rescue* a carried failure, scanning the
whole roster in order - the one place the no-wrap rule is relaxed. Each id is
rescued at most once per round and rounds are bounded by `review_rounds`, so
it cannot loop. A failure is saved before the next agent is asked, so a
restart does not forget it. A repeated `Other` failure class still stops the
chain (`last_fail` seeds `prev`); a dropped stream that a nudge recovers is
never recorded as a failure.
- **A review is still fresh each round**: the full prompt for the new patch is
sent. Trade-off accepted: an agent with a transient failure is not used again
in this run's reviews while another agent answers, so a persistent failure
(quota, auth, prompt-shaped error) is not re-billed every round.
## Rate limits, and what a collapsed panel means
- **Machine failures are detected, not guessed.** Claude usage detection accepts
`is_error: true` with a `session limit` result, or the structured
`429` / `usage_limit_reached` pair. Codex requires a top-level `error` event
starting with the observed `You've hit your usage limit. Visit
https://chatgpt.com/settings/usage to purchase more credits` message **and** a
`turn.failed` event in the same invocation; `try again at ` supplies the reset
hint to the existing dated parser. agy's structured quota shapes remain
supported. Assistant text quoting errors is never evidence.
- **Authentication is a machine failure too.** Claude must report
`is_error: true`, `terminal_reason: "api_error"`, and a result starting with
`Failed to authenticate:` containing `OAuth session expired and could not be
refreshed`. Unknown errors, including unobserved Codex/agy authentication
shapes, remain ordinary failures. `Quota::cause` and `QuotaLoss::cause`
distinguish authentication from usage limits (serde defaults preserve older
records); losses also retain the agent id. Both use `AgentOutcome::Quota`,
so neither is immediately re-asked and both can hand over to another agent.
Authentication raises a notice keyed by agent id asking to re-authenticate.
A fixer chain ending in a usage limit or authentication failure uses its
caller's resource deferral path, including the independent landing fixer
chain: it records the final agent/cause and defers without handing off the
PR or spending a fix round. Partial edits are rescued to a local commit
under repository coordination before deferral; normal resume gates that
commit before publishing it. Resume retries its checks/comments; an explicit
merge-repair request remains pending after restoring partial fixer work.
This excludes best-effort graft, which records
the loss, restores its tree and proceeds to review and gate. The same applies
to missing-report continuations: gate and review fix rounds remain unspent
until recovery. Operator fixes rescue edits, release their worktree and save
an unreported outcome before deferring; retry explicitly with `magi fix`
after recovery (`--allow-stale` if the saved work moved the branch).
- **A node with no available agents stops resumably.** When every final seat
of an advisor, implementation or shared structured wave ends on quota/auth,
record a `ResourceBlock` and stop `Blocked` before completing the node.
Pending candidates stay pending; successful earlier work stays intact.
Settlement and orphan recovery refund the attempt. Usage stops retain the
existing cooldown policy (a pinned implementer remains held); authentication
stops use a machine `Held` reason
and require re-authentication followed by explicit release/resume, never a
cooldown-triggered second empty attempt. Historical losses alone must not
turn a later ordinary failure into a refundable machine outage.
Sequential deliberation aggregates all turns in a round before declaring
an outage; one unavailable seat does not block healthy peers. Interrupted
rounds remain pending, while completed rounds survive resumption.
- **A verdict needs a quorum.** `tally()` counts a judge as present unless a
`QuotaLoss` names that seat; a strict majority (`judges/2 + 1`) is required,
or the run becomes `Stalled`. `Stalled` is a terminal-but-suspect status: it
must never look like `Ready` in the report or the TUI (which is why
`Filter::Attention` and `status_style` carry it), and the graph's
fold/review/gate/merge stop at the tally so the run stays resumable.
- **A stalled run must stay stalled across `--resume` until its quota comes
back.** `execute()` short-circuits at the top when the loaded status is
already `Stalled` — otherwise `deliberate()`/`vote()` clobber it back to
`Voting` and the run resumes into a tidy `Ready`. But the early return first
gives the run one chance to repair itself: `recover_stall()` re-asks exactly
the seats recorded in `RunState::quota` for the judge/vote nodes (never a
healthy seat), and if the re-tally restores the quorum the run picks up and
finishes; for a seat that ranks again its `QuotaLoss` is dropped so `tally`
counts it present. Successful validated judge/vote answers also clear the
seat's previous losses on the normal path after an all-seat `Blocked` wave;
the first healthy resume must restore quorum without another stall.
If the quota is still out, the seat fails again, the run
stays `Stalled` and the marker is persisted (the normal end-of-execute save
sits below the `Stalled` return), so it stays resumable for a later retry.
## Known follow-ups from the takeover review (PR #322)
- **R3-1-1 (race).** `Runner::execute_graph` loads `released_to`, then later
saves the whole in-memory `RunState`; a takeover that writes the release mark
in between is overwritten by the resume's `driver_pid` save, so the takeover
can delete a clean worktree under a run that just started driving. Intended
fix: compare-and-set on `released_to`, or a re-read under a lock.
- **R3-1-3.** `Released::restore` runs an unconditional `git branch -f` unless
the current tip equals the saved tip, so a branch a third party moved is
overwritten. `Released` cannot tell a legitimate post-sync tip from a foreign
one; intended fix: refuse (or lease-check) when the branch moved to a third
value.
- A refused handover keeps `Task::review_branch` (`Task::hold_for_handover`),
and `Task::release` keeps it only for a machine hold; releasing without
cleaning the old worktree re-holds the task without spending an attempt.
## A run is interrupted at a node boundary, never mid-node
`graph::Pause` is checked between nodes in `execute`, and that is the only
place it may be checked. The cheapness of a park is entirely a property of the
boundary: every node saves the run's state before the next one starts, and
every node skips what is already on disk — `prep` returns early once
candidates exist, `implement` asks only the seats with nothing recorded,
`judge` returns early once judgements exist. A park therefore resumes into
exactly the node it stopped before and throws nothing away. A check *inside* a
node would abandon the wave in flight, which for an implement wave is an hour
of paid calls.
Two rules follow, and neither is optional:
- **A parked run is not a failed one.** `Verdict::parked` refunds the attempt.
It is an explicit owner or scheduling/resource checkpoint request, not an
agent failure. Worker-based upgrades do not request a park or alter attempts.
- **An unfinished run is resumed, never re-competed.** `attempt` looks for a
non-terminal run of the task and calls `Runner::resume` on it. When it did
not, run 01c2 was blocked and the loop immediately started 3cbf on the same
task, paying three implementers to redo two and a half hours of work that
was already on a branch.
## Passes: why a run stopped is recorded when it happens
A resume is another **pass** over the same run, not a new run, and a refunded
attempt is not a failed one. The cause is written down at the moment it
occurs, never reconstructed from `upgrade.json`, `web.log` or `park` event
prose (the first is overwritten by the next upgrade, the rest cannot be
annotated after a resume).
- **Two records, one each side.** `RunState::passes` (`run::RunPass`, appended
by `RunState::begin_pass` in `Runner::claim_driver`, closed by
`end_pass_parked` in `park_here` and the two "waiting for the owner" parks)
says why the pass stopped (`run::ParkCause`: `Upgrade{from, to}`,
`Operator`, `Interrupt`, `Question`, `Unspecified`). `Task::passes`
(`queue::TaskPass`, written by `daemon::settle_and_diagnose`) says what the
settle did to the budget; the refund is read off `attempts` before and after,
never inferred from the status. `queue::SCHEMA` 15; `run::SCHEMA` is
unchanged (additive, `#[serde(default)]`).
- **The cause comes from the requester.** `Stop::park` takes a `ParkCause`;
`web::park_for_upgrade` passes the running version and the release it is
installing (`to` is `None` when unknown, shown as "from X"). `Pause` keeps
the first cause it is given.
- **Unknown stays unknown.** A pass the next process finds still open is closed
as `PassEnd::Unrecorded` (a crash, a kill): it is never shown as an upgrade.
A run from before passes existed has none for its earlier entries;
`web::task_history` aligns records to the tail of `Task::runs` and leaves
the rest as "cause not recorded, refund unknown".
- The Attempts panel counts three different things: entries (passes), distinct
runs, and attempts consumed (`Task::attempts`). Do not merge them.
## Rebase conflicts: the seat resolves contents, the launcher stages
`rebase::launcher_stage` runs after every fixer round and at the head of the
`rebase_with_fixer` loop, before the budget check. A sandboxed seat may be
unable to write Git metadata (the index lock), so it only edits the conflicted
paths. Under the repository coordination lease the launcher re-validates the
unmerged set against the round's recorded paths (`RebaseFixRecord::paths`,
stop point `stop` = `REBASE_HEAD`), refuses remaining markers and any edit or
index change outside those paths, stages exactly them with literal pathspecs
and runs `git rebase --continue` (recording exec and todo untouched). A
denied or failed Git write is a `ResourceBlocked` stop (`infra` on the record):
no round is spent, nothing is aborted, scratch and resolved files are kept and
a resume repeats the same step. A record from before `stop` existed matches
only when every recorded round saw the same conflict set.
## Execution-boundary ownership waits
`pr_head::owner_lock_wait` is the shared asynchronous acquisition path for
driver claim/finalization and scheduler resume preflight. Use the saved run's
`graph.timeout_resource_wait`, then re-read ownership under the acquired lock;
never turn a short maintenance transaction into an immediate task hold.
Finalization retains its execution lease throughout the wait. Only lock
contention is retried; permission and other I/O errors still fail closed.
The synchronous `owner_lock` remains non-blocking for administrative operations
and drop cleanup.
## Verification runs as a standalone caller
`graph::run_commands` removes only `worker::INVOCATION_ENV` from verification
children (e2e, pre-gate and gate, including landing and gate-repair rechecks).
Unit and integration subprocess isolation uses that same list. Inherited worker
identity can resolve against a fixture's unrelated home, and a pinned worker
generation suppresses updater checks or selects an old helper executable.
Keep `MAGI_HOME`, seat metadata, process containment, toolchain/cache settings
and authentication available; fixture storage belongs to each test. Never
change the driver's environment or normal worker/agent launch semantics here.
## New run and conversation identities are reserved before use
`RunState::new` only builds an unreserved value. Every production creation path
must call `reserve` (or `reserve_under`) before exposing its id, deriving branches
or worktree paths, or linking it to a task. Resumes load the existing record and
never reserve again. Reservation also excludes suffixes held by run history,
because candidate branches and worktrees use the four-character short id.
New conversations go through `Talks::create`; `Talks::put` is the update path.
Both stores share `src/id_reserve.rs` with queue filing for bounded retries and
injected candidate sources. Unknown I/O results are errors, never free ids.
## Reviews of foreign worktrees
A clean hand-written checkout remains operator-owned. Review-only runs record
`RunState::foreign_checkout` and edit a `magi/<run>/review` shadow branch in their
own worktree. Never run setup, reset, clean, rescue commits or fold against the
foreign path. Before filing a review, and again at execution, reject dirty or
locked foreign holders. Completion and every publication path must pass through
`foreign_checkout::write_back`: revalidate the canonical Git directory, attached
branch, clean status (including untracked files) and saved head, then fast-forward
only. A moved checkout or rewritten review history blocks delivery and retains
the isolated fixes; never force-move the operator's branch to recover.
Remote tips may seed the shadow branch only after a successful branch fetch;
failed fetches retain the saved local head even if a tracking ref survives.
Automatic base synchronization merges into the shadow branch instead of rebasing,
so the saved foreign head remains an ancestor for fast-forward delivery. A merge
conflict is aborted and blocks the run with both checkouts retained.
Landing synchronization retains the existing rebase/fixer path, then joins the
saved pre-sync head with an `ours` merge before gating or publication. This keeps
the repaired tree and fast-forward delivery ancestry. `land_rebase_from` remains
the recovery checkpoint until restoration and that ancestry join complete;
resumes must perform the same join before clearing it.
## A red `verify.e2e` is rerun once on the same commit before it is believed
`graph::run_e2e_with_retry` is the one implementation, called by every place
`verify.e2e` decides something: the review loop's per-round leg, the deferred
catch-up in `stop_reviewing`, `verify_current_head` (before and after the gate,
after a base sync, at publication) and `check_gate_repair_e2e`. `verify.gate`
is untouched. Measured on this repository over ten days: 65 of 113 e2e runs
failed, and 46 of 74 failure outputs named only tests that failed in three or
more distinct runs, almost always while other runs shared the machine.
- **What reruns.** `rerunnable_failure`: every red command ran, exited non-zero
other than 126 / 127, is not `build_failed`, and nothing in the list is
`resource_blocked`. A timeout (`code: None`), a spawn failure and a resource
block are never rerun. Only the failed commands run again; commands that
passed keep their first outcome.
- **Bounded.** One extra attempt per failed verification, a plain `if`, never a
loop. The build/link retry stays and runs first, so one decision is run at
most three times (`a_verification_never_runs_more_than_three_times`). The
rerun is made inside the caller's `with_cache_lease`, so the lease is held
across both attempts, and `run_commands` gives it its own full
`timeout_verify`. It spends no review round, fix round, task attempt or
repair budget: nothing in `ReviewRound`, `FixRecord` or `Task` counts it.
- **Second run passes: a flake.** The head is verified, and the first failure is
recorded in `RunState::verify_flakes` (`run::VerifyFlake`, `#[serde(default)]`,
`run::SCHEMA` unchanged) with the round, context, commit, command, excerpt,
fingerprint and the task. It shows as a `verify` event, as "e2e green on
rerun only (flake)" on the round in `magi show` / the web run page
(`E2eView::flaked`, `app.js` `renderRound`) and in a "flaky verification"
section. `ReviewRound::e2e_status()` still says `Passed`: the round record
itself is not changed, the ledger is the record, matched to a round by
`VerifyFlake::round`.
- **Second run fails: verification stays red, with structured attempt comparison.**
`src/verify_evidence.rs` extracts confirmed, count-reconciled terminal test
failures from raw output before `summarize_verify` reduces it, separating
intermediate `TRY` failures, `FLAKY` passes, cancellations, and captured test
stdout/stderr from final verdicts. `CommandOutcome` keeps additive
`artifact` (recorded whenever an artifact write succeeds, compressed or not),
`failure_evidence`, and `rerun_comparison` (`RerunComparison`: target commit,
both attempts' exit codes, durations, bounded excerpts, artifact refs,
extractions, intermediate notes, and a `Matching` / `Distinct` / `Unknown`
verdict). Only identical confirmed non-empty terminal failure sets report a
reproduced match; distinct sets list attempt-1-only, attempt-2-only, and
common failures; anything incomplete, unconfirmed, or legacy (`FAILED_TWICE`)
reports an unknown comparison. Events, `ReviewRound::verification_summary`,
fixer/recovery prompts, CLI/web run reports (including `head_e2e` and
`gate_repair_e2e`), stop reasons, and automatic task chat reports all share
this saved record and reuse it on unchanged stops without re-running e2e or
resurfacing resolved earlier failures. `flake::signature` is never used for
terminal-failure comparison.
- **A flake is filed once, by `src/flake.rs`.** A failure is identified without
knowing the test framework: the lines of the saved excerpt that mention a
failure word (`FAILURE_WORDS`), minus `test result: ok` lines, with numbers,
long hex words and `tmp...` names replaced, sorted and de-duplicated, hashed
with the repository (`fingerprint`). The task id is derived from that hash,
never from the run, and written with `Queue::create_new`, so concurrent runs
still leave one task. A task that is not `Done` covers every later
occurrence (the run only records the id); a `Done` task does not, and the
next generation id (`flake-r<N>-<key>`) is filed. `Source::Agent` with node
`flake`, solo, `dupes::check` deliberately not run. Filing is best effort:
a failure is `VerifyFlake::filing_error` plus an event, never a failed run.
The signature depends on the excerpt `summarize_verify` kept, so a very
different excerpt of the same failure can file a second task; accepted.
- **The switch** is `[graph] rerun_failed_e2e` (default true). Off, the
function takes the exact path it took before (no rerun, no new events);
`with_the_switch_off_the_first_result_decides_as_before` pins the events.
- Tests: `tests/graph_e2e_rerun.rs` (real shell commands that fail once, fail
twice, or fail to build; counters live outside the worktree) and the unit
tests in `src/flake.rs`.
## An implementation turn that never started is retried once
`graph::Runner::retry_unstarted` runs in `implement` after `resume_undelivered`
and before `resume_seat_handovers`. It covers a clean exit-0 reply from a seat
that did nothing: in three days of logs, 14 of 38 `sol` implementation turns
answered "Implementation incomplete" as their first response, in 6 to 12
seconds, and were recorded as ordinary empty candidates.
- **Evidence, never wording** (`graph::ended_unstarted`): a usable reply,
`AgentOutput::tool_calls == Some(0)`, no command evidence, `HEAD` equal to the
one recorded before the turn and a clean tree. The comparison is with the
seat's own starting point, not the run's base, so an untouched inherited patch
counts as unstarted. A dirty tree, a moved `HEAD` or an unreadable repository
never authorizes a retry, and neither does a reply whose `NO CHANGE NEEDED`
claim verifies.
- **`tool_calls` is `None` for unknown, never 0.** Only the omp arm of
`agent::extract_answer` fills it (`tool_execution_start` events and
`toolCall` parts), so other CLIs are never retried by this. `commands` stays
empty for omp and says nothing about tool use.
- **A `command` agent that relays an omp stream is read as omp**
(`agent::relays_omp_stream`: the first line is omp's session line). That is
how `tests/graph_unstarted_retry.rs` drives this path.
- **Once per candidate and run.** `RunState::unstarted_retries`
(`#[serde(default)]`, `run::SCHEMA` unchanged) is saved before the agent is
asked. The seat's conversation is resumed with `prompt::resume_unstarted`
(the whole prompt again when there is no session), on the full
`timeout_implement`: nothing was done yet, so it is the job itself. A
`ResourceBlocked` retry spawned nothing and gives the retry back.
- **Exhausted is an ordinary failure** with `graph::UNSTARTED_TWICE` as its
reason, so the existing handover may give the seat to the next roster agent
and a pinned implementer holds as for any other failure. A quota on the retry
stays a quota.