magi-cli 0.271.1

Blind multi-agent implementation competition: N agents implement, M judges rank blind, deliberate, vote privately, winner survives double review + E2E gate
Documentation
# Queue, daemon, workers and upgrades

Conventions for this area of magi. `AGENTS.md` indexes these files: read this
one before changing the code it covers.

## The queue: data with pure transitions, I/O in one place

`src/queue.rs` splits `Task` (data plus *pure* state changes) from `Queue`
(every filesystem call, constructed with its root). That is not decoration:

- `Queue::at(root)` is why the queue tests run in parallel against temp
  directories with no process-global state. The first version used
  `run::set_home`, whose `OnceLock` means **the first call in the process
  wins** — three tests silently shared one home and clobbered each other. If
  you find yourself reaching for `set_home` in a unit test, parameterise the
  root instead.
- `Task::fail` decides whether an attempt was the last one, with no disk in
  the way, so the retry policy is asserted directly.

**A quota stall or recorded machine resource stop is refunded.** `Task::stall`
decrements `attempts`. A rate limit or authentication outage is a property of
the machine, not of the task, and a quota window closing overnight must not
leave a backlog of `held` tasks that were never actually judged. Do not "simplify" this into `fail`.

But the refund is keyed on `Verdict::quota_hit`, not on the `Stalled` status,
and that distinction is load-bearing. A quorum can collapse for a reason that
has nothing to do with quota: run e633 stalled with `quota: []` because two
judges answered with the wrong JSON shape, twice each, nudge included. That is
ordinary flakiness, it can recur every time, and refunding it removes the
bound from the retry loop — each attempt paying for another hour-long
implement wave before it reaches the same judges. `max_attempts` exists so
that cannot happen. Refund the machine's failures; charge the task for its
own.

## Web and scheduler restart independently of execution workers

`src/worker.rs` owns durable detached reservations, execution leases and immutable
SHA-256 executable generations. `magi web` serves HTTP; `magi serve` dispatches;
task workers run the existing attempt and settlement. Updating replaces web and
scheduler, never parks or cancels paid work. Conversation execution and publication
fencing live in `src/chat_worker.rs`, independently of the legacy consultation
protocol in `src/consult.rs`. Keep generation ordering, recorded-send restoration
and TurnLease ownership in that chat-native module when removing consultation
code. A scheduler restart reconstructs ordinary/urgent/decision-only capacity
from reservations. Standalone CLI workers
remain outside those lanes and global queue-worker park requests.

- **The worker owns the claim.** Keep task claims and run execution leases until
  settlement. A missing scheduler heartbeat is not a dead worker. Unknown worker
  storage is an error, never an empty active set or permission to reclaim.
  `daemon::resume_owner_lock` waits asynchronously for transient ownership updates
  within the saved `timeout_resource_wait` before an attempt starts, then re-reads
  ownership under the lock; maintenance contention must not hold a resumable task.
  A worker must exclude only its own verified reservation from public-owner
  preflight liveness; that reservation still protects cleanup, and the prior
  driver's execution lease/process evidence must still be checked.
  Sandboxed liveness checks use `worker::observe_active` with read-only lease
  handles; only authorized writers use `worker::active` to reconcile and retire
  records. Never widen a chat's write scope merely to observe worker ownership.
- **Pin helpers too.** Worker PATH and `MAGI_WORKER_EXE` name its retained
  executable. `MAGI_WORKER_ID` identifies the reservation; `Job.sequence` orders
  publications under the store lock. Pinned helpers never self-update.
  The hidden `__worker` spelling appears in `main.rs` and
  `worker::detached_command`; change both together. Do not use the ordinary task
  word `worker` as this internal command: the typo guard would reject real prose.
- **Retry a busy generation at spawn.** On Unix a concurrent fork can inherit
  the copy's writable descriptor until exec or exit, even after pinning closes
  its own copy. Generation spawns go through `worker::spawn_generation`, which
  retries only `ExecutableFileBusy` with a short bounded backoff.
- **Finite services, independent deputies.** Waiter/release/maintenance work
  outlives a scheduler in finite jobs. Each deputy question has its own job;
  global capacity counts both reservations and fresh question leases. An active
  service key is retained across config changes, not re-spawned with a new payload.
- **Admission is short.** Web handover closes new admission and waits only for
  persistence-to-reservation transactions, never Chat or graph execution.
  A per-talk publication lease covers draft writes through startup acknowledgement;
  a worker uses it for generation selection and draft promotion, then releases it
  before invoking the CLI. UI TurnLease acquisition remains nonblocking.
