magi-cli 0.274.0

Blind multi-agent implementation competition: N agents implement, M judges rank blind, deliberate, vote privately, winner survives double review + E2E gate
Documentation
# Disk, build cache and retention

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

## The shared build cache is only shared if both sides name the same path

`magi.toml` renders `CARGO_TARGET_DIR` from `{{ vars.cache }}`, whose default
is `/tmp`. The verification commands run under a POSIX shell, which resolves
`/tmp` to its own temp directory; magi measures the string literally. On
Windows those are two different places, so the janitor pruned and the health
view sized a path that never existed while 17 GB of build output sat in the
shell's `/tmp`. `magi cache show` now says so instead of printing `0 bytes`.

**Set `MAGI_CACHE` to a real absolute path on any machine whose shell rewrites
`/tmp`** (this one: `C:/Users/yukimemi/AppData/Local/Temp`, set as a user
environment variable). Forward slashes, so the same string works in the shell
command and in `std::fs`.

## The disk is a resource the graph can exhaust

A run costs a candidate worktree plus a reviewer worktree per reviewer, each
with its own multi-GB `target/`. Two failures came out of that, both silent:

- **A save that runs out of disk leaves `<home>/runs/<id>/run.json.tmp` and
  nothing else.** `run::list_ids` therefore keys on the directory's *name*
  ([`run::is_run_id`]), never on a readable `run.json`: filtering on the state
  file made run `88c0` invisible to `magi list`, to `runs_unreadable`, and to
  every phone route, so nothing could report it and nothing could clear it.
- **An agent that cannot write files reports it in prose and nowhere else.**
  Run `4043`'s implementer said the disk had 8.9 MB free; the run was recorded
  as "blocked with one finding open". `daemon::disk_gate` holds a task before
  minting a run instead, which spends no attempt and leaves it in the list.
  Typed disk-capacity holds are resource waits: triage and the existing daemon
  maintenance service probe admission at most once per minute per task, including
  while other work runs. Pressure and measurement failure remain held without
  questions. Recovery preserves attempts, approvals and retained execution identity;
  it never authorizes a replacement competition. Legacy migration requires the
  exact localized gate format and machine provenance. Only untouched automatic
  disk triage questions may be superseded; owner replies, discussion and unrelated
  approval gates still need owner resolution. Queue transitions compare the complete
  held snapshot under the task write lock, so a concurrent owner hold wins.

Housekeeping is best-effort by construction: one run's fold failure is a
`tracing::warn` and the pass continues (`clean::fold_due`). A `?` there stopped
automatic folding permanently at the first run git refused to let go of.

**A different schema number is not "unreadable", and conflating the two once
stopped the janitor fleet-wide.** `clean::fold_due` used to require a full
`RunState` to pass the same schema check `RunState::load` enforces for
`--resume`, and treated any mismatch as unreadable - silently skipped, not
counted, not logged. The moment magi's own `run::SCHEMA` bumped, every run
still on disk failed that check at once: on one operator's machine this was
90 of 93 runs, folding 0 per pass, for months, with nothing anywhere saying
so (`Housekeeping::unreadable` was defined but never incremented). The fix
narrows "unreadable" to what `RunState::load` cannot do at all - `run.json`
failing to parse - because folding only ever reads worktree paths, branch
names and a tally winner off the struct, and every schema bump so far has
only added a field or a variant, never repurposed one; an old record's values
are exactly as good for that purpose as a current one's. `RunState::load`
itself keeps the strict check, because *its* callers (`--resume`, the review
loop, the tally) do recompute against a field's current meaning and must not
guess at a value an older schema never had a chance to mean correctly.

**Finished runs are folded on a busy machine too (`fold` service).** Idle
housekeeping was the only caller of `clean::fold_due`, and it is admitted only
with no busy worker and no runnable task (`daemon::housekeeping_eligible`), so a
queue that is never empty folded nothing (issue 1275). The idle gate came from
the first janitor's "folding worktrees and pruning a cache mid-build would race
the very compile"; that is about the shared-cache prune, `fold_orphaned_worktrees`
and `worktree_prune`, which stay idle-only. Folding a finished run is protected
per run (owner lock, execution lease, output leases, repository coordination in
`graph::fold_run_when`, which the automatic callers ask for once and give way on, see
"A handover in flight"; a live claim in `clean::eligibility`) and is already done
beside live runs by `magi fold` and the phone's fold route, so
`daemon::fold_turn_eligible` admits `service:daemon-fold` exactly where
housekeeping is not (never beside a housekeeping worker).

- **A fold needs the record it locked.** `clean::fold_one` / `clean::eligibility`
  are shared with `fold_due`; never fork them. `graph::fold_run*` reloads the run
  record *after* it holds the owner lock and the execution lease and acts on that
  record only - deletion decisions, `released_branches`, what is saved. There is
  **no fallback to the caller's earlier read**: the reload must succeed and carry
  the locked id, or the fold refuses (`FoldRefusal::RecordGone` for a missing or
  foreign record, `FoldRefusal::Unreadable` for a record that parses no more) and
  **touches nothing**: the lock files are never unlinked (`pr_head::owner_lock`: an
  unlinked lock file lets the next caller lock another inode) and a run directory
  that is not there is never created to lock it - a missing directory at the lock
  or the reload is `record gone`. A record whose embedded id is not its directory's
  name is `unreadable` at the first read for the automatic callers
  (`clean::read_meta` / `read_state`) and an error for the explicit ones
  (`RunState::ensure_directory` in `magi fold` and the phone routes), nothing
  touched. Tests that fold a synthetic record save it first
  (and save every arrangement they make to it, and assert the refusal the rule
  produces - `FoldRefusal` or its message - never a bare `is_err()`, which `record
  gone` would also satisfy: a fold decides on the record on
  disk, so a change made only to the in-memory copy is not seen). The loader is the
  caller's: `fold_run_when` (idle pass, busy turn, the janitor's fold after it
  recorded an external merge) uses `RunState::load_tolerant_under` (no schema check,
  like `fold_due`); `fold_run` and `fold_run_overriding_recovery_retention`
  (`magi fold`, the phone route) use the migrating `RunState::load_under`, followed
  by the same preservation checks on that fresh record. The override keeps its
  liveness assessment *before* the fold holds the execution lease (a held lease
  reads as a live driver), and that record is identity-checked too; the record read
  once both locks are held is checked again. The automatic callers re-ask
  `eligibility` on the fresh record (the external-merge fold re-validates only the
  confirmed-merge conditions - no grace, the merge is the news); a run no longer
  eligible is left alone. A handover (`handover::release`) records `released_to` /
  `released_branches` under the owner lock and keeps the branch; a fold on the
  earlier read would delete the handed-over branch and save the stale record over
  the handover.
- **A handover in flight is not folded by an automatic caller.**
  `clean::handover_settled`: a record naming a successor (`released_to`) whose
  startup is still running (`startup` not complete, no failure recorded - the
  rollback of a failed start runs *before* the failure is saved), whose driver is
  live, or whose record cannot be read is `live`; a missing successor record, a
  failed or completed startup and a stopped driver settle it. A startup killed
  mid-way leaves the same marker as one in progress and so keeps its predecessor
  out of automatic folding until an operator settles that run (the safe
  direction). **Lock order with a handover.** A handover holds repository
  coordination and then asks for the predecessor's owner lock (`handover::release`,
  `Released::restore`); an automatic fold holds the owner lock and execution lease
  and, last, asks for coordination - and `released_to`, which `handover_settled`
  reads, is only recorded after the handover has the owner lock, so before it the
  two orders meet. The automatic fold therefore never *waits* for coordination while
  it holds the owner lock: `graph::fold_run_when` asks once
  (`repo_lock::WaitPolicy::immediate`) and, when it is busy, releases everything,
  changes and saves nothing and is `live`. The handover side retries the owner lock
  for up to two seconds (`handover::owner_lock_retrying`: 10 ms doubling to 250 ms,
  the last pause clipped to the remaining time) in `release` and in the rollback, so
  a fold that holds the lock only long enough to reload and refuse neither fails the
  successor's startup (charged to the task as an attempt) nor makes a rollback
  abandon; a lock held longer still fails the handover / gives up the rollback.
  `magi fold` and the phone route keep waiting for coordination (`timeout_resource_wait`).