- **Never replay uncertain starts.** Only `worker::not_started` proof permits
  restoring a recorded operator send to a manual draft. Preserve attachments,
  reply metadata, later drafts and task posts. A posted task turn is not proof
  that the chat answered an operator send.
- **Release, then spawn.** Remember the installed executable path before update,
  replace the scheduler, release the listener, then start the successor web.
  Answer 202 before process exit. A live legacy embedded scheduler requires one
  finish/park migration; a stale heartbeat alone does not permit overlap.
- **Evidence stays local.** Active jobs and logs live in `workers/jobs`, terminal
  records retire lazily to `workers/results` after execution handles close
  (Windows cannot rename live directories). Keep the latest 256 terminal records;
  generation executables remain retained. Health projects public metadata only,
  never payload/configuration or output.

Real restart tests kill one parent PID, not its descendant tree. They use private
host homes as well as `MAGI_HOME` so default worktree measurement and housekeeping
never visit the operator's directories.

## Autonomy is bounded, and the bound is the point

`src/daemon.rs` runs one competition at a time — no `--jobs`. The graph is
already parallel inside (candidates times judges), and the scarce resource is
the agent CLIs' quota, not local CPU.

- Every attempt is counted, and a task that burns its attempts is `held` for a
  human rather than retried until the money runs out.
- A setup error that never minted a run still spends an attempt. Otherwise a
  task naming a nonexistent repository is retried at every poll, forever.
- A crash mid-run leaves the task `Running` with its run id recorded. That is
  deliberate legibility: the operator can see what was in flight. Do not add a
  startup sweep that "cleans" those into `Queued` without also proving the run
  is dead.
- Driver ownership lasts for one graph execution, including resource-block and
  park postprocessing. A pass-bound OS execution lease and drop guard release it
  on return, error, cancellation or unwind; normal completion saves final state
  and cleared ownership together. Cleanup checks the pass identity so it cannot
  clear a successor. Save failure or process kill leaves lease-based recovery.
- Before publishing a new daemon generation, startup reconciles proven-stopped
  driver records once under the ownership lock, retaining status and resume
  checkpoints. Prior daemon claims with a proven-lost matching process identity
  do not survive restart. Unknown identities and held leases stay protected;
  recovered resumable runs are not failed by abandoned-seat cleanup.
- Ctrl-C does not abandon a run in flight. Killing the graph mid-node leaves
  worktrees, branches and agent sessions behind, and throws away agent calls
  already paid for.

## Duplicate-work claims are gathered from several places

`src/dupes.rs` refuses (`--force` overrides) a `magi task add`, `magi run` or
`magi review`, and a web edit that changes a task's instruction, when it names
a branch, a commit SHA or a pull request that unfinished work already owns
*and* a one-shot judge says it is duplicate work; a
judge that cannot answer lets it through (fail-open, stderr note + warn).
`[roles] dupes_judge` accepts a string or fallback chain; unset inherits `chatter`.
Only concrete identifiers match, never text similarity. What counts as
"owned" is spread over `Task::review_branch`, `Task::runs`, and each run's
`candidates[].branch` / `pr_head` / `pr` / `base_commit` in `run.json`, none of
which a compiler ties together, so a new field that names a branch or PR belongs in
`dupes::task_claims` / `run_claims`. `run.json` is read through a tolerant
view, not `RunState::load`, so a schema bump cannot silently drop claims. The
daemon's retries, requeues, review requests and resumes never go through this
check: they would collide with themselves. A PR number the text names that no
record explains is asked of the forge (`gh pr view`, 5 s cap, any failure is
"unknown" and ignored); tests inject that lookup via `dupes::check_with`.

A terminal run with `pr_taken_over_by` naming a readable successor drops its
PR and public-head claims, like `released_to`; the successor owns them.
`task_claims` keeps those claims within the owning task rather than attributing
the same PR to each attempt.

## Task attachments live beside the task file, outside the worktree

`magi task add|edit --attach <PATH>` copies a file into `<queue>/<id>.attachments/`
(`Queue::attach`), never a `*.json`, so `Queue::list` and `revision` do not see
it; `Queue::remove` deletes the directory. Names must pass
`ask::valid_asset_name` and are numbered, never overwritten. `queue::SCHEMA` is
bumped to 7 for `Task::attachments` (the existing convention: schema 6 was a
field-only bump too); `run::SCHEMA` is not, since `RunState::attachments` is
additive and `migrate_schema` would otherwise need another arm. The daemon
refreshes `RunState::attachments` from the task on every start and resume, and
the implementer prompt lists the absolute paths under `# Attachments`. `task
done` does not delete them.