- **Everything that writes the record takes the same two locks.** Deleting a run
  (`magi run rm`, the phone's delete button) is `clean::delete_run`: owner lock and
  execution lease without waiting (a held lock is `clean::DeleteRefused`, "try again
  later"), the record read under them, `ensure_can_delete` judged on it, then the
  directory renamed to a tombstone under `<home>/deleted-runs/` (outside `runs/`,
  which nothing scans) and removed there while both guards are held, so its lock
  files and `run.json` disappear together; where a directory with open files cannot
  be renamed (Windows), `run.json` is removed first. The wholesale removal of an
  unreadable run (`clean::fold_unreadable`) leaves through the same helper once it
  holds both locks. A deletion killed between the rename and the removal leaves the
  directory in `deleted-runs/`; `clean::sweep_graveyard` removes it before the next
  deletion and in idle housekeeping (nothing else reads it). So a record cannot
  vanish under
  a fold, and its four-character worktree suffix cannot be reserved again while the
  fold deletes that suffix's directories. The abandoned-seat
  cleanup of `magi fold` / the phone (`clean::clear_abandoned_active`) writes under
  the locks too, from a fresh read, and answers `false` for a held lock or a missing
  record; saving the caller's copy after the fold released its locks erased a
  handover.
- **Typed refusals.** `graph::FoldRefusal` (`Live`, `Resumable`, `WithinGrace`,
  `Retained`, `ProofIncomplete`, `RecordGone`, `Unreadable`) travels in the
  `anyhow::Error`; `clean` maps it to the receipt without changing what is deleted.
  A `Live` refusal is *added to* the error as context (`graph::live_or`), never
  substituted for it: callers match the error underneath
  (`repo_lock::ResourceBlocked` for a coordination wait) and both downcasts work.
  `Live` is **only contention**: a lock held by somebody (would-block, Windows
  lock violation, `retention::OutputsInUse`, repository coordination). Any other OS
  error from a lock call (`ENOLCK`, `EINTR`, a permission error) is `failed` with its
  text, including the Cargo build locks inside the source proof
  (`retention::LockCallFailed`, kept through `graph::source_proof_failure`). Any
  other failure of the confirmed-merge source proof
  (`verify_merged_fold_sources`: Cargo residue, Git checkpoints, the fetched base)
  is `ProofIncomplete` by what that stage is for; `failed` is left for the deletion
  itself (git, filesystem). A record readable at the first look and not under the
  locks is `unreadable` and counts in the idle pass's unreadable counter.
- **A cycle covers a fixed range.** A pass works through `(cursor, high_water]` of
  `<home>/fold-turn-cursor` (JSON `{cursor, high_water}`; `high_water` is the last
  run id when the cycle began, absent file = no cycle) and the pass that finds the
  range exhausted removes the file, so the next pass begins a new cycle with a new
  high-water mark. A cycle over N records at its start takes at most
  `ceil(N / inspect)` passes plus the passes its fold invocations consume
  (`ceil(F / fold)`), plus one per pass the time budget cut short (a pass can spend
  the budget judging without starting a fold), and a run that
  left its grace after being judged is folded within the next cycle. The bound is
  as honest as the ids: they start with local wall-clock time, so runs created
  after the mark sort after it and wait, while a run created in the same second as
  the mark, or after a backwards clock step, may join the current cycle (each adds
  at most its own judgement; no cohort list is kept on purpose). A cycle file that
  is unreadable, names an id that is not a run id, has a `high_water` newer than
  every run, a `high_water` below the cursor, a cursor naming a vanished run, or an
  empty range starts a clean cycle and says why (`cycle_restart`).
- **Bounds.** `clean::BUSY_FOLD_BOUNDS`: 64 records judged, 4 `fold_run_when`
  invocations, 5 minutes between runs, always at least one judged. The fold budget
  is charged when an invocation begins, whatever it returns. The inventory of
  `runs/` is O(history) per pass and counted in `elapsed_ms`; the busy turn's
  inventory holds only names for which `run::is_run_id` holds (a stray directory
  with a `run.json` would become the saved high-water mark, be refused as "not a
  run id" and restart the cycle on every pass; the idle pass keeps its wider
  inventory). Judging a record
  reads files whose cost depends on the disk, which is why the time budget covers
  judging as well as folding.
- **A run is skipped on a fact a fold recorded, never on an inference.**
  `RunState::fold_settled_at` (`#[serde(default)]`, absent = unknown;
  `run::SCHEMA` unchanged) is written in the fold's own locked save when it found
  nothing left to remove **and** the run's worktree bay was gone (`try_exists` was
  `Ok(false)`); a fold that finds work clears it in the same save. The busy turn
  (`clean::settled`, counted `already_folded`, no fold, no budget) skips a run only
  when the mark is present and the bay is confirmed absent *now* by a fallible
  check: an error, or a bay that exists even empty, means the fold is invoked. A
  stale Git registration or a branch without a bay is not disk and is left to the
  ordinary paths. Nothing infers "nothing left" from candidate flags, directory
  listings or Git; the idle `fold_due` never skips.
- **Receipt.** `source-eviction-fold-worker.json` carries per-outcome counts
  (`folded`, `nothing_left`, `already_folded`, `live`, `resumable`, `within_grace`,
  `recovery_retained`, `proof_incomplete`, `unreadable`, `record_gone`, `failed`),
  `records`, `inspected`, `invoked`, `cursor`, `high_water`, `stopped`,
  `cycle_restart`, `cursor_error`, `elapsed_ms` and `notes` (the text of up to 8
  `proof_incomplete` / `failed` runs, scrubbed, 300 chars). A skipped dispatch says
  why in `source-eviction-fold-dispatch.json`, an unreadable startup configuration
  included. Test seams: `daemon::launch_service` runs the worker inline under
  `cfg(test)`; `clean::tests::AFTER_FIRST_READ` and `graph::BEFORE_LOCKS` run a
  closure between a look at the record and the locks;
  `retention::WithoutContainment` makes `sweep` refuse as on a platform without
  Unix containment.

The turn never sweeps retention and owns no deletion authority beyond what
`fold_run` already has. `retention::sweep` persists `retention.json` even when it
refuses on a platform without Unix containment (`sweep_inner_on` takes the
capability); do not make that refusal return before `save_report`. `save_report`
stages into a uniquely named file created exclusively and renames it, since the
refusal path takes no `retention.lock` and two passes may publish at once; a
staging file of this report (`retention.json.*.tmp`) older than a day is removed
when a report is published.

## Collection threshold versus admission floor

`[disk] min_free_bytes` means admission only; `[disk] reclaim_free_bytes`
(`Option<u64>`, skipped when unset so `run.json` and older records are
unchanged) is where free space drives collection. **Read it only through
`config::Disk::reclaim_threshold()`** (unset = `2 x min_free_bytes`, saturating;
never below `min_free_bytes`, so an explicit `0` is not an off switch; the
*resolved* `0` - only with `min_free_bytes = 0` - means no free-space
collection, except that the retained-output sweep still treats a failed
free-space measurement as pressure). Readers of the threshold:
`clean::prune_cache_under_pressure` (shared cache), through
`disk::pressure_limit` / `disk::pressure_reserve` / `disk::pressure_outcome`, the
free-space tests in `retention::sweep_inner` (pressure flag and per-target
skip), plus the `reclaim_free_bytes` field of `retention::Report` and of the
daemon's `disk-pressure` service receipt (the one reporting addition; everything
else is a log line). The isolated-build pool
(`build_target::prune_registered`) deliberately does **not** read it (below).
Readers that stay on
`min_free_bytes`: `daemon::disk_gate_with` / `disk::gate*` and `main::disk_precheck`
(admission), `triage` floors and disk-hold recovery, `retention::emergency` and
`OutputLease::admit*` (the half-floor writer stop and 1 GiB reservations), the
`graph.rs` fix-round guard, `agent.rs`, `bump.rs`, `worktree_clean`/`worktree_setup`
admission, the isolated managed-operation admission in `build_target`, and the
"retention remains blocked" notice at the end of `sweep_inner` (about operating,
so a volume merely below the threshold with nothing eligible raises nothing).
`magi cache prune` prunes to the plain cap. A new reader of free space must pick
one side on purpose and be listed here.

**A pass is estimated-deficit collection.** The shared-cache pass measures free
space once, computes the deficit against the threshold from that one number and
removes that many *logical* bytes oldest-first; it never re-measures in a loop
(hard links and other writers mean the freed space can differ - the next pass, a
service period later, measures again). Do not write "collects until the
threshold is reached" anywhere.

**The isolated-build pool is outside the threshold, on purpose.** The collection
threshold applies to the shared build cache and to retained worktree outputs.
`build_target::prune_registered` is collected to its cap and, below the
admission floor, by the deficit against `min_free_bytes`, exactly as before the
threshold existed (it calls `disk::pressure_limit` with threshold = floor, which
is that rule). A pool-wide reserve would need a pool-wide inventory that stays
true across several targets' leases and concurrent passes; that machinery was
tried and cut. Do not add a threshold reader there without it.

**The shared build cache keeps a reserve while free space is at or above the
admission floor and below the threshold, and it is enforced where files are
deleted.** `disk::pressure_limit` has three bands: free at or above the
threshold (the cap), between the floor and the threshold (shrink by the deficit
but never below half the cache's configured cap - `disk::pressure_reserve`) and
below the floor (exactly the pre-threshold rule: shrink by the deficit against
`min_free_bytes`, to zero if need be). The limit alone cannot keep the reserve,
because files go whole: one artifact larger than `size - reserve` would be
deleted, rebuilt and deleted again. So the reserve is also passed to the pruning
routine as a "keep at least" bound (`disk::prune_dir_keeping`,
`cache::maintenance_prune_keeping`; `0` for every other caller: below the floor,
the plain cap, manual `magi cache prune`, which go through `prune_dir` /
`maintenance_prune` unchanged): oldest-first as always, but a file whose removal
would leave less is skipped and later candidates are still tried while the cache
is over its limit. The inventory is the one taken under the maintenance lease
and Cargo locks. The half-cap ratio is a constant on purpose, not a setting: a
cache with nothing in it is no cache, and without it a disk whose free space
other software controls would be emptied and rebuilt cold every pass. A zero cap
still means pruning is off. Retained worktree outputs get no reserve (nothing
rebuilds from them).

**Reporting is one log line per shared-cache pass, and nothing else new.**
`clean::prune_cache_under_pressure` documents the contract: a pass that *runs to
completion* (measured free space, took the maintenance lease, walked the cache)
emits one `tracing::info!` line - admission floor, collection threshold, free
bytes measured, the size the prune's own inventory reported, logical bytes
removed, outcome (`disk::pressure_outcome`: `within limit`, `at reserve`,
`collected`, `nothing eligible`) - for every caller (busy-time `disk-pressure`
service, idle `housekeep`, between-runs `cache` service). A pass that is
*refused or fails* (lease or Cargo lock held, an I/O error, an unreadable
free-space measurement) keeps exactly the pre-threshold reporting (return value
or error) and emits no additional line. The only persisted value is the
resolved threshold in the busy-time service receipt and the sweep report: there
are no per-pass receipts, volume reports or report structs. Tests assert the
outcome function and file effects, never log text. The shared-cache pass
measures the cache (`dir_size`) only below the threshold; the retained-output
sweep remeasures targets on each sweep while a volume is below the threshold
(before: below the floor), once per sweep, i.e. once per service period (30 s
while work runs).

## Retained output sweep budget

`src/retention.rs` normally visits targets by oldest activity; under free-space
pressure it remeasures and visits largest targets first (oldest breaks ties).
Inventory sizes only prioritize targets. Budget decisions use dep-info-proven
outputs and independently proven incremental generations measured under all
ownership, registration, lease and Cargo locks.
`[disk] worktree_reclaim_bytes = 0` disables output deletion. A positive budget
allows the first target whose deletion starts to exceed it, preventing permanent
retention of oversized outputs; this can increase deletion volume and duration.
That exception is consumed at deletion start even on partial failure, and stops
further deletions in that pass. Successful removals are counted even on failure.
Other targets must fit the remaining budget; safety refusals consume no exception.
Cargo v1 `deps` and v2 unit `out` share the same dep-info/signature proof;
unit fingerprints restrict v2 authority, and mixed or incomplete layouts retain outputs.
See `docs/retained-worktrees.md` for the complete retention policy.

## Managed incremental caches

`src/incremental.rs` defaults managed command environments to
`CARGO_INCREMENTAL=0`. Unix linked-worktree opt-ins use fresh compiler
generations and per-file completion proofs in the worktree Git directory;
legacy caches never acquire ownership retroactively. The 512 MiB worktree budget
charges actual bytes for validated completed generations and reserves 128 MiB
for each live/unproven generation, with at most 1024 provenance records. These
are conservative growth controls, not filesystem quotas. Generation admission
waits up to 30 seconds for its namespace lock; hash completed generations before
that lock and retain shared owner guards through the reservation check.
Keep wrapper chaining, unknown-data refusal and generation/session locks intact.
Incremental proof is never a retirement proof. `src/retention.rs` reserves
1 GiB per admitted editing/verification writer per volume under one home;
these output leases follow `seat_process::Running` through descendant cleanup.
Logical inventory/deletion, deduplicated file allocations, estimated released
allocations and observed free-space change are separate report quantities.
See `docs/retained-worktrees.md` for the policy and its deliberate limitations.

## Checkout evidence and eviction

`retention::copies` evicts proved inactive reviewer, judge and advisor copies
and empty superseded candidate checkouts independently of run folding/retirement. It must keep task
lineage, candidate branches, review history and selected/public recovery sources.
`fold_evidence` snapshots preserve complete base/source trees plus original tip
metadata without requiring their parent history to survive Git GC. Pending
checkout intents retain raw administration and every admitted reflog/ORIG_HEAD
tip, including unrelated earlier tips; changed or unknown contents must block retries.
Validation applies each archived binary patch in a private index again before
unlink. `fold --show-seats` and `fold --restore-seat <head> --dest <new-path>`
inspect/restore recorded tips without the original repository. `source-evidence --restore`
creates an inspection repository only and must never transfer recovery/public
authority or approval. See `docs/checkout-eviction.md` for limits and accounting.

## Build cache policy and isolated outputs

New task runs select `[verify] build_cache` at admission: explicit task
choice first (including `shared` on urgent work), then `isolated` for urgent
tasks, then the layered config (default `shared`). The urgent rule applies only
where it helps and works (`build_target::urgent_isolation`): the repository
has a shared cache to wait behind and its verification commands fit the
grammar isolated mode accepts. Otherwise an urgent task keeps the configured
mode, because isolation must never be what stops urgent work; only an explicit
`isolated` is strict. Historical tasks retain
their shared choice until changed. The resolved mode belongs to
`RunState.config.verify`; resumes use it regardless of later task or config
edits. Non-config selections are recorded in the run's `build-cache` events.
Use the same precedence for startup disk recovery and the task-show preview.

In shared mode, keep the configured shared-path wave lease and existing
source freshness behavior. In isolated mode, never lease the configured shared
path: `build_target` gives each linked-checkout generation its own target and
leases that actual path, with source freshness and maintenance exclusion.
Publish the Git admin anchor only after the target ownership proof is complete.
Editing seats and managed commands in the checkout use that target; read-only
agent seats get no target write grant. Launcher-run setup still uses the
checkout's target. Do not bypass the managed Cargo shim or relax repository
coordination, admission, registry or incremental-cache locks.

Isolated targets are full build outputs outside source trees under
`MAGI_HOME/isolated-builds`. Probe source, worktree and output volumes; charge
one 1 GiB reservation per active managed writer per affected volume when
`min_free_bytes` is enabled, and keep output leases through descendant cleanup.
The pool cap is separate from the shared cache cap. Snapshot the checkout's
binding before fold removes its Git admin anchor; reclaim only proved idle
outputs after the source is gone. Reserve isolated setup once before any step
so an archived seat can roll back a pristine restoration on disk admission
failure without replaying a started setup.