## Every run belongs to a task

`magi run` / `magi review` file a task first (`direct::file`), then either hand
it to a live scheduler as `urgent` or reserve a standalone task worker while
holding the filing claim. `direct::follow` follows live workers even while the
scheduler is being replaced; it never takes the work over. Workers reuse the
daemon's existing attempt and settlement, so accounting has one implementation.
CLI choices live in `Task::overrides`; an explicit review fails on a missing
branch rather than competing. Standalone failures hold instead of auto-retrying.
`--dry-run` never dispatches. CLI, Web and owner-choice resumes share atomic
`direct::claim_resume_owner`, a forced run pin and the same task-worker handoff;
an ownerless legacy run is filed under its claim before it becomes runnable.

## A stuck handover must be diagnosable from files alone

`<home>/upgrade.log` records replacement, scheduler restart, admission drain,
listener release, successor PID/error and runtime shutdown through
`updater::log_step`. It rotates at `LOG_MAX_BYTES` (256 KiB).
`<home>/web.log` contains successor stdout/stderr; supervisor redirection alone
only follows the first generation's descriptors.

`upgrade.json` and the separate `upgrade.note.json` carry monotonic progress and
watchdog evidence. The watchdog must never rewrite the progress record.
Legacy `parking`, `parked_run` and `parked_talks` fields remain readable as history,
not instructions to pause independent workers. New handovers report restarting
and wait only for the short admission boundary.

Worker startup, panic and execution output goes to the reservation's `worker.log`
from before exec. Terminal results are saved before lazy archival, so a Windows
sharing violation cannot turn a completed execution into scheduler failure.
An unavailable result or execution lease never authorizes an automatic replay.


## Upgrade resume scheduling

Only tasks parked by `ParkCause::Upgrade` retain their place ahead of ordinary
runnable work, including newer tasks with higher ordinary priority. The latest
settled pass must belong to the current run and the task must still be parked
without a fresh-start request. `queue::dispatch_order` orders these resumes by
the persisted pass start time, then task id, before ordinary priority/id order.
Legacy pass records without a start time use settlement time and id as an
approximation. Parking refunds the attempt; dispatch resumes the existing run
and checkpoint rather than creating a competition. Startup parks with no run
or recorded upgrade pass do not receive this ordering.

This is candidate ordering only. Explicit interrupts, urgent slots, concurrency,
claims, coordination, approval waits, cooldowns and resource gates retain their
existing checks. A resume that cannot run must not stop the daemon from trying
unrelated eligible candidates. Other park causes receive no promotion.

## Automatic web upgrades

`[update] auto_restart` is opt-in and uses the manual upgrade gate, progress,
installer and successor handover in `src/web.rs`. Keep those paths shared.
Automatic requests trigger without waiting for idle task, chat, or service
workers and never park active runs. The handover drains only short admission
transactions before restarting the detached scheduler and web listener; active
workers and pinned helpers continue uninterrupted on their original executable
generation while newly dispatched work uses the new generation (old and new
generations may temporarily coexist). Legacy embedded schedulers are still
refused. Failed-tag suppression is process-local, not run state; do not persist
it or change `run::SCHEMA` for update bookkeeping.

## Task repository reassignment

`task_reassign::reassign` is the shared CLI/chat/Web transaction. Assignment
history length is its monotonic generation, and each boundary excludes all
previous runs from execution, including when moving back to the original repo.
Use `Task::execution_runs` for execution/recovery candidates and
`Task::assignment_accepts` at admission. Keep `Task::runs` intact for history,
publication ownership and duplicate-work checks; those checks must use each
run's original repository. Never adopt historical branches across assignments.
Question actions must check `Task::stale_question`, including conductor and
maintenance questions. Chat reassignment requires its authenticated bridge and
must never fall back to direct store writes. Reassignment holds task claims,
run owner/execution leases and output reservations until its atomic task save;
new execution discovers destination config and takes destination coordination.

Targeted `Runner::fix_selected` operations hold the same `FixClaim` as repository
reassignment, including preflight and follow-up review. Recheck the canonical
full run ID inside that claim before awaiting or editing. New runs snapshot
`task_assignment` before startup: their public heads use that durable generation,
not the task's later assignment. Legacy generation zero keeps its original head.
Publication takeover and explicit PR recovery must not cross assignment generations.