Skip to main content

magi/
agent.rs

1//! Driving agent CLIs.
2//!
3//! Every agent in magi is a subscription CLI (`claude`, `opencode`, `agy`) or
4//! an arbitrary command, invoked headless in a working directory. There is no
5//! API-key path on purpose: the CLIs carry the operator's own plan, and they
6//! are the only interface that exposes an agent's whole tool loop rather than a
7//! single completion.
8//!
9//! # Seats, not agents
10//!
11//! Conversations are keyed by *seat* ([`SeatState::key`]), never by agent id. A
12//! model that implements candidate B and also sits as judge 3 gets two
13//! unrelated conversations, so the judge cannot recognise its own work from
14//! having written it. Sessions are what make deliberation affordable — a judge
15//! remembers its own argument instead of being re-fed the entire candidate set
16//! — and seat scoping is what keeps that from destroying blindness.
17//!
18//! # Session mechanics per CLI
19//!
20//! | CLI | open | resume |
21//! |-----|------|--------|
22//! | `claude` | `--session-id <uuid>` (magi mints it) | `--resume <uuid>` |
23//! | `opencode` | `--format json` reports `sessionID` | `-s <id>` |
24//! | `agy` | `--output-format json` reports `conversation_id` | `--conversation <id>` |
25//! | `codex` | `exec --json` reports `thread.started.thread_id` | `exec … resume <id>` |
26//! | `omp` | `-p --mode=json` reports `id` on its `"type":"session"` line | `--resume <id>` |
27//!
28//! Claude is the only one magi can address before the first turn; the others
29//! report an id back, so [`SeatState::captured_session`] stays `None` until a
30//! turn has completed and [`has_session`] answers honestly instead of
31//! optimistically.
32use std::collections::BTreeMap;
33use std::ffi::OsStr;
34use std::path::{Path, PathBuf};
35use std::process::Stdio;
36use std::time::{Duration, Instant};
37
38use anyhow::{Context as _, Result, bail};
39use serde::{Deserialize, Serialize};
40use std::sync::{Arc, Mutex};
41
42use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
43use tokio::process::Command;
44
45use crate::config::{AgentChoice, AgentKind, AgentSpec, Delivery};
46use crate::proc::Quiet as _;
47use crate::rng::SplitMix64;
48
49/// Conversation state for one seat, persisted with the run so `magi run
50/// --resume` continues the same CLI conversations.
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
52pub struct SeatState {
53    /// Stable seat name, e.g. `impl-A`, `judge-2`, `review-1`, `fix`.
54    pub key: String,
55    /// Agent id occupying the seat.
56    pub agent: String,
57    /// Turns already taken in this seat.
58    pub turns: usize,
59    /// Claude session uuid, minted up front so the first turn and every resume
60    /// agree on it without parsing anything back.
61    pub claude_session: Option<String>,
62    /// Session id reported by a CLI that mints its own.
63    pub captured_session: Option<String>,
64    /// Absolute directory paired with an isolated omp session id.
65    /// An existing omp id without this field uses legacy lookup.
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub omp_session_dir: Option<PathBuf>,
68}
69
70impl SeatState {
71    /// New seat. `run_seed` scopes the minted Claude uuid to this run.
72    pub fn new(key: &str, agent: &str, run_seed: u64) -> Self {
73        let mut rng = SplitMix64::new(run_seed ^ crate::rng::fnv1a(key));
74        Self {
75            key: key.to_owned(),
76            agent: agent.to_owned(),
77            turns: 0,
78            claude_session: Some(rng.uuid_v4()),
79            captured_session: None,
80            omp_session_dir: None,
81        }
82    }
83}
84
85/// Can a follow-up prompt rely on this seat remembering the conversation?
86pub fn has_session(kind: AgentKind, seat: &SeatState, sessions_enabled: bool) -> bool {
87    if !sessions_enabled || seat.turns == 0 {
88        return false;
89    }
90    match kind {
91        AgentKind::Claude => seat.claude_session.is_some(),
92        AgentKind::Opencode | AgentKind::Antigravity | AgentKind::Codex | AgentKind::Omp => {
93            seat.captured_session.is_some()
94        }
95        AgentKind::Command => true,
96    }
97}
98
99/// One agent invocation.
100#[derive(Debug, Clone)]
101pub struct Invocation<'a> {
102    /// Rendered repository coordination policy for this invocation.
103    pub coordination: Option<&'a crate::config::Coordination>,
104    /// Launcher fetch evidence, unchanged on session resume.
105    pub fetched_base: Option<&'a crate::run::FetchedBase>,
106    /// Working directory. Always a real checkout, so every CLI can read the
107    /// repository without per-vendor "extra directory" flags.
108    pub cwd: &'a Path,
109    /// The full prompt.
110    pub prompt: &'a str,
111    /// Wall-clock limit; the process tree is killed when it elapses.
112    pub timeout: Duration,
113    /// May the agent modify files? Judges and reviewers may not. Together
114    /// with an editing node (see [`repository_writer`]) it also drops a codex
115    /// seat's OS sandbox and approval gate, as claude's `bypassPermissions`
116    /// does for every claude seat.
117    pub allow_write: bool,
118    /// Continue this seat's conversation when the CLI supports it.
119    pub sessions: bool,
120    /// Directory for prompt / stdout / stderr artifacts.
121    pub artifacts: &'a Path,
122    /// Artifact filename stem.
123    pub stem: &'a str,
124    /// Run this invocation belongs to. Exported as `MAGI_RUN` so an agent that
125    /// files a task with `magi task add` is attributed to the run that was
126    /// paying for it, rather than looking like a human wandered by.
127    pub run: &'a str,
128    /// Graph node being executed, e.g. `implement` or `review`. Exported as
129    /// `MAGI_NODE` for the same reason: "who asked for this" is the first
130    /// question about an autonomously created task.
131    pub node: &'a str,
132    /// Shared build cache the seat should build into, from the rendered
133    /// `CARGO_TARGET_DIR=` in the verify commands. Exported as
134    /// `CARGO_TARGET_DIR` so the implementer's compile lands inside the same
135    /// directory `verify` reads back from - one cache, one prune, and the
136    /// build the agent just paid for is the build the gate reuses.
137    pub cache_dir: Option<&'a Path>,
138    /// Absolute paths of images the operator attached to this conversation,
139    /// outside `cwd` - see `chat`/`talk`'s `attachments_dir`. Empty for every
140    /// invocation that is not a chat or talk turn. [`build_command`] uses
141    /// this only to decide whether a CLI's sandbox needs widening to read
142    /// them; the prompt text naming each path and its mime is built by the
143    /// caller, not here.
144    pub attachments: &'a [PathBuf],
145    /// Directories outside `cwd` the seat may write, when it may write at all.
146    /// Explicit, purpose-specific grants (for example a deputy's stores).
147    /// Repository editing seats also receive the shared Git directory and
148    /// question control-plane directories in [`invoke`]; adapters that widen
149    /// a workspace per directory (agy's `--add-dir`) need them, while a codex
150    /// editing seat runs without a sandbox and ignores them.
151    pub writable: &'a [PathBuf],
152}
153
154/// A repository editing seat: implementer, fixer, grafter, gate fixer, land
155/// or rebase resolver, or a chat turn authorized for a direct change.
156///
157/// For codex this is also the whole sandbox policy: these seats run with
158/// `--dangerously-bypass-approvals-and-sandbox` (owner decision 2026-10-27),
159/// matching claude's `bypassPermissions`, because codex's seatbelt sandbox
160/// refuses `$TMPDIR` and aborts Chrome, so repository tests cannot run inside
161/// it. Every other seat keeps its sandbox.
162fn repository_writer(inv: &Invocation<'_>) -> bool {
163    inv.allow_write
164        && (matches!(
165            inv.node,
166            "implement"
167                | "fix"
168                | "graft"
169                | "gate-fix"
170                | "land"
171                | "rebase"
172                | "base-conflict"
173                | "external-chat"
174        ) || inv.node == crate::queue::CHAT_NODE)
175}
176
177fn repository_seat(inv: &Invocation<'_>) -> bool {
178    // These roles consume supplied state, prompts and conversation history.
179    // In particular, they must be able to deliver an answer or make queue
180    // decisions while an editor holds its reservation waiting for that answer.
181    // Chat turns and their transcript-only title seats bypass repository
182    // scheduling, including waiter delivery.
183    !matches!(
184        inv.node,
185        crate::queue::CHAT_NODE | "external-chat" | "talk-title" | "deputy" | "conduct" | "dupes"
186    )
187}
188
189/// Resolve the additional write scope for a repository editing seat.
190///
191/// Resolve Git's common directory from the actual seat checkout, never by
192/// assuming `.git` is a directory. Canonicalize directories before handing
193/// them to a sandbox (notably `/tmp` aliases on macOS). Failure is a startup
194/// error: do not start work with an unusable lock/question route.
195pub async fn worktree_writable_roots(cwd: &Path, home: &Path) -> Result<Vec<PathBuf>> {
196    let mut roots = Vec::new();
197    if let Some(common) = crate::repo_lock::common_dir(cwd).await? {
198        let cwd = std::fs::canonicalize(cwd).context("canonicalize seat working directory")?;
199        if !common.starts_with(&cwd) {
200            roots.push(common);
201        }
202    }
203    // Questions::put/update/beat/panels write questions. Its quiet_for hook
204    // updates matching notifications. Neither needs queue, runs, talks, nor
205    // the entire state directory.
206    for name in ["questions", "notifications"] {
207        let dir = home.join(name);
208        std::fs::create_dir_all(&dir).with_context(|| format!("prepare seat {name} directory"))?;
209        roots.push(std::fs::canonicalize(dir)?);
210    }
211    Ok(roots)
212}
213
214/// Current-turn instructions override stale fetch requirements in history.
215fn editing_access_note(base: Option<&crate::run::FetchedBase>) -> String {
216    let mut note = String::from(
217        "Launcher repository access contract (applies to this turn and overrides earlier fetch instructions):\n",
218    );
219    if let Some(base) = base {
220        note.push_str(&format!(
221            "The launcher successfully fetched `{}/{}` at {} and pinned the run base to `{}`. Use this exact local commit as the verified fetched base; this is a snapshot, not a claim that the remote has not moved since. Do not fetch again as a prerequisite, move the base, or refresh it on resume. Base updates belong to the launcher's existing base-sync path.\n",
222            base.remote, base.branch, base.fetched_at, base.commit,
223        ));
224    } else {
225        note.push_str("No successful launcher fetch evidence is supplied for this invocation. Do not describe local tracking refs as freshly fetched. If fresh remote evidence is essential, report an infrastructure blocker requiring a launcher fetch and a new prepared turn.\n");
226    }
227    note
228}
229
230/// Evidence of a CLI usage limit or authentication outage, distinct from an
231/// ordinary task failure.
232///
233/// `reset` is free text: CLIs render the reset time in their own locale, and
234/// parsing it exactly would be a bug factory. When it is not readable we say
235/// nothing rather than invent a format.
236#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
237pub struct Quota {
238    /// Machine-side cause; old records describe a usage limit.
239    #[serde(default)]
240    pub cause: QuotaCause,
241    /// Agent id, filled by the invocation boundary.
242    #[serde(default)]
243    pub agent: String,
244    /// Human-readable reset time, when the CLI printed one.
245    #[serde(default)]
246    pub reset: Option<String>,
247}
248
249/// Why an invocation needs machine-side recovery rather than a task retry.
250#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
251#[serde(rename_all = "snake_case")]
252pub enum QuotaCause {
253    /// Subscription usage must reset or be replenished.
254    #[default]
255    UsageLimit,
256    /// The operator must restore the CLI's authenticated session.
257    Authentication,
258}
259
260/// A CLI hung up on its own stream while the agent was working.
261///
262/// Separate from a failure because the work was done and billed, and separate
263/// from a [`Quota`] because it is worth asking again: the answer is in the
264/// conversation, not lost to a limit that has to reset first. See
265/// [`dropped_stream`].
266#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
267pub struct Dropped {
268    /// What the CLI said as it hung up, verbatim.
269    pub why: String,
270    /// Output tokens the CLI reported before it did - the evidence that this
271    /// was a delivery failure and not an agent that produced nothing.
272    pub output_tokens: u64,
273}
274
275/// One command a CLI's own structured event stream reported running, with
276/// the result it reported for it.
277///
278/// This is evidence the CLI chose to report about its own tool loop — never
279/// something magi polled, supervised, or inferred from a process list. Only
280/// the Codex arm of [`extract`] currently populates it (its `item.completed`
281/// / `command_execution` events name `id`, `command`, `exit_code` and
282/// `aggregated_output` directly); every other backend's CLI does not expose
283/// this in what magi currently captures, so its seats simply never produce
284/// any. A command a CLI never reported finishing (still running when the
285/// turn ended, or the event stream never named it) has no entry here either
286/// — there is no event to build one from, and this type must never be used
287/// to *guess* that a command is still in flight.
288#[derive(Debug, Clone, Serialize, Deserialize)]
289pub struct CommandEvidence {
290    /// The CLI's own id for this command.
291    pub id: String,
292    /// The command itself, as the CLI reported it.
293    pub description: String,
294    /// Exit code the CLI reported for it.
295    pub exit_code: Option<i32>,
296    /// Tail of the command's own output, when the CLI reported one.
297    pub result_summary: String,
298    /// Which CLI/event stream this came from, e.g. `"codex"`.
299    pub source: String,
300}
301
302/// Result of an agent invocation.
303#[derive(Debug, Clone, Serialize, Deserialize)]
304pub struct AgentOutput {
305    /// The agent's final message, extracted from whatever the CLI printed.
306    pub text: String,
307    /// Exit status code.
308    pub exit_code: Option<i32>,
309    /// Did the invocation hit its timeout?
310    pub timed_out: bool,
311    /// Wall-clock duration.
312    pub duration_ms: u64,
313    /// Artifact file names, relative to the run's `artifacts/` directory.
314    pub artifacts: Vec<String>,
315    /// Usage limit or authentication outage, when distinguishable from a normal
316    /// failure. `None` for a normal failure, a timeout, or a CLI we cannot
317    /// read — the conservative default.
318    #[serde(default)]
319    pub quota: Option<Quota>,
320    /// The CLI hung up on its own stream after the agent had done billed
321    /// work. `None` unless that exact shape was recognised — see
322    /// [`dropped_stream`].
323    #[serde(default)]
324    pub dropped: Option<Dropped>,
325    /// Commands the CLI's own event stream reported running, see
326    /// [`CommandEvidence`]. Always empty for a backend this crate does not
327    /// currently read structured job events from.
328    #[serde(default)]
329    pub commands: Vec<CommandEvidence>,
330    /// Input-side tokens the CLI reported for this turn - approximately the
331    /// size of the context the model just read. `None` when the CLI reports
332    /// no usage (or in a shape this build does not read): unknown, never 0.
333    /// See [`context_tokens`].
334    #[serde(default)]
335    pub context_tokens: Option<u64>,
336    /// Tool calls the CLI's own stream reported for this turn. `None` when
337    /// the CLI does not report them in a shape this build reads: unknown,
338    /// never 0. `Some(0)` is therefore positive evidence of a turn that
339    /// answered without using a single tool.
340    #[serde(default)]
341    pub tool_calls: Option<u64>,
342}
343
344impl AgentOutput {
345    /// Did the CLI exit cleanly with something to say?
346    pub fn usable(&self) -> bool {
347        !self.quota_exhausted()
348            && !self.timed_out
349            && self.exit_code == Some(0)
350            && !self.text.trim().is_empty()
351    }
352
353    /// Does this invocation need machine-side quota or authentication recovery?
354    pub fn quota_exhausted(&self) -> bool {
355        self.quota.is_some()
356    }
357
358    /// Did the agent work and the CLI fail to deliver it?
359    ///
360    /// Worth re-asking, unlike [`AgentOutput::quota_exhausted`]: the answer is
361    /// in a conversation this process can resume.
362    pub fn work_undelivered(&self) -> bool {
363        self.dropped.is_some()
364    }
365}
366
367/// Typed context distinguishing an interrupted process from admission that
368/// never spawned one. ResourceBlocked remains in the error chain for parking.
369#[derive(Debug)]
370pub(crate) struct ExecutionInterrupted(pub String);
371
372impl std::fmt::Display for ExecutionInterrupted {
373    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
374        write!(f, "execution interrupted: {}", self.0)
375    }
376}
377
378impl std::error::Error for ExecutionInterrupted {}
379
380/// How long to keep reading a pipe after the child is gone.
381///
382/// Bounded on purpose: a surviving grandchild can hold the write end open
383/// forever, and the graph must not hang on a process it has already killed.
384const PIPE_GRACE: Duration = Duration::from_secs(3);
385
386/// Bytes a pipe reader has accumulated so far, shared with whoever spawned it.
387pub(crate) type Captured = Arc<Mutex<Vec<u8>>>;
388
389/// Read `pipe` to end in its own task, appending into a buffer the caller can
390/// inspect at any time.
391///
392/// The buffer is shared rather than returned because the interesting moment is
393/// exactly the one where the reader has *not* finished: a killed agent's pipe
394/// may still be held open by a surviving grandchild, and the bytes that did
395/// arrive are the only evidence of what it was doing. An earlier version
396/// returned the buffer from the task and dropped it on timeout, which is how
397/// `<stem>.out` came to be empty on every timeout.
398pub(crate) fn drain<R>(pipe: Option<R>) -> (Captured, Option<tokio::task::JoinHandle<()>>)
399where
400    R: tokio::io::AsyncRead + Unpin + Send + 'static,
401{
402    let buf: Captured = Arc::new(Mutex::new(Vec::new()));
403    let Some(mut pipe) = pipe else {
404        return (buf, None);
405    };
406    let sink = Arc::clone(&buf);
407    let handle = tokio::spawn(async move {
408        let mut chunk = [0u8; 8192];
409        loop {
410            match pipe.read(&mut chunk).await {
411                Ok(0) | Err(_) => break,
412                Ok(n) => {
413                    if let Ok(mut guard) = sink.lock() {
414                        guard.extend_from_slice(&chunk[..n]);
415                    }
416                }
417            }
418        }
419    });
420    (buf, Some(handle))
421}
422
423/// Take whatever a reader has captured, giving it at most `grace` to finish.
424///
425/// A reader still blocked after that is abandoned, not awaited — but its bytes
426/// come back either way, which is the whole point.
427pub(crate) async fn collect(
428    buf: &Captured,
429    handle: Option<tokio::task::JoinHandle<()>>,
430    grace: Duration,
431) -> String {
432    if let Some(handle) = handle {
433        if tokio::time::timeout(grace, handle).await.is_err() {
434            tracing::debug!("a pipe is still held open after the child exited");
435        }
436    }
437    let bytes = buf.lock().map(|g| g.clone()).unwrap_or_default();
438    String::from_utf8_lossy(&bytes).into_owned()
439}
440
441#[derive(Debug)]
442pub(crate) struct IsolatedSeatWait(pub(crate) crate::run::ResourceBlock);
443
444impl std::fmt::Display for IsolatedSeatWait {
445    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
446        f.write_str(&self.0.description())
447    }
448}
449
450/// Invoke `spec` for `seat`, updating the seat's conversation state.
451///
452/// The work itself runs as one heap-allocated future. Every caller holds this
453/// future inside its own (a chat turn nests it four levels deep), and in a
454/// debug build each level also keeps by-value temporaries of it in its poll
455/// frame. Inline, that pushed a chat worker turn past the 2 MiB a test thread
456/// has on Windows; boxed, callers carry a pointer.
457pub async fn invoke(
458    spec: &AgentSpec,
459    seat: &mut SeatState,
460    inv: &Invocation<'_>,
461) -> Result<AgentOutput> {
462    Box::pin(invoke_on_heap(spec, seat, inv, &mut false, None)).await
463}
464
465/// A wave holds the shared-cache lease across all its seats.
466pub(crate) async fn invoke_in_wave(
467    spec: &AgentSpec,
468    seat: &mut SeatState,
469    inv: &Invocation<'_>,
470    cache_guard: Option<&crate::cache::Guard>,
471) -> Result<AgentOutput> {
472    Box::pin(invoke_on_heap(spec, seat, inv, &mut false, cache_guard)).await
473}
474
475/// Record entry into spawning, not successful launch: a spawn error can
476/// occur after creating a process, so callers must treat it conservatively.
477pub(crate) async fn invoke_tracking_spawn(
478    spec: &AgentSpec,
479    seat: &mut SeatState,
480    inv: &Invocation<'_>,
481    spawn_attempted: &mut bool,
482) -> Result<AgentOutput> {
483    Box::pin(invoke_on_heap(spec, seat, inv, spawn_attempted, None)).await
484}
485
486async fn invoke_on_heap(
487    spec: &AgentSpec,
488    seat: &mut SeatState,
489    inv: &Invocation<'_>,
490    spawn_attempted: &mut bool,
491    wave_cache_guard: Option<&crate::cache::Guard>,
492) -> Result<AgentOutput> {
493    let home = crate::run::home();
494    // Graph writers use their saved configuration on every turn.
495    let (min_free, isolated) = if repository_writer(inv) && repository_seat(inv) {
496        match crate::run::RunState::load_under(inv.run, &home) {
497            Ok(state) => (
498                state.config.disk.min_free_bytes,
499                crate::build_target::isolated(&state.config).then(|| Box::new(state.config)),
500            ),
501            Err(error) if crate::run::is_run_id(inv.run) => {
502                return Err(crate::repo_lock::ResourceBlocked(format!(
503                    "cannot confirm saved build policy: {error:#}"
504                ))
505                .into());
506            }
507            Err(_) => (0, None),
508        }
509    } else {
510        (0, None)
511    };
512    let isolated = isolated.as_deref();
513    let resource = |error: anyhow::Error| {
514        crate::repo_lock::ResourceBlocked(format!("{}: {error:#}", crate::build_target::KIND))
515    };
516    let mut build_guard = None;
517    let mut target = None;
518    if let Some(config) = isolated {
519        let path = crate::build_target::resolve(&home, inv.cwd).map_err(resource)?;
520        let head = crate::git::rev_parse(inv.cwd, "HEAD")
521            .await
522            .map_err(resource)?;
523        let owner = crate::cache::Owner::here(inv.run, inv.node, &seat.key, inv.cwd, &head);
524        let started = std::time::Instant::now();
525        build_guard = Some(
526            crate::build_target::acquire(&home, &path, &owner, config)
527                .await
528                .map_err(|error| {
529                    let detail = format!("{}: {error:#}", path.display());
530                    let timeout = error.is::<crate::cache::WaitTimeout>().then(|| {
531                        IsolatedSeatWait(crate::run::ResourceBlock {
532                            cause: crate::run::ResourceBlockCause::IsolatedCacheTimeout {
533                                target: path.clone(),
534                                waited_secs: started.elapsed().as_secs(),
535                                limit_secs: config.graph.timeout_resource_wait,
536                            },
537                            node: inv.node.to_owned(),
538                            kind: crate::build_target::KIND.into(),
539                            detail: detail.clone(),
540                            at: jiff::Timestamp::now(),
541                        })
542                    });
543                    let error = anyhow::Error::new(crate::repo_lock::ResourceBlocked(format!(
544                        "{}: {detail}",
545                        crate::build_target::KIND
546                    )));
547                    match timeout {
548                        Some(timeout) => error.context(timeout),
549                        None => error,
550                    }
551                })?,
552        );
553        target = Some((path, head));
554    }
555    // Direct invocations (land, rebase, chat and waiter delivery) do not
556    // necessarily run in a graph wave. Never export an unleased cache.
557    let requested_cache = inv
558        .cache_dir
559        .filter(|_| inv.allow_write && target.is_none());
560    let mut shared_guard = None;
561    let shared_cache = if let Some(cache) = requested_cache {
562        if wave_cache_guard.is_some() {
563            Some(cache)
564        } else {
565            let owner = crate::cache::Owner::here(inv.run, inv.node, &seat.key, inv.cwd, "");
566            match crate::cache::try_acquire(&home, cache, &owner) {
567                Ok(crate::cache::AcquireOutcome::Acquired(guard)) => {
568                    shared_guard = Some(guard);
569                    Some(cache)
570                }
571                Ok(crate::cache::AcquireOutcome::Busy(busy)) => {
572                    tracing::info!(seat = %seat.key, reason = %busy.describe(), "shared build cache unavailable");
573                    None
574                }
575                Err(error) => {
576                    tracing::warn!(seat = %seat.key, %error, "could not lease shared build cache");
577                    None
578                }
579            }
580        }
581    } else {
582        None
583    };
584    if let Some(cache) = shared_cache {
585        crate::cache::invalidate_identity(&home, cache);
586    }
587    let inv = &Invocation {
588        cache_dir: target
589            .as_ref()
590            .map(|(path, _)| path.as_path())
591            .or(shared_cache),
592        ..inv.clone()
593    };
594    // Wait for repository scheduling before spawning or starting a seat's
595    // budget. Readers hold the real lock; editors exclude local readers while
596    // taking their own repository-prescribed lock inside the seat. Running
597    // owns the lease through descendant cleanup on cancel.
598    let lease = if repository_seat(inv) {
599        crate::repo_lock::SeatLease::for_checkout(inv.cwd, inv.allow_write, inv.coordination)
600            .await?
601    } else {
602        None
603    };
604    let inv = &Invocation {
605        timeout: spec.turn_timeout(inv.timeout),
606        ..inv.clone()
607    };
608    let mut outputs = Vec::new();
609    if repository_writer(inv) {
610        let mut paths = vec![inv.cwd.to_owned()];
611        if let Some(cache) = inv.cache_dir {
612            paths.push(cache.to_owned());
613        }
614        let admit = if isolated.is_some() {
615            crate::retention::OutputLease::admit_isolated
616        } else {
617            crate::retention::OutputLease::admit
618        };
619        outputs
620            .extend(admit(&home, &paths, min_free).map_err(|e| {
621                crate::repo_lock::ResourceBlocked(format!("disk admission: {e:#}"))
622            })?);
623    }
624    if repository_seat(inv) {
625        if let Some(guard) = crate::retention::OutputLease::borrow(inv.cwd).map_err(|e| {
626            crate::repo_lock::ResourceBlocked(format!("worktree output ownership: {e:#}"))
627        })? {
628            outputs.push(guard);
629        }
630    }
631    if let Some(cache) = inv.cache_dir {
632        outputs.push(crate::retention::OutputLease::cache(&home, cache, false)?);
633    }
634    if let (Some(config), Some((path, head))) = (isolated, &target) {
635        crate::build_target::ensure_fresh(&home, path, inv.cwd, head, config)
636            .with_context(|| format!("target {}", path.display()))
637            .map_err(resource)?;
638        // A seat may edit or build a dirty tree without changing HEAD.
639        crate::cache::invalidate_identity(&home, path);
640        tracing::info!(target = %path.display(), seat = %seat.key, "admitted isolated build cache");
641    }
642
643    let mut prompt = inv.prompt.to_owned();
644    if requested_cache.is_some() && shared_cache.is_none() {
645        prompt.push_str("\n\nThe shared Cargo cache is currently unavailable. Do not set its path manually; any necessary build must use the checkout's own target directory.");
646    }
647    if let Some(lease) = lease.as_ref().filter(|lease| lease.delegated) {
648        prompt.push_str(&format!("\n\nRepository coordination: the launcher holds the exclusive repository lock at {} for this invocation. Do not acquire a second lock or release/delete it. Repository access remains read-only.", lease.path.display()));
649    }
650    // Apply once for initial, resumed, fallback and waiter invocations alike.
651    // Deputies/chat retain their explicit grants; read-only stays read-only.
652    let home = repository_writer(inv).then(crate::run::home);
653    let mut writable = inv.writable.to_vec();
654    if let Some(home) = &home {
655        for root in worktree_writable_roots(inv.cwd, home).await? {
656            if !writable.contains(&root) {
657                writable.push(root);
658            }
659        }
660    }
661    if let Some((path, _)) = &target {
662        writable.push(path.clone());
663        prompt.push_str("\n\nUse the launcher-provided Cargo target and Cargo command. Do not set a different target or bypass the managed Cargo launcher.");
664    }
665    if repository_writer(inv) {
666        prompt.push_str("\n\n");
667        prompt.push_str(&editing_access_note(inv.fetched_base));
668    }
669    let inv = &Invocation {
670        writable: &writable,
671        prompt: &prompt,
672        ..inv.clone()
673    };
674    tokio::fs::create_dir_all(inv.artifacts)
675        .await
676        .with_context(|| format!("create {}", inv.artifacts.display()))?;
677    let prompt_path = inv.artifacts.join(format!("{}.prompt.md", inv.stem));
678    tokio::fs::write(&prompt_path, inv.prompt)
679        .await
680        .with_context(|| format!("write {}", prompt_path.display()))?;
681
682    let omp_session = if spec.kind == AgentKind::Omp {
683        Some(OmpSession::prepare(
684            spec,
685            seat,
686            inv.sessions,
687            crate::run::home,
688        )?)
689    } else {
690        None
691    };
692    let plan = build_command(spec, seat, inv, &prompt_path)?;
693    tracing::debug!(seat = %seat.key, agent = %spec.id, argv = ?plan.logged_argv(), "spawning agent");
694    // Store scope evidence without environment values or arbitrary extra args.
695    tokio::fs::write(
696        inv.artifacts.join(format!("{}.access.json", inv.stem)),
697        serde_json::to_vec_pretty(&serde_json::json!({
698            "launcher_version": env!("CARGO_PKG_VERSION"),
699            "kind": spec.kind,
700            "allow_write": inv.allow_write,
701            "unsandboxed": repository_writer(inv),
702            "writable_roots": inv.writable,
703            "isolated_build_target": target.as_ref().map(|(path, _)| path),
704            "fetched_base": inv.fetched_base,
705        }))?,
706    )
707    .await
708    .context("write seat access evidence")?;
709
710    let started = Instant::now();
711    // Resolve against the PATH the child will actually see: `spec.env` may
712    // override it, and the resolved absolute path bypasses any later lookup.
713    let child_path = spec
714        .env
715        .iter()
716        .find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
717        .map(|(_, v)| std::ffi::OsString::from(v))
718        .or_else(|| std::env::var_os("PATH"))
719        .unwrap_or_default();
720    let program = crate::config::find_program_on(&plan.argv[0], &child_path).map_or_else(
721        || plan.argv[0].clone().into(),
722        std::path::PathBuf::into_os_string,
723    );
724    let mut cmd = Command::new(program);
725    cmd.args(plan.args(omp_session.as_ref().and_then(|session| session.dir(seat))))
726        .current_dir(inv.cwd)
727        .envs(&spec.env)
728        .env("MAGI_SEAT", &seat.key)
729        .env("MAGI_TURN", seat.turns.to_string())
730        .env("MAGI_RUN", inv.run)
731        .env("MAGI_NODE", inv.node)
732        .env("MAGI_PROMPT_FILE", &prompt_path)
733        .env("MAGI_ALLOW_WRITE", if inv.allow_write { "1" } else { "0" })
734        .env("GIT_TERMINAL_PROMPT", "0")
735        .stdin(if plan.stdin.is_some() || plan.rpc {
736            Stdio::piped()
737        } else {
738            Stdio::null()
739        })
740        .stdout(Stdio::piped())
741        .stderr(Stdio::piped())
742        .kill_on_drop(true)
743        // No console window. `magi web` has no console of its own, so Windows
744        // would give each agent a fresh one - and draw it. See `crate::proc`.
745        .quiet();
746    if let Some(session) = &omp_session {
747        session.isolate_terminal_history(&mut cmd, seat);
748    }
749    crate::incremental::default_environment(&mut cmd);
750    if repository_writer(inv) {
751        crate::incremental::configure(&mut cmd, inv.cwd)?;
752    }
753    if let Some(home) = home {
754        // Match the control-plane store we granted, even with a relative
755        // MAGI_HOME or a per-agent environment override.
756        cmd.env("MAGI_HOME", std::fs::canonicalize(home)?);
757    }
758    if target.is_none() {
759        crate::build_target::command::clear(&mut cmd)?;
760    }
761    if let Some((path, _)) = &target {
762        crate::build_target::command::configure(&mut cmd, path).map_err(resource)?;
763    } else if let Some(cache) = inv.cache_dir {
764        // Same directory the verify commands build into: one cache to prune,
765        // and the compile the seat pays for is the compile the gate reuses.
766        cmd.env("CARGO_TARGET_DIR", cache);
767    } else {
768        // `Command` inherits this process's environment by default, so
769        // simply not setting the variable here is not the same as the seat
770        // not seeing it: if the magi process itself is running under a
771        // shared `CARGO_TARGET_DIR` (the ordinary case), a read-only seat
772        // would otherwise inherit that exact path and try to build there
773        // anyway - the write refusal this is meant to prevent in the first
774        // place. Strip it explicitly.
775        cmd.env_remove("CARGO_TARGET_DIR");
776        cmd.env_remove("CARGO_BUILD_TARGET_DIR")
777            .env_remove("CARGO_BUILD_BUILD_DIR");
778    }
779
780    #[cfg(any(unix, windows))]
781    let _chat_controls = {
782        use crate::chat_control::bridge::{self, Bridge};
783        // Strip inherited and per-agent capabilities for every invocation,
784        // including external-chat; only an ordinary owner chat gets a new one.
785        bridge::clear_environment(&mut cmd);
786        if matches!(
787            crate::chat_goal::current_source(),
788            crate::chat_goal::Source::Standing(_)
789        ) {
790            cmd.env(crate::chat_control::standing::ENV, "1");
791        }
792        let bridge = if inv.node == crate::queue::CHAT_NODE {
793            crate::run::try_home().and_then(|home| {
794                match Bridge::start(&home, inv.run, inv.artifacts) {
795                    Ok(bridge) => Some(bridge),
796                    Err(error) => {
797                        tracing::warn!(%error, "chat controls unavailable; continuing conversation");
798                        None
799                    }
800                }
801            })
802        } else {
803            None
804        };
805        if let Some(bridge) = &bridge {
806            // Read-only chat CLIs also authorize against the launcher's talk
807            // store before dispatching through the bridge. Match its home
808            // without granting the child filesystem write access.
809            cmd.env("MAGI_HOME", std::fs::canonicalize(crate::run::home())?);
810            bridge.attach(&mut cmd);
811        }
812        bridge
813    };
814
815    let spawn = if build_guard.is_some() {
816        crate::seat_process::Running::spawn_build
817    } else {
818        crate::seat_process::Running::spawn
819    };
820    *spawn_attempted = true;
821    let spawned = spawn(cmd, lease, outputs)
822        .with_context(|| format!("spawn `{}` for seat {}", plan.argv[0], seat.key));
823    let mut running = if isolated.is_some() {
824        spawned.map_err(resource)?
825    } else {
826        spawned?
827    };
828    // Feed stdin from a task rather than inline: a `command` agent that never
829    // reads its stdin, or a prompt larger than the pipe buffer, would
830    // otherwise deadlock here before the process is ever waited on.
831    if let Some(body) = plan.stdin.clone()
832        && let Some(mut sink) = running.child().stdin.take()
833    {
834        tokio::spawn(async move {
835            sink.write_all(body.as_bytes()).await.ok();
836            sink.shutdown().await.ok();
837        });
838    }
839
840    // Drain the pipes in their own tasks, and wait on the *process*, not on
841    // end-of-file. Two failures come out of conflating those:
842    //
843    // 1. `wait_with_output` returns when both pipes reach EOF, which is not
844    //    when the child exits. A CLI that leaves a helper process holding the
845    //    inherited stdout handle - normal on Windows, where a `.cmd` shim and
846    //    its grandchildren share handles - never closes the pipe, so a seat
847    //    that answered in five minutes was billed the full hour and then
848    //    recorded as a timeout. The answer was thrown away with it.
849    // 2. Cancelling `wait_with_output` at the timeout drops the buffers it
850    //    owned, so `<stem>.out` and `<stem>.err` were written empty exactly
851    //    when an operator needs them most. "It printed nothing" and "we
852    //    discarded what it printed" looked identical on disk.
853    //
854    // Now the readers own the bytes, so a timeout keeps whatever arrived, and
855    // the wait ends at exit even if a stray handle stays open.
856    let (err_buf, err_reader) = drain(running.child().stderr.take());
857    // An RPC chat turn reads stdout through the protocol driver, which logs the
858    // frames the extraction below reads into the same kind of buffer. The
859    // driver is a future of this invocation, not a spawned task: a timeout,
860    // disk pressure or a cancelled caller drops it together with omp's pipes.
861    let (out_buf, out_reader, mut rpc_driver) = if plan.rpc {
862        let log: Captured = Arc::new(Mutex::new(Vec::new()));
863        let writer = running
864            .child()
865            .stdin
866            .take()
867            .context("omp rpc has no stdin")?;
868        let reader = running
869            .child()
870            .stdout
871            .take()
872            .context("omp rpc has no stdout")?;
873        let session = omp_session.clone().expect("omp rpc session");
874        let initial = seat.clone();
875        let driver = Box::pin(crate::omp_rpc::drive(
876            writer,
877            reader,
878            inv.prompt.to_owned(),
879            crate::omp_rpc::current(),
880            Arc::clone(&log),
881            move |reported| {
882                let mut checkpoint = initial.clone();
883                session.clone().record(&mut checkpoint, reported, true)?;
884                checkpoint.turns += 1;
885                Ok(checkpoint)
886            },
887        ));
888        (log, None, Some(driver))
889    } else {
890        let (buf, reader) = drain(running.child().stdout.take());
891        (buf, reader, None)
892    };
893    let mut rpc_outcome = None;
894
895    #[cfg(all(test, unix))]
896    let min_free = test_watchdog::floor(inv.run, min_free);
897    let mut paths = vec![inv.cwd.to_owned()];
898    if let Some(cache) = inv.cache_dir {
899        paths.push(cache.to_owned());
900    }
901    let mut pressure = None;
902    let waited = tokio::select! {
903        waited = tokio::time::timeout(inv.timeout, async {
904            let Some(driver) = rpc_driver.take() else {
905                return running.child().wait().await;
906            };
907            rpc_outcome = Some(driver.await);
908            // The driver closed omp's stdin; give the session time to dispose.
909            match tokio::time::timeout(RPC_EXIT_GRACE, running.child().wait()).await {
910                Ok(status) => status,
911                Err(_) => {
912                    running.child().kill().await?;
913                    running.child().wait().await
914                }
915            }
916        }) => Some(waited),
917        reason = crate::retention::emergency(paths, min_free, isolated.is_some()) => {
918            pressure = Some(reason);
919            None
920        }
921    };
922    let (code, timed_out) = match waited {
923        Some(Ok(res)) => {
924            let status = res.with_context(|| format!("wait for seat {}", seat.key))?;
925            (status.code(), false)
926        }
927        Some(Err(_)) | None => {
928            if let Some(reason) = &pressure {
929                tracing::warn!(seat = %seat.key, %reason, "agent execution interrupted");
930            } else {
931                tracing::warn!(seat = %seat.key, secs = inv.timeout.as_secs(), "agent timed out");
932            }
933            // Wait for CLI termination before releasing its repository lease.
934            if !running.coordinated() {
935                running
936                    .child()
937                    .kill()
938                    .await
939                    .context("stop timed-out seat")?;
940            }
941            (None, true)
942        }
943    };
944    running.finish().await;
945    drop(shared_guard);
946
947    // The child is gone either way, so the readers are bounded now. A grace
948    // window rather than an unbounded await: a surviving grandchild can still
949    // hold the write end open, and losing a few trailing bytes beats hanging
950    // the graph on a process we no longer control.
951    let stdout = collect(&out_buf, out_reader, PIPE_GRACE).await;
952    let mut stderr = collect(&err_buf, err_reader, PIPE_GRACE).await;
953    // A failed RPC turn says why on stderr, where a print-mode CLI would.
954    let mut rpc_quota = None;
955    let mut rpc_failed = false;
956    let mut rpc_answers = Vec::new();
957    let rpc_error = match rpc_outcome {
958        Some(Ok(ended)) => {
959            rpc_answers = ended.answers;
960            for notice in &ended.notices {
961                if !stderr.is_empty() {
962                    stderr.push('\n');
963                }
964                stderr.push_str(&format!("omp notice: {notice}"));
965            }
966            ended.error.map(|error| {
967                rpc_quota = omp_quota(&error);
968                format!("omp: {}", error.message)
969            })
970        }
971        Some(Err(error)) => Some(format!("{error:#}")),
972        None => None,
973    };
974    if let Some(error) = rpc_error {
975        if !stderr.is_empty() {
976            stderr.push('\n');
977        }
978        stderr.push_str(&error);
979        rpc_failed = true;
980    }
981
982    let out_path = inv.artifacts.join(format!("{}.out", inv.stem));
983    let err_path = inv.artifacts.join(format!("{}.err", inv.stem));
984    tokio::fs::write(&out_path, &stdout).await.ok();
985    tokio::fs::write(&err_path, &stderr).await.ok();
986    if let Some(reason) = pressure {
987        return Err(
988            anyhow::Error::new(crate::repo_lock::ResourceBlocked(reason.clone()))
989                .context(ExecutionInterrupted(reason)),
990        );
991    }
992
993    if code != Some(0)
994        && (stdout.contains(crate::incremental::BLOCKED)
995            || stderr.contains(crate::incremental::BLOCKED))
996    {
997        let detail = if stderr.contains(crate::incremental::BLOCKED) {
998            &stderr
999        } else {
1000            &stdout
1001        };
1002        return Err(crate::repo_lock::ResourceBlocked(tail_chars(detail, 2000)).into());
1003    }
1004
1005    let mut extracted = extract(spec.kind, &stdout);
1006    // A steered RPC turn answered several messages; the stream's last text
1007    // alone would drop the earlier answers.
1008    if rpc_answers.len() > 1 {
1009        extracted.text = rpc_answers.join("\n\n");
1010    }
1011    if spec.kind == AgentKind::Antigravity && extracted.quota.is_none() {
1012        extracted.quota = agy_quota(&stdout, &stderr);
1013    }
1014    if extracted.quota.is_none() {
1015        extracted.quota = rpc_quota;
1016    }
1017    // An error after a real answer still delivers that answer; without one,
1018    // the stderr explanation must not read as the agent's reply.
1019    let resident_failed = rpc_failed
1020        && plan.rpc
1021        && crate::omp_rpc::current().is_some_and(|hooks| hooks.resident.is_some());
1022    let code = if resident_failed || (rpc_failed && extracted.text.trim().is_empty()) {
1023        Some(1)
1024    } else {
1025        code
1026    };
1027    if let Some(quota) = &mut extracted.quota {
1028        quota.agent.clone_from(&spec.id);
1029        if quota.cause == QuotaCause::Authentication {
1030            let _ = crate::notices::Notices::open().raise(crate::notices::Notice::warn(
1031                &format!("agent-authentication:{}", spec.id),
1032                format!("Agent `{}` cannot authenticate. Re-authenticate this agent, then resume the held task.", spec.id),
1033            ));
1034        }
1035        // A quota response carries usage too, so it can look like a dropped
1036        // stream; a rate limit is never worth re-asking, so it wins.
1037        extracted.dropped = None;
1038        tracing::warn!(
1039            seat = %seat.key,
1040            agent = %spec.id,
1041            reset = ?quota.reset,
1042            cause = ?quota.cause,
1043            "agent needs machine-side recovery"
1044        );
1045    }
1046    if let Some(omp_session) = omp_session {
1047        omp_session.record(seat, extracted.session, code == Some(0))?;
1048    } else if let Some(session) = extracted.session {
1049        match spec.kind {
1050            AgentKind::Claude => seat.claude_session = Some(session),
1051            AgentKind::Opencode | AgentKind::Antigravity | AgentKind::Codex => {
1052                seat.captured_session = Some(session);
1053            }
1054            AgentKind::Command | AgentKind::Omp => {}
1055        }
1056    }
1057    if let Some(status) = &extracted.status
1058        && !status.eq_ignore_ascii_case("success")
1059    {
1060        tracing::warn!(seat = %seat.key, status = %status, "agent reported a non-success status");
1061    }
1062    let text = if resident_failed {
1063        stderr.trim().to_owned()
1064    } else if extracted.text.trim().is_empty() {
1065        // A CLI that printed only to stderr still told us something. An RPC
1066        // turn's stdout is the protocol log, never something to show.
1067        if plan.rpc || stdout.trim().is_empty() {
1068            stderr.trim().to_owned()
1069        } else {
1070            stdout.trim().to_owned()
1071        }
1072    } else {
1073        extracted.text
1074    };
1075    seat.turns += 1;
1076
1077    Ok(AgentOutput {
1078        text,
1079        exit_code: code,
1080        timed_out,
1081        duration_ms: started.elapsed().as_millis() as u64,
1082        artifacts: vec![
1083            file_name(&prompt_path),
1084            file_name(&out_path),
1085            file_name(&err_path),
1086        ],
1087        quota: extracted.quota,
1088        dropped: extracted.dropped,
1089        commands: extracted.commands,
1090        context_tokens: extracted.context_tokens,
1091        tool_calls: extracted.tool_calls,
1092    })
1093}
1094
1095fn file_name(p: &Path) -> String {
1096    p.file_name()
1097        .unwrap_or_default()
1098        .to_string_lossy()
1099        .into_owned()
1100}
1101
1102#[derive(Clone)]
1103enum OmpSession {
1104    Fresh(PathBuf),
1105    Resume,
1106}
1107
1108impl OmpSession {
1109    fn prepare(
1110        spec: &AgentSpec,
1111        seat: &SeatState,
1112        sessions: bool,
1113        home: impl FnOnce() -> PathBuf,
1114    ) -> Result<Self> {
1115        let resume = has_session(AgentKind::Omp, seat, sessions);
1116        if resume && seat.omp_session_dir.is_none() {
1117            // Preserve the old argv and config for sessions started before isolation.
1118            return Ok(Self::Resume);
1119        }
1120        for arg in &spec.extra_args {
1121            let flag = arg.split_once('=').map_or(arg.as_str(), |(flag, _)| flag);
1122            if matches!(
1123                flag,
1124                "--session-dir"
1125                    | "--no-session"
1126                    | "--resume"
1127                    | "--session"
1128                    | "--fork"
1129                    | "--restore"
1130                    | "--continue"
1131                    | "--from-claude"
1132                    | "--from-codex"
1133                    | "-r"
1134                    | "-c"
1135            ) {
1136                bail!("omp extra_args cannot set {flag} for isolated sessions");
1137            }
1138        }
1139        if resume {
1140            let dir = seat.omp_session_dir.as_ref().expect("managed resume");
1141            anyhow::ensure!(
1142                dir.is_absolute(),
1143                "saved omp session directory is not absolute"
1144            );
1145            std::fs::read_dir(dir)
1146                .with_context(|| format!("open saved omp session directory {}", dir.display()))?;
1147            return Ok(Self::Resume);
1148        }
1149
1150        let root = std::path::absolute(home().join("agent-sessions").join("omp"))
1151            .context("resolve absolute omp session store")?;
1152        // omp and the JSON seat store both require Unicode paths.
1153        anyhow::ensure!(
1154            root.to_str().is_some(),
1155            "omp session store is not valid Unicode"
1156        );
1157        std::fs::create_dir_all(&root)
1158            .with_context(|| format!("create omp session store {}", root.display()))?;
1159        let ids =
1160            crate::id_reserve::IdSource::new(|| SplitMix64::new(crate::rng::entropy()).uuid_v4());
1161        let id = ids.reserve(None, "omp session directory", |id| {
1162            crate::id_reserve::create_dir(&root.join(id))
1163        })?;
1164        Ok(Self::Fresh(root.join(id)))
1165    }
1166
1167    fn dir<'a>(&'a self, seat: &'a SeatState) -> Option<&'a Path> {
1168        match self {
1169            Self::Fresh(dir) => Some(dir),
1170            Self::Resume => seat.omp_session_dir.as_deref(),
1171        }
1172    }
1173
1174    fn isolate_terminal_history(&self, cmd: &mut Command, seat: &SeatState) {
1175        if self.dir(seat).is_none() {
1176            return;
1177        }
1178        // omp falls back to these identifiers even when stdin is piped.
1179        // Otherwise ordinary `omp --continue` can follow its terminal
1180        // breadcrumb outside the default session directory.
1181        for key in [
1182            "ZELLIJ_PANE_ID",
1183            "TMUX_PANE",
1184            "CMUX_SURFACE_ID",
1185            "KITTY_WINDOW_ID",
1186            "WEZTERM_PANE",
1187            "TERM_SESSION_ID",
1188            "WT_SESSION",
1189        ] {
1190            cmd.env_remove(key);
1191        }
1192    }
1193
1194    fn record(self, seat: &mut SeatState, reported: Option<String>, success: bool) -> Result<()> {
1195        let reported = reported.filter(|id| !id.is_empty());
1196        match self {
1197            Self::Resume if seat.omp_session_dir.is_none() => {
1198                // Legacy lookup can resolve a continuation with a new ID.
1199                if let Some(id) = reported {
1200                    seat.captured_session = Some(id);
1201                }
1202            }
1203            Self::Resume => {
1204                if let Some(id) = reported {
1205                    let previous = seat.captured_session.as_deref().expect("managed resume");
1206                    let dir = seat.omp_session_dir.as_deref().expect("managed resume");
1207                    if previous != id {
1208                        anyhow::ensure!(
1209                            omp_continues(dir, previous, &id)?,
1210                            "omp resumed a different session than requested"
1211                        );
1212                        seat.captured_session = Some(id);
1213                    }
1214                } else if success {
1215                    // An unsuccessful turn may exit before reporting an ID.
1216                    // Keep the saved pair and let the caller classify the output.
1217                    bail!("omp did not confirm the requested session; see the seat output");
1218                }
1219            }
1220            Self::Fresh(dir) => {
1221                if let Some(id) = reported {
1222                    seat.captured_session = Some(id);
1223                    seat.omp_session_dir = Some(dir);
1224                } else if success {
1225                    bail!("omp did not report a new session id; see the seat output");
1226                }
1227            }
1228        }
1229        Ok(())
1230    }
1231}
1232
1233/// A resume may move to a successor when omp cannot append to the old file.
1234/// Only accept lineage recorded by session headers in this seat's directory.
1235fn omp_continues(dir: &Path, previous: &str, reported: &str) -> Result<bool> {
1236    use std::io::{BufRead as _, BufReader, Read as _};
1237
1238    let mut parents = BTreeMap::new();
1239    let mut line = Vec::new();
1240    for entry in std::fs::read_dir(dir).context("read omp continuation directory")? {
1241        let entry = entry?;
1242        let path = entry.path();
1243        if path.extension() != Some(OsStr::new("jsonl")) || !entry.file_type()?.is_file() {
1244            continue;
1245        }
1246        line.clear();
1247        // The rest of the transcript is unrelated and can be arbitrarily large.
1248        BufReader::new(std::fs::File::open(path)?)
1249            .take(64 * 1024)
1250            .read_until(b'\n', &mut line)?;
1251        if !line.ends_with(b"\n") {
1252            continue;
1253        }
1254        let Ok(header) = serde_json::from_slice::<serde_json::Value>(&line) else {
1255            continue;
1256        };
1257        if header["type"].as_str() != Some("session") {
1258            continue;
1259        }
1260        if let Some(id) = header["id"].as_str() {
1261            let parent = header["continuationOf"].as_str().map(str::to_owned);
1262            if parents.insert(id.to_owned(), parent).is_some() {
1263                return Ok(false);
1264            }
1265        }
1266    }
1267
1268    let mut current = reported.to_owned();
1269    // Removing each visited ID also rejects cycles.
1270    while let Some(Some(parent)) = parents.remove(&current) {
1271        if parent == previous {
1272            return Ok(true);
1273        }
1274        current = parent;
1275    }
1276    Ok(false)
1277}
1278
1279/// The argv plus optional stdin body for one invocation.
1280#[derive(Debug)]
1281struct Plan {
1282    argv: Vec<String>,
1283    stdin: Option<String>,
1284    /// Speak omp's RPC protocol over stdin/stdout ([`crate::omp_rpc`]).
1285    rpc: bool,
1286}
1287
1288/// A chat turn on omp runs as an RPC session: streamed, steerable, stoppable.
1289fn omp_rpc_turn(spec: &AgentSpec, inv: &Invocation<'_>) -> bool {
1290    spec.kind == AgentKind::Omp && inv.node == crate::queue::CHAT_NODE
1291}
1292
1293/// Grace for omp to dispose its session after the driver closed stdin.
1294const RPC_EXIT_GRACE: Duration = Duration::from_secs(15);
1295
1296/// A usage limit or credential failure omp reported for a prompt.
1297fn omp_quota(error: &crate::omp_rpc::PromptError) -> Option<Quota> {
1298    let message = error.message.to_ascii_lowercase();
1299    let cause = if matches!(error.http_status, Some(401 | 403))
1300        || message.contains("authenticat")
1301        || message.contains("credential")
1302    {
1303        QuotaCause::Authentication
1304    } else if error.http_status == Some(429)
1305        || error.code.as_deref() == Some("cost_cap")
1306        || ["usage limit", "rate limit", "quota"]
1307            .iter()
1308            .any(|needle| message.contains(needle))
1309    {
1310        QuotaCause::UsageLimit
1311    } else {
1312        return None;
1313    };
1314    Some(Quota {
1315        cause,
1316        agent: String::new(),
1317        reset: None,
1318    })
1319}
1320
1321impl Plan {
1322    /// Keep the storage path one native argument, independent of the child cwd.
1323    fn args<'a>(&'a self, omp_dir: Option<&'a Path>) -> impl Iterator<Item = &'a OsStr> {
1324        omp_dir
1325            .into_iter()
1326            .flat_map(|dir| [OsStr::new("--session-dir"), dir.as_os_str()])
1327            .chain(self.argv[1..].iter().map(OsStr::new))
1328    }
1329
1330    /// Settings may have been loaded from a file containing credentials.
1331    /// Log the option, never its value, including repeated and equals forms.
1332    fn logged_argv(&self) -> Vec<&str> {
1333        let mut settings_value = false;
1334        self.argv
1335            .iter()
1336            .map(|arg| {
1337                if settings_value {
1338                    settings_value = false;
1339                    "[redacted]"
1340                } else if arg == "--settings" {
1341                    settings_value = true;
1342                    arg.as_str()
1343                } else if arg.starts_with("--settings=") {
1344                    "--settings=[redacted]"
1345                } else {
1346                    arg.as_str()
1347                }
1348            })
1349            .collect()
1350    }
1351}
1352
1353/// How a file-delivered prompt is pointed at, per CLI.
1354///
1355/// `agy` has a native file-context syntax, `@<path>`, and it is measurably the
1356/// better contract: on the same trivial task it finished in 17s against 73s for
1357/// the prose form, because prose makes the model spend a tool round-trip
1358/// deciding to read the file. It is also the form yukimemi/rvpm proved out.
1359///
1360/// opencode has no equivalent, so it gets the prose. That is not a fallback
1361/// worth apologising for — it works, and it is what the winning opencode
1362/// candidates on this repository have been driven by all along.
1363fn pointer(kind: AgentKind, prompt_path: &Path) -> String {
1364    if matches!(kind, AgentKind::Antigravity) {
1365        return format!("@{}", prompt_path.display());
1366    }
1367    format!(
1368        "Read the file at {} and follow every instruction in it exactly. That \
1369         file is your complete task description; this message contains nothing \
1370         else.",
1371        prompt_path.display()
1372    )
1373}
1374
1375fn build_command(
1376    spec: &AgentSpec,
1377    seat: &SeatState,
1378    inv: &Invocation<'_>,
1379    prompt_path: &Path,
1380) -> Result<Plan> {
1381    let mut argv: Vec<String> = Vec::new();
1382    let mut stdin: Option<String> = None;
1383    let rpc = omp_rpc_turn(spec, inv);
1384    let delivery = spec.delivery();
1385    let resuming = has_session(spec.kind, seat, inv.sessions);
1386
1387    match spec.kind {
1388        AgentKind::Claude => {
1389            // Claude's own tools have no cwd-confined sandbox - the CLI can
1390            // already `Read` any absolute path magi hands it, an attachment
1391            // outside the repository included - so no extra flag is needed
1392            // here.
1393            argv.push("claude".to_owned());
1394            argv.push("-p".to_owned());
1395            argv.push("--output-format".to_owned());
1396            argv.push("json".to_owned());
1397            if let Some(m) = &spec.model {
1398                argv.push("--model".to_owned());
1399                argv.push(m.clone());
1400            }
1401            if inv.sessions {
1402                let uuid = seat
1403                    .claude_session
1404                    .as_deref()
1405                    .context("claude seat is missing its session uuid")?;
1406                argv.push(if resuming { "--resume" } else { "--session-id" }.to_owned());
1407                argv.push(uuid.to_owned());
1408            }
1409            argv.push("--permission-mode".to_owned());
1410            argv.push("bypassPermissions".to_owned());
1411            if !inv.allow_write {
1412                argv.push("--disallowed-tools".to_owned());
1413                argv.push("Edit,Write,MultiEdit,NotebookEdit".to_owned());
1414            }
1415        }
1416        AgentKind::Opencode => {
1417            // `--auto` below already bypasses every permission, reads of a
1418            // path outside `--dir` included, so an attachment elsewhere
1419            // needs no extra flag.
1420            argv.push("opencode".to_owned());
1421            argv.push("run".to_owned());
1422            argv.push("--format".to_owned());
1423            argv.push("json".to_owned());
1424            argv.push("--dir".to_owned());
1425            argv.push(inv.cwd.to_string_lossy().into_owned());
1426            // `--auto` gates *every* permission, reads included: without it a
1427            // non-interactive opencode cannot even open the prompt file, and
1428            // the seat drops out of the panel with "the user rejected
1429            // permission to use this specific tool call". opencode has no
1430            // read-only mode, so read-only seats rely on the prompt plus the
1431            // fact that judge and reviewer worktrees are disposable — judges'
1432            // are deleted after the tally, reviewers' are reset to the commit
1433            // under review every round.
1434            argv.push("--auto".to_owned());
1435            if let Some(m) = &spec.model {
1436                argv.push("-m".to_owned());
1437                argv.push(m.clone());
1438            }
1439            if resuming {
1440                argv.push("-s".to_owned());
1441                argv.push(
1442                    seat.captured_session
1443                        .clone()
1444                        .expect("has_session checked the id is present"),
1445                );
1446            }
1447        }
1448        AgentKind::Antigravity => {
1449            argv.push("agy".to_owned());
1450            argv.push("--output-format".to_owned());
1451            argv.push("json".to_owned());
1452            // agy's print mode gives up after 5 minutes by default, which is
1453            // far below an implementation node's budget.
1454            argv.push("--print-timeout".to_owned());
1455            argv.push(format!("{}s", inv.timeout.as_secs()));
1456            argv.push("--mode".to_owned());
1457            argv.push(
1458                if inv.allow_write {
1459                    "accept-edits"
1460                } else {
1461                    "plan"
1462                }
1463                .to_owned(),
1464            );
1465            if inv.allow_write {
1466                argv.push("--dangerously-skip-permissions".to_owned());
1467            }
1468            if let Some(m) = &spec.model {
1469                argv.push("--model".to_owned());
1470                argv.push(m.clone());
1471            }
1472            if resuming {
1473                argv.push("--conversation".to_owned());
1474                argv.push(
1475                    seat.captured_session
1476                        .clone()
1477                        .expect("has_session checked the id is present"),
1478                );
1479            }
1480            // The prompt file lives outside the worktree, so the workspace has
1481            // to be widened to reach it - and so does an attachment's own
1482            // directory, which usually lives right beside it under the
1483            // conversation's `artifacts_dir` (see `chat`/`talk`). "Usually":
1484            // a chat derived from another one (`chat::derived_background`)
1485            // can carry attachment paths that live under the *source*
1486            // conversation's own artifacts dir instead, so each attachment
1487            // outside `inv.artifacts` gets its own `--add-dir` rather than
1488            // assuming one directory covers all of `inv.attachments`.
1489            let mut add_dirs: Vec<String> = Vec::new();
1490            if delivery == Delivery::File || !inv.attachments.is_empty() {
1491                add_dirs.push(inv.artifacts.to_string_lossy().into_owned());
1492            }
1493            for path in inv.attachments {
1494                let Some(parent) = path.parent() else {
1495                    continue;
1496                };
1497                if parent.starts_with(inv.artifacts) {
1498                    continue;
1499                }
1500                let dir = parent.to_string_lossy().into_owned();
1501                if !add_dirs.contains(&dir) {
1502                    add_dirs.push(dir);
1503                }
1504            }
1505            if inv.allow_write {
1506                for path in inv.writable {
1507                    let dir = path.to_string_lossy().into_owned();
1508                    if !add_dirs.contains(&dir) {
1509                        add_dirs.push(dir);
1510                    }
1511                }
1512            }
1513            for dir in add_dirs {
1514                argv.push("--add-dir".to_owned());
1515                argv.push(dir);
1516            }
1517        }
1518        AgentKind::Codex => {
1519            // `--sandbox` below governs writes, not reads (see the module
1520            // doc: it is what makes codex the one kind whose *read-only*
1521            // mode is enforced, by refusing edits) - both presets can read
1522            // anywhere the OS lets the process, so an attachment outside
1523            // `cwd` is already reachable without an extra flag.
1524            argv.push("codex".to_owned());
1525            argv.push("exec".to_owned());
1526            argv.push("--json".to_owned());
1527            // The worktrees magi hands out are real checkouts, but a judge's
1528            // is detached and a fixture's may be no repository at all.
1529            argv.push("--skip-git-repo-check".to_owned());
1530            argv.push("-C".to_owned());
1531            argv.push(inv.cwd.to_string_lossy().into_owned());
1532            // Codex is the only kind whose read-only-ness is enforced by the
1533            // CLI rather than by the prompt: a judge or reviewer seat cannot
1534            // write even if it decides to try. Repository editing seats
1535            // (implementer, fixer, grafter, gate fixer, land, rebase and an
1536            // authorized chat editing turn - see `repository_writer`) drop sandbox and
1537            // approvals altogether, as claude's `bypassPermissions` does: the
1538            // seatbelt sandbox refuses `$TMPDIR` and aborts Chrome, so the
1539            // repository's own tests could not run (owner decision
1540            // 2026-10-27). Every other seat keeps its sandbox.
1541            if repository_writer(inv) {
1542                argv.push("--dangerously-bypass-approvals-and-sandbox".to_owned());
1543            } else {
1544                argv.push("--sandbox".to_owned());
1545                argv.push(
1546                    if inv.allow_write {
1547                        "workspace-write"
1548                    } else {
1549                        "read-only"
1550                    }
1551                    .to_owned(),
1552                );
1553                // Nothing is watching to approve anything: an unattended seat
1554                // that asks blocks until its timeout kills it.
1555                argv.push("-c".to_owned());
1556                argv.push("approval_policy=\"never\"".to_owned());
1557                if inv.allow_write && !inv.writable.is_empty() {
1558                    let roots: Vec<String> = inv
1559                        .writable
1560                        .iter()
1561                        .map(|p| p.to_string_lossy().into_owned())
1562                        .collect();
1563                    argv.push("-c".to_owned());
1564                    argv.push(format!(
1565                        "sandbox_workspace_write.writable_roots={}",
1566                        serde_json::to_string(&roots).unwrap_or_else(|_| "[]".to_owned())
1567                    ));
1568                }
1569            }
1570            if let Some(m) = &spec.model {
1571                argv.push("-m".to_owned());
1572                argv.push(m.clone());
1573            }
1574            // `resume` is a subcommand of `exec`, and it rejects the flags
1575            // above when they follow it - so every option is emitted first and
1576            // the subcommand last. Established by hand against codex-cli
1577            // 0.153.4: with the order reversed the CLI exits on
1578            // `unexpected argument '--sandbox'`.
1579            if resuming {
1580                argv.push("resume".to_owned());
1581                argv.push(
1582                    seat.captured_session
1583                        .clone()
1584                        .expect("has_session checked the id is present"),
1585                );
1586            }
1587        }
1588        AgentKind::Omp => {
1589            // Print mode reads the prompt from stdin (see
1590            // `AgentSpec::delivery`); a chat turn speaks the RPC protocol
1591            // instead and sends the prompt as its first command.
1592            argv.push("omp".to_owned());
1593            if rpc {
1594                argv.push("--mode".to_owned());
1595                argv.push("rpc".to_owned());
1596            } else {
1597                argv.push("-p".to_owned());
1598                argv.push("--mode=json".to_owned());
1599            }
1600            // `--auto-approve` is required, and is the same trade opencode's
1601            // `--auto` makes: it gates *every* permission, reads included, so
1602            // without it a non-interactive seat cannot even open the prompt
1603            // file magi wrote and drops out of the panel on a permission
1604            // rejection. `omp` has no read-only mode of its own, so a judge or
1605            // reviewer seat rests on the prompt plus the worktree discipline
1606            // (judge worktrees are deleted after the tally, reviewer worktrees
1607            // are reset to the commit under review every round) - never on this
1608            // flag, and never on a bypass flag.
1609            argv.push("--auto-approve".to_owned());
1610            if let Some(m) = &spec.model {
1611                argv.push("--model".to_owned());
1612                argv.push(m.clone());
1613            }
1614            // Established by hand against omp 18.1.19: `-p --mode=json` reports
1615            // the session id on its `"type":"session"` line, and
1616            // `--resume <id>` continues that conversation. `--continue` is
1617            // deliberately not used - it opens a *new* session rather than the
1618            // stored one, which silently loses the seat's memory.
1619            if resuming {
1620                argv.push("--resume".to_owned());
1621                argv.push(
1622                    seat.captured_session
1623                        .clone()
1624                        .expect("has_session checked the id is present"),
1625                );
1626            }
1627        }
1628        AgentKind::Command => {
1629            // The operator's own command line, not one of the roster CLIs -
1630            // there is no flag this function could add on its behalf, so an
1631            // attachment's path has to reach it the same way the prompt
1632            // does, through the substitutions below.
1633            if spec.command.is_empty() {
1634                bail!("agent `{}` has kind = \"command\" but no command", spec.id);
1635            }
1636            let vars: BTreeMap<&str, String> = BTreeMap::from([
1637                ("{prompt_file}", prompt_path.to_string_lossy().into_owned()),
1638                ("{cwd}", inv.cwd.to_string_lossy().into_owned()),
1639                ("{label}", seat.key.clone()),
1640                ("{session}", seat.claude_session.clone().unwrap_or_default()),
1641            ]);
1642            for raw in &spec.command {
1643                let mut arg = raw.clone();
1644                for (k, v) in &vars {
1645                    if arg.contains(k) {
1646                        arg = arg.replace(k, v);
1647                    }
1648                }
1649                argv.push(arg);
1650            }
1651        }
1652    }
1653
1654    argv.extend(spec.extra_args.iter().cloned());
1655
1656    // `agy` takes the prompt as the value of `-p`, so the flag has to be
1657    // emitted right before whatever the delivery mode produces.
1658    if spec.kind == AgentKind::Antigravity {
1659        argv.push("-p".to_owned());
1660    }
1661    // `codex exec` reads stdin only when its prompt argument is `-`; without
1662    // it the CLI waits on a prompt it will never be given.
1663    if spec.kind == AgentKind::Codex && delivery == Delivery::Stdin {
1664        argv.push("-".to_owned());
1665    }
1666    match delivery {
1667        Delivery::Stdin if spec.kind == AgentKind::Antigravity => {
1668            // agy has no text stdin path; fall back to the pointer file.
1669            argv.push(pointer(spec.kind, prompt_path));
1670        }
1671        Delivery::Stdin if rpc => {}
1672        Delivery::Stdin => stdin = Some(inv.prompt.to_owned()),
1673        Delivery::Argv => argv.push(inv.prompt.to_owned()),
1674        Delivery::File => argv.push(pointer(spec.kind, prompt_path)),
1675    }
1676
1677    Ok(Plan { argv, stdin, rpc })
1678}
1679
1680/// What a CLI's stdout yielded.
1681#[derive(Debug, Default)]
1682struct Extracted {
1683    text: String,
1684    session: Option<String>,
1685    status: Option<String>,
1686    quota: Option<Quota>,
1687    dropped: Option<Dropped>,
1688    commands: Vec<CommandEvidence>,
1689    context_tokens: Option<u64>,
1690    tool_calls: Option<u64>,
1691}
1692
1693/// Pull the agent's message (and any session id) out of a CLI's stdout.
1694fn extract(kind: AgentKind, stdout: &str) -> Extracted {
1695    let mut extracted = extract_answer(kind, stdout);
1696    extracted.context_tokens = context_tokens(kind, stdout);
1697    extracted
1698}
1699
1700/// `v[key]` as an unsigned integer, or `None` when absent or not a number.
1701fn uint(v: &serde_json::Value, key: &str) -> Option<u64> {
1702    v.get(key).and_then(serde_json::Value::as_u64)
1703}
1704
1705/// The input side of a usage object: `input` plus whatever the cache served
1706/// or stored, each key read under the names the CLIs use. A missing cache
1707/// counter is 0 (the CLI simply had no cache traffic to report) but a missing
1708/// *input* counter makes the whole thing unknown - `None`, never a made-up 0.
1709fn input_side(usage: &serde_json::Value, input: &[&str], cache: &[&str]) -> Option<u64> {
1710    let first = |keys: &[&str]| keys.iter().find_map(|k| uint(usage, k));
1711    let base = first(input)?;
1712    let cached: u64 = cache.iter().filter_map(|k| uint(usage, k)).sum();
1713    Some(base.saturating_add(cached))
1714}
1715
1716/// The context size a CLI reported for its last turn: its input-side token
1717/// count, which approximates how much of the model's window the conversation
1718/// occupies. A pure function of stdout, so each CLI's shape is unit-testable.
1719///
1720/// Rules, all deliberate:
1721/// - **Last report wins, never a sum.** A multi-event stream (opencode's
1722///   `step_finish`, codex's `turn.completed`, omp's `message_end`) reports the
1723///   input of each model call; the final one is the largest context the
1724///   conversation reached this turn, and adding them would count the same
1725///   prefix once per tool round-trip.
1726/// - **Missing or mistyped usage is `None`**, which the UI shows as "unknown".
1727/// - **A cumulative total is not a context size, so it is `None`.** claude's
1728///   result `usage` sums every model call of the turn and, on a resumed
1729///   session, carries the session's earlier usage too, so even `num_turns == 1`
1730///   does not make it one call's context. codex's `turn.completed.usage` is the
1731///   session's running input total, and agy's `usage` aggregates the whole
1732///   print-mode call (the observed sample exceeds any window). None of the
1733///   three carries a per-call figure, so each is unknown rather than made up.
1734///   Only the streams that report each model call (opencode `step_finish`, omp
1735///   message usage) yield a number.
1736fn context_tokens(kind: AgentKind, stdout: &str) -> Option<u64> {
1737    use serde_json::Value;
1738    let lines = || {
1739        stdout
1740            .lines()
1741            .filter_map(|l| serde_json::from_str::<Value>(l.trim()).ok())
1742    };
1743    match kind {
1744        AgentKind::Claude => None,
1745        AgentKind::Opencode => lines()
1746            .filter(|v| {
1747                // The event is `step_finish`; its part is `step-finish`.
1748                v.get("type").and_then(|t| t.as_str()) == Some("step_finish")
1749                    || v.get("part")
1750                        .and_then(|p| p.get("type"))
1751                        .and_then(|t| t.as_str())
1752                        == Some("step-finish")
1753            })
1754            .filter_map(|v| {
1755                let tokens = v.get("part")?.get("tokens")?;
1756                let base = uint(tokens, "input")?;
1757                let cache = tokens.get("cache");
1758                let cached = ["read", "write"]
1759                    .iter()
1760                    .filter_map(|k| cache.and_then(|c| uint(c, k)))
1761                    .sum::<u64>();
1762                Some(base.saturating_add(cached))
1763            })
1764            .next_back(),
1765        AgentKind::Antigravity => None,
1766        AgentKind::Codex => None,
1767        AgentKind::Omp => lines()
1768            .flat_map(|v| {
1769                // Same walk as the answer: `agent_end` carries the thread,
1770                // `turn_end` / `message_end` one message each.
1771                match v.get("type").and_then(|t| t.as_str()) {
1772                    Some("agent_end") => v
1773                        .get("messages")
1774                        .and_then(|m| m.as_array())
1775                        .cloned()
1776                        .unwrap_or_default(),
1777                    Some("turn_end") | Some("message_end") => {
1778                        v.get("message").cloned().into_iter().collect()
1779                    }
1780                    _ => Vec::new(),
1781                }
1782            })
1783            .filter(|m| m.get("role").and_then(|r| r.as_str()) == Some("assistant"))
1784            .filter_map(|m| omp_message_context(&m))
1785            .next_back(),
1786        AgentKind::Command => None,
1787    }
1788}
1789
1790/// The input-side context one omp assistant message reports: the unit of
1791/// [`context_tokens`]' omp walk, read on its own by a resident chat session.
1792pub(crate) fn omp_message_context(message: &serde_json::Value) -> Option<u64> {
1793    input_side(
1794        message.get("usage")?,
1795        &["input", "input_tokens"],
1796        &[
1797            "cacheRead",
1798            "cacheWrite",
1799            "cache_read_tokens",
1800            "cache_write_tokens",
1801        ],
1802    )
1803}
1804
1805/// The answer text of a stored `<stem>.out`, through the same per-CLI
1806/// extraction a live call uses. Never the raw event stream.
1807pub(crate) fn answer_text(kind: AgentKind, stdout: &str) -> String {
1808    extract_answer(kind, stdout).text
1809}
1810
1811fn extract_answer(kind: AgentKind, stdout: &str) -> Extracted {
1812    match kind {
1813        AgentKind::Claude => {
1814            let Ok(v) = serde_json::from_str::<serde_json::Value>(stdout.trim()) else {
1815                return Extracted {
1816                    text: stdout.trim().to_owned(),
1817                    ..Extracted::default()
1818                };
1819            };
1820            Extracted {
1821                text: v
1822                    .get("result")
1823                    .and_then(|r| r.as_str())
1824                    .unwrap_or_default()
1825                    .to_owned(),
1826                session: v
1827                    .get("session_id")
1828                    .and_then(|s| s.as_str())
1829                    .map(str::to_owned),
1830                status: v.get("is_error").and_then(|e| e.as_bool()).map(|e| {
1831                    if e {
1832                        "error".to_owned()
1833                    } else {
1834                        "success".to_owned()
1835                    }
1836                }),
1837                quota: claude_quota(&v),
1838                // Claude reports a truncated stream as an ordinary error; the
1839                // shape `dropped_stream` keys on is agy's.
1840                dropped: None,
1841                commands: Vec::new(),
1842                context_tokens: None,
1843                tool_calls: None,
1844            }
1845        }
1846        AgentKind::Opencode => {
1847            // A JSONL event stream: text parts concatenated in arrival order.
1848            let mut text = String::new();
1849            let mut session = None;
1850            for line in stdout.lines() {
1851                let Ok(v) = serde_json::from_str::<serde_json::Value>(line.trim()) else {
1852                    continue;
1853                };
1854                if session.is_none() {
1855                    session = v
1856                        .get("sessionID")
1857                        .and_then(|s| s.as_str())
1858                        .map(str::to_owned);
1859                }
1860                let part = v.get("part").unwrap_or(&serde_json::Value::Null);
1861                if part.get("type").and_then(|t| t.as_str()) == Some("text")
1862                    && let Some(t) = part.get("text").and_then(|t| t.as_str())
1863                {
1864                    if !text.is_empty() {
1865                        text.push('\n');
1866                    }
1867                    text.push_str(t);
1868                }
1869            }
1870            Extracted {
1871                text,
1872                session,
1873                status: None,
1874                quota: None,
1875                dropped: None,
1876                commands: Vec::new(),
1877                context_tokens: None,
1878                tool_calls: None,
1879            }
1880        }
1881        AgentKind::Antigravity => {
1882            // agy prints warnings before the JSON object, so parse the last
1883            // line that is one rather than the whole stream.
1884            let obj = stdout
1885                .lines()
1886                .rev()
1887                .find_map(|l| serde_json::from_str::<serde_json::Value>(l.trim()).ok());
1888            let Some(v) = obj else {
1889                return Extracted {
1890                    text: stdout.trim().to_owned(),
1891                    ..Extracted::default()
1892                };
1893            };
1894            Extracted {
1895                text: v
1896                    .get("response")
1897                    .and_then(|r| r.as_str())
1898                    .unwrap_or_default()
1899                    .trim()
1900                    .to_owned(),
1901                session: v
1902                    .get("conversation_id")
1903                    .and_then(|s| s.as_str())
1904                    .map(str::to_owned),
1905                status: v.get("status").and_then(|s| s.as_str()).map(str::to_owned),
1906                quota: None,
1907                dropped: dropped_stream(&v),
1908                commands: Vec::new(),
1909                context_tokens: None,
1910                tool_calls: None,
1911            }
1912        }
1913        AgentKind::Codex => {
1914            // A JSONL event stream, prefixed on a real machine by tracing
1915            // lines the CLI writes about its own config and skills - so
1916            // non-JSON lines are skipped rather than treated as the answer.
1917            //
1918            // The thread id arrives once, in `thread.started`, and a resumed
1919            // turn reports the same one. The answer is the last
1920            // `item.completed` carrying an `agent_message`: earlier ones are
1921            // the model narrating its way through the tool loop, and taking
1922            // the first would hand the caller a progress note instead of a
1923            // verdict.
1924            //
1925            // A `command_execution` item is different evidence entirely: the
1926            // CLI's own record that it ran a command and what that command
1927            // reported back, kept as `CommandEvidence` — see run
1928            // 20260912-214939-b3bb's artifacts, where these very fields
1929            // (`id`/`command`/`exit_code`/`aggregated_output`) were what
1930            // caught a paired test result magi's own agent prose had missed.
1931            // Only what `item.completed` actually reports: a command still
1932            // running when the turn ended emits no such event at all, and is
1933            // not something this can detect — see [`CommandEvidence`]'s own
1934            // doc for why that must not be guessed at instead.
1935            let mut text = String::new();
1936            let mut session = None;
1937            let mut status = None;
1938            let mut commands = Vec::new();
1939            for line in stdout.lines() {
1940                let Ok(v) = serde_json::from_str::<serde_json::Value>(line.trim()) else {
1941                    continue;
1942                };
1943                match v.get("type").and_then(|t| t.as_str()) {
1944                    Some("thread.started") => {
1945                        session = v
1946                            .get("thread_id")
1947                            .and_then(|s| s.as_str())
1948                            .map(str::to_owned);
1949                    }
1950                    Some("item.completed") => {
1951                        let item = v.get("item").unwrap_or(&serde_json::Value::Null);
1952                        match item.get("type").and_then(|t| t.as_str()) {
1953                            Some("agent_message") => {
1954                                if let Some(t) = item.get("text").and_then(|t| t.as_str()) {
1955                                    text = t.trim().to_owned();
1956                                }
1957                            }
1958                            Some("command_execution") => {
1959                                commands.push(command_evidence(item));
1960                            }
1961                            _ => {}
1962                        }
1963                    }
1964                    Some("turn.completed") => status = Some("success".to_owned()),
1965                    Some("turn.failed") => status = Some("error".to_owned()),
1966                    _ => {}
1967                }
1968            }
1969            Extracted {
1970                text,
1971                session,
1972                status,
1973                quota: codex_quota(stdout),
1974                dropped: None,
1975                commands,
1976                context_tokens: None,
1977                tool_calls: None,
1978            }
1979        }
1980        AgentKind::Omp => {
1981            // A JSONL event stream. The session id arrives once, on the
1982            // `"type":"session"` line that opens the run.
1983            //
1984            // The answer is the *last* non-empty assistant text block anywhere
1985            // in the stream, and neither of the two obvious shortcuts works:
1986            //
1987            // 1. Do not key on `agent_end`. `omp` emits it only for a run that
1988            //    quiesces on a message turn; a turn that ends on a tool call
1989            //    (`stopReason: "toolUse"`) ends the run with **no `agent_end`
1990            //    line at all**, and the answer is in `message_end` / `turn_end`
1991            //    instead. Reading only `agent_end` silently discards a complete
1992            //    review - which is exactly what the first hand-written wrapper
1993            //    did, three times, before this arm existed.
1994            // 2. Do not take the first assistant text. Earlier ones narrate the
1995            //    tool loop (sometimes with a single `.`), so the last non-empty
1996            //    block is the answer and the one before it is a progress note.
1997            //
1998            // Every line is parsed independently: a non-JSON line (a CLI
1999            // warning, a truncated write) is skipped rather than treated as the
2000            // answer, the same way the codex arm treats its tracing prefix.
2001            let mut text = String::new();
2002            let mut session = None;
2003            // Tool activity is read from two records, because a stream can
2004            // lack either: the execution events, and the tool-call parts of
2005            // the assistant messages. The parts are summed per event type,
2006            // since `agent_end` / `turn_end` repeat what `message_end` said.
2007            let mut tool_starts = 0u64;
2008            let mut tool_parts = [0u64; 3];
2009            let mut answered = false;
2010            for line in stdout.lines() {
2011                let Ok(v) = serde_json::from_str::<serde_json::Value>(line.trim()) else {
2012                    continue;
2013                };
2014                let event = v.get("type").and_then(|t| t.as_str());
2015                if event == Some("session") {
2016                    session = v.get("id").and_then(|s| s.as_str()).map(str::to_owned);
2017                    continue;
2018                }
2019                if event == Some("tool_execution_start") {
2020                    tool_starts += 1;
2021                    continue;
2022                }
2023                // `agent_end` carries the whole thread; `turn_end` and
2024                // `message_end` each carry one message. Whichever appears, the
2025                // messages are walked the same way.
2026                let (messages, echo): (Vec<&serde_json::Value>, usize) = match event {
2027                    Some("agent_end") => (
2028                        v.get("messages")
2029                            .and_then(|m| m.as_array())
2030                            .map(|m| m.iter().collect())
2031                            .unwrap_or_default(),
2032                        0,
2033                    ),
2034                    Some("turn_end") => (v.get("message").into_iter().collect(), 1),
2035                    Some("message_end") => (v.get("message").into_iter().collect(), 2),
2036                    _ => continue,
2037                };
2038                for message in messages {
2039                    if message.get("role").and_then(|r| r.as_str()) != Some("assistant") {
2040                        continue;
2041                    }
2042                    let Some(parts) = message.get("content").and_then(|c| c.as_array()) else {
2043                        continue;
2044                    };
2045                    answered = true;
2046                    for part in parts {
2047                        match part.get("type").and_then(|t| t.as_str()) {
2048                            Some("toolCall") => tool_parts[echo] += 1,
2049                            Some("text") => {
2050                                if let Some(t) = part.get("text").and_then(|t| t.as_str())
2051                                    && !t.trim().is_empty()
2052                                {
2053                                    text = t.trim().to_owned();
2054                                }
2055                            }
2056                            _ => {}
2057                        }
2058                    }
2059                }
2060            }
2061            let tool_parts = tool_parts.into_iter().max().unwrap_or(0);
2062            Extracted {
2063                text,
2064                session,
2065                status: None,
2066                quota: None,
2067                dropped: None,
2068                commands: Vec::new(),
2069                context_tokens: None,
2070                // Only a stream that carried an assistant message says
2071                // anything about tools; an unread one stays unknown.
2072                tool_calls: answered.then(|| tool_starts.max(tool_parts)),
2073            }
2074        }
2075        AgentKind::Command => {
2076            // A `command` wrapper or fixture may relay an `omp --mode=json`
2077            // stream as it is. Nothing else opens with omp's session line, so
2078            // such a stream is read the way omp's own is; left as text, the
2079            // whole event log would stand as the answer.
2080            if relays_omp_stream(stdout) {
2081                return extract_answer(AgentKind::Omp, stdout);
2082            }
2083            // A `command` agent may wrap a subscription CLI (a fixture, or a
2084            // thin shim around `claude`). If its output is the claude error
2085            // shape we recognise the quota the same way, so tests and wrappers
2086            // do not need their own detection; anything else is just text.
2087            let parsed = serde_json::from_str::<serde_json::Value>(stdout.trim()).ok();
2088            let quota = parsed.as_ref().and_then(claude_quota);
2089            // A `command` fixture may also stand in for a CLI that hangs up on
2090            // its own stream, which is how that path is tested.
2091            let dropped = parsed.as_ref().and_then(dropped_stream);
2092            Extracted {
2093                text: stdout.trim().to_owned(),
2094                session: None,
2095                status: None,
2096                quota,
2097                dropped,
2098                commands: Vec::new(),
2099                context_tokens: None,
2100                tool_calls: None,
2101            }
2102        }
2103    }
2104}
2105
2106/// Does this stdout open with the session line of an `omp --mode=json` stream?
2107fn relays_omp_stream(stdout: &str) -> bool {
2108    stdout
2109        .lines()
2110        .map(str::trim)
2111        .find(|l| !l.is_empty())
2112        .and_then(|l| serde_json::from_str::<serde_json::Value>(l).ok())
2113        .is_some_and(|v| {
2114            v.get("type").and_then(|t| t.as_str()) == Some("session")
2115                && v.get("id").is_some_and(serde_json::Value::is_string)
2116        })
2117}
2118
2119/// Build one [`CommandEvidence`] from a Codex `command_execution` item.
2120///
2121/// `command` arrives either as a single string or as an argv array,
2122/// depending on how the CLI shaped the call; both are read rather than
2123/// assuming one. Missing fields are left at their honest defaults (an empty
2124/// id/description, `exit_code: None`) rather than guessed at.
2125fn command_evidence(item: &serde_json::Value) -> CommandEvidence {
2126    let description = match item.get("command") {
2127        Some(serde_json::Value::String(s)) => s.clone(),
2128        Some(serde_json::Value::Array(parts)) => parts
2129            .iter()
2130            .filter_map(|p| p.as_str())
2131            .collect::<Vec<_>>()
2132            .join(" "),
2133        _ => String::new(),
2134    };
2135    let result_summary = item
2136        .get("aggregated_output")
2137        .and_then(|o| o.as_str())
2138        .map(|s| tail_chars(s.trim(), 400))
2139        .unwrap_or_default();
2140    CommandEvidence {
2141        id: item
2142            .get("id")
2143            .and_then(|s| s.as_str())
2144            .unwrap_or_default()
2145            .to_owned(),
2146        description,
2147        exit_code: item
2148            .get("exit_code")
2149            .and_then(serde_json::Value::as_i64)
2150            .map(|e| e as i32),
2151        result_summary,
2152        source: "codex".to_owned(),
2153    }
2154}
2155
2156/// The last `max` characters of `s`, cut on a char boundary.
2157fn tail_chars(s: &str, max: usize) -> String {
2158    let count = s.chars().count();
2159    if count <= max {
2160        return s.to_owned();
2161    }
2162    s.chars().skip(count - max).collect()
2163}
2164
2165/// Require both the observed top-level limit event and a failed turn. Text
2166/// inside an assistant message is never evidence of an outage.
2167fn codex_quota(stdout: &str) -> Option<Quota> {
2168    let mut message = None;
2169    let mut failed = false;
2170    for line in stdout.lines() {
2171        let Ok(v) = serde_json::from_str::<serde_json::Value>(line) else {
2172            continue;
2173        };
2174        match v.get("type").and_then(serde_json::Value::as_str) {
2175            Some("error") => {
2176                if let Some(m) = v.get("message").and_then(serde_json::Value::as_str)
2177                    && m.starts_with("You've hit your usage limit. Visit https://chatgpt.com/settings/usage to purchase more credits")
2178                {
2179                    message = Some(m.to_owned());
2180                }
2181            }
2182            Some("turn.failed") => failed = true,
2183            _ => {}
2184        }
2185    }
2186    if !failed {
2187        return None;
2188    }
2189    let message = message?;
2190    Some(Quota {
2191        reset: message
2192            .split_once("try again at ")
2193            .map(|(_, hint)| hint.trim().trim_end_matches('.').trim().to_owned())
2194            .filter(|hint| !hint.is_empty()),
2195        cause: QuotaCause::UsageLimit,
2196        agent: String::new(),
2197    })
2198}
2199
2200/// Recognise claude's usage-limit and expired OAuth error shapes, when it is present.
2201///
2202/// Recognises `is_error: true` with a session-limit result or the structured
2203/// pair `api_error_status: 429` (number or string), `api_error: usage_limit_reached`;
2204/// also accepts the observed api_error result for an expired OAuth session.
2205/// Unknown error shapes remain ordinary failures.
2206fn claude_quota(v: &serde_json::Value) -> Option<Quota> {
2207    let is_err = v.get("is_error").and_then(|e| e.as_bool()).unwrap_or(false);
2208    if !is_err {
2209        return None;
2210    }
2211    let result = v.get("result").and_then(|r| r.as_str()).unwrap_or("");
2212    if v.get("terminal_reason").and_then(serde_json::Value::as_str) == Some("api_error")
2213        && result.starts_with("Failed to authenticate:")
2214        && result.contains("OAuth session expired and could not be refreshed")
2215    {
2216        return Some(Quota {
2217            reset: None,
2218            cause: QuotaCause::Authentication,
2219            agent: String::new(),
2220        });
2221    }
2222    let status = v.get("api_error_status");
2223    let usage_limit = (status.and_then(serde_json::Value::as_u64) == Some(429)
2224        || status.and_then(serde_json::Value::as_str) == Some("429"))
2225        && v.get("api_error").and_then(serde_json::Value::as_str) == Some("usage_limit_reached");
2226    if !usage_limit && !result.to_lowercase().contains("session limit") {
2227        return None;
2228    }
2229    // "…session limit · resets 4:50am (Asia/Tokyo)". The timezone read is not
2230    // worth parsing exactly; keep the whole phrase after "resets" as free text.
2231    let reset = result
2232        .split("resets ")
2233        .nth(1)
2234        .map(str::trim)
2235        .filter(|s| !s.is_empty())
2236        .map(str::to_owned);
2237    Some(Quota {
2238        reset,
2239        cause: QuotaCause::UsageLimit,
2240        agent: String::new(),
2241    })
2242}
2243
2244/// Recognise `agy` running out of quota, from either stream.
2245///
2246/// Observed shape while out of quota: stdout carries the JSON object
2247/// `{"status":"ERROR","response":"","error":"Individual quota reached. … Resets
2248/// in 1h2m49s."}` and stderr carries `AGY_ERROR: {"status":"RESOURCE_EXHAUSTED",
2249/// "error_code":429,…}`. Either alone is enough (a mangled stdout must not hide
2250/// a quota that stderr states plainly), but each is keyed on a *pair* of
2251/// structured fields: `status: ERROR` with the quota text, or
2252/// `RESOURCE_EXHAUSTED` together with 429. An error status alone, or a 429
2253/// alone, stays an ordinary failure - the conservative side, as for
2254/// [`claude_quota`].
2255///
2256/// The reset hint is what follows `Resets ` (e.g. `in 1h2m49s`), trailing full
2257/// stop dropped.
2258fn agy_quota(stdout: &str, stderr: &str) -> Option<Quota> {
2259    let from_stdout = stdout
2260        .lines()
2261        .rev()
2262        .find_map(|l| serde_json::from_str::<serde_json::Value>(l.trim()).ok())
2263        .and_then(|v| {
2264            let status = v.get("status").and_then(|s| s.as_str()).unwrap_or("");
2265            let error = v.get("error").and_then(|e| e.as_str()).unwrap_or("");
2266            (status.eq_ignore_ascii_case("error") && error.to_lowercase().contains("quota reached"))
2267                .then(|| error.to_owned())
2268        });
2269    let from_stderr = || {
2270        stderr.lines().find_map(|l| {
2271            let v: serde_json::Value =
2272                serde_json::from_str(l.trim().strip_prefix("AGY_ERROR:")?.trim()).ok()?;
2273            let exhausted = v.get("status").and_then(|s| s.as_str()) == Some("RESOURCE_EXHAUSTED");
2274            let code = v.get("error_code").and_then(serde_json::Value::as_u64) == Some(429);
2275            (exhausted && code).then(|| {
2276                v.get("short_error")
2277                    .and_then(|e| e.as_str())
2278                    .unwrap_or_default()
2279                    .to_owned()
2280            })
2281        })
2282    };
2283    let text = from_stdout.or_else(from_stderr)?;
2284    let reset = text
2285        .split_once("Resets ")
2286        .map(|(_, rest)| rest.trim().trim_end_matches('.').trim())
2287        .filter(|s| !s.is_empty())
2288        .map(str::to_owned);
2289    Some(Quota {
2290        reset,
2291        cause: QuotaCause::UsageLimit,
2292        agent: String::new(),
2293    })
2294}
2295
2296/// Recognise a CLI that gave up on its own stream while the agent was working.
2297///
2298/// Observed once, verbatim, from `agy` on a candidate that produced nothing:
2299///
2300/// ```text
2301/// {"conversation_id":"36743d06-…","status":"ERROR","response":"",
2302///  "error":"the connection to the agent was interrupted before the response
2303///           finished: subscriber fell behind updates, stalled for 5s",
2304///  "duration_seconds":431.19,"num_turns":1,
2305///  "usage":{"input_tokens":260113,"output_tokens":14267,
2306///           "thinking_tokens":9695,"cache_read_tokens":2200925}}
2307/// ```
2308///
2309/// Seven minutes of work and fourteen thousand output tokens, billed, with an
2310/// empty `response`: the agent did the job and the CLI's own subscriber fell
2311/// behind and hung up. That is **not** an agent that failed to implement, and
2312/// counting it as one is how `agy` came to read as 0 wins in 4 entries with
2313/// five empty candidates - a number that has twice been used to argue the seat
2314/// out of the roster, and twice been wrong (see `cb6b830`, which reverted the
2315/// first removal: *"agy does not fail to implement, it fails to report"*).
2316///
2317/// The distinction that matters is **billed work with nothing delivered**, so
2318/// that is what this keys on: an error status, an empty response, and a usage
2319/// report showing output tokens. Everything else - including an error with no
2320/// usage at all - returns `None` and stays an ordinary failure, the
2321/// conservative side, exactly as [`claude_quota`] treats shapes it does not
2322/// recognise.
2323///
2324/// Unlike a quota, this **is** worth re-asking: the work exists in the
2325/// conversation the CLI just abandoned, and `conversation_id` is right there.
2326fn dropped_stream(v: &serde_json::Value) -> Option<Dropped> {
2327    let status = v.get("status").and_then(|s| s.as_str()).unwrap_or("");
2328    if !status.eq_ignore_ascii_case("error") {
2329        return None;
2330    }
2331    let response = v.get("response").and_then(|r| r.as_str()).unwrap_or("");
2332    if !response.trim().is_empty() {
2333        // It answered. Whatever the status says, there is something to read.
2334        return None;
2335    }
2336    let produced = v
2337        .get("usage")
2338        .and_then(|u| u.get("output_tokens"))
2339        .and_then(serde_json::Value::as_u64)
2340        .unwrap_or(0);
2341    if produced == 0 {
2342        // An error with nothing produced is just an error.
2343        return None;
2344    }
2345    Some(Dropped {
2346        why: v
2347            .get("error")
2348            .and_then(|e| e.as_str())
2349            .unwrap_or("the CLI ended the stream without delivering its answer")
2350            .trim()
2351            .to_owned(),
2352        output_tokens: produced,
2353    })
2354}
2355
2356/// Preflight: which configured agents are not runnable here?
2357pub fn missing_programs(specs: &[AgentSpec]) -> Vec<String> {
2358    let mut missing = Vec::new();
2359    for s in specs {
2360        let program = match s.kind {
2361            AgentKind::Command => s.command.first().map(String::as_str),
2362            other => other.program(),
2363        };
2364        if let Some(p) = program
2365            && !crate::config::which(p)
2366            && !Path::new(p).is_file()
2367            && !missing.iter().any(|m: &String| m == p)
2368        {
2369            missing.push(p.to_owned());
2370        }
2371    }
2372    missing
2373}
2374
2375/// Absolute path of a run's artifact directory.
2376pub fn artifacts_dir(run_dir: &Path) -> PathBuf {
2377    run_dir.join("artifacts")
2378}
2379
2380/// Can this agent's CLI actually be run on this machine?
2381pub fn installed(spec: &AgentSpec) -> bool {
2382    // A `command` agent has no program of its own to look for - its argv is the
2383    // operator's, and they are the authority on whether it runs.
2384    spec.kind.program().is_none_or(crate::config::which)
2385}
2386
2387/// Choose the agent for a seat that stands alone rather than rotating through
2388/// the roster: [`crate::talk`]'s standing conversation,
2389/// or anything else that needs one agent picked once
2390/// rather than a panel filled in.
2391///
2392/// `available` is a parameter rather than a call to [`installed`] so the order
2393/// below is assertable on a machine with none of these CLIs installed, which is
2394/// every CI runner.
2395///
2396/// The order, and why:
2397///
2398/// 1. An explicit id always wins, and is an error rather than a fallback when
2399///    it is unusable. Naming a seat has a reason, and silently substituting a
2400///    different model would waste whatever that reason was.
2401/// 2. Otherwise a [`AgentKind::Claude`] seat, ahead of the roster order: it is
2402///    the only one of the three CLIs magi can address before the first turn
2403///    (see this module's own doc on session mechanics), which matters most for
2404///    a conversation that opens with nothing typed yet.
2405/// 3. Otherwise the first runnable agent in roster order, because the roster
2406///    order is the operator's own stated preference and magi has nothing
2407///    better to go on.
2408pub fn pick(
2409    agents: &[AgentSpec],
2410    want: Option<&str>,
2411    available: &dyn Fn(&AgentSpec) -> bool,
2412) -> Result<AgentSpec> {
2413    if let Some(id) = want {
2414        let spec = agents
2415            .iter()
2416            .find(|a| a.id == id)
2417            .with_context(|| format!("no agent `{id}` in the roster; it has {}", ids(agents)))?;
2418        if !available(spec) {
2419            bail!(
2420                "agent `{}` needs `{}` on PATH; install it or pass a different \
2421                 --agent",
2422                spec.id,
2423                spec.kind.program().unwrap_or("its command")
2424            );
2425        }
2426        return Ok(spec.clone());
2427    }
2428
2429    if agents.is_empty() {
2430        bail!(
2431            "the agent roster is empty, so there is nobody to ask: install one \
2432             of claude, opencode or agy - magi derives a roster from what is on \
2433             PATH - or add an [[agents]] entry to magi.toml."
2434        );
2435    }
2436
2437    if let Some(spec) = agents
2438        .iter()
2439        .find(|a| a.kind == AgentKind::Claude && available(a))
2440    {
2441        return Ok(spec.clone());
2442    }
2443
2444    agents
2445        .iter()
2446        .find(|a| available(a))
2447        .cloned()
2448        .with_context(|| {
2449            let missing = agents
2450                .iter()
2451                .filter_map(|a| a.kind.program())
2452                .collect::<Vec<_>>()
2453                .join(", ");
2454            format!(
2455                "no agent in the roster can be run here: install one of \
2456                 {missing}, or add an [[agents]] entry to magi.toml for a CLI \
2457                 you do have"
2458            )
2459        })
2460}
2461
2462/// `spec` for a seat whose answer is posted to GitHub (a pull request title or
2463/// description, a release reason), so the answer comes back in
2464/// `github_language` whatever language the operator set for their own CLI.
2465///
2466/// claude applies the user-level `language` setting (`"language": "Japanese"`
2467/// in `~/.claude/settings.json`) over a sentence in the prompt: the change
2468/// summary prompt said "Write ... in English" and the description came back in
2469/// Japanese, three times out of three when replayed, and in English every time
2470/// with this override. A per-invocation `--settings` outranks the user file, so
2471/// it is the CLI's own mechanism rather than more prompt wording. The other
2472/// CLIs have no operator-level answer-language preference magi knows of and
2473/// are returned unchanged.
2474pub fn for_github_text(spec: &AgentSpec, github_language: &str, cwd: &Path) -> Result<AgentSpec> {
2475    let mut spec = spec.clone();
2476    if spec.kind == AgentKind::Claude {
2477        // The CLI uses the last --settings value. Replace that value in
2478        // place, preserving its settings and the precedence of earlier flags.
2479        let mut existing = None;
2480        let mut args = spec.extra_args.iter().enumerate();
2481        while let Some((index, arg)) = args.next() {
2482            if arg == "--settings" {
2483                let (value_index, value) = args.next().context("--settings requires a value")?;
2484                existing = Some((value_index, value.as_str(), false));
2485            } else if let Some(value) = arg.strip_prefix("--settings=") {
2486                existing = Some((index, value, true));
2487            }
2488        }
2489        let mut settings = if let Some((_, value, _)) = existing {
2490            let json = if value.trim_start().starts_with('{') {
2491                value.to_owned()
2492            } else {
2493                std::fs::read_to_string(cwd.join(value))
2494                    .context("cannot read existing seat --settings file")?
2495            };
2496            serde_json::from_str::<serde_json::Value>(&json)
2497                .context("cannot parse existing seat --settings JSON")?
2498        } else {
2499            serde_json::json!({})
2500        };
2501        settings
2502            .as_object_mut()
2503            .context("seat --settings must be a JSON object")?
2504            .insert(
2505                "language".to_owned(),
2506                serde_json::json!(crate::lang::name(github_language)),
2507            );
2508        let settings = settings.to_string();
2509        if let Some((index, _, equals)) = existing {
2510            spec.extra_args[index] = if equals {
2511                format!("--settings={settings}")
2512            } else {
2513                settings
2514            };
2515        } else {
2516            spec.extra_args.extend(["--settings".to_owned(), settings]);
2517        }
2518    }
2519    Ok(spec)
2520}
2521
2522/// Resolve a standalone seat's agent choice into the ordered chain to try.
2523///
2524/// Unset (or empty) is [`pick`]'s default order, one entry. Otherwise each
2525/// named id is kept at its first appearance only - that is what bounds a
2526/// chain to one attempt per agent - and an id that is not in the roster or
2527/// not installed is skipped with a warning rather than failing the chain.
2528/// Errors, naming `role`, only when nothing resolves.
2529pub fn pick_chain(
2530    agents: &[AgentSpec],
2531    choice: Option<&AgentChoice>,
2532    available: &dyn Fn(&AgentSpec) -> bool,
2533    role: &str,
2534) -> Result<Vec<AgentSpec>> {
2535    let wanted = choice.map(AgentChoice::ids).unwrap_or_default();
2536    if wanted.is_empty() {
2537        return pick(agents, None, available)
2538            .map(|s| vec![s])
2539            .with_context(|| format!("choose an agent for the {role} role"));
2540    }
2541    let mut chain: Vec<AgentSpec> = Vec::new();
2542    for id in wanted {
2543        if chain.iter().any(|s| s.id == id) {
2544            continue;
2545        }
2546        match pick(agents, Some(id), available) {
2547            Ok(spec) => chain.push(spec),
2548            Err(e) => tracing::warn!("[roles] {role}: skipping `{id}`: {e:#}"),
2549        }
2550    }
2551    if chain.is_empty() {
2552        bail!(
2553            "[roles] {role} names no agent that can run here; the roster has {}",
2554            ids(agents)
2555        );
2556    }
2557    Ok(chain)
2558}
2559
2560/// Should a chain move on to its next agent after this call?
2561///
2562/// The one place that decides it: an error, a quota hit (judged apart from
2563/// `usable`, since a CLI can exit 0 with a quota message), or an unusable
2564/// answer such as a timeout or empty reply.
2565pub fn chain_advances(outcome: &Result<AgentOutput>) -> bool {
2566    match outcome {
2567        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => false,
2568        Err(_) => true,
2569        Ok(out) => output_advances(out),
2570    }
2571}
2572
2573/// [`chain_advances`] for a call that did return an output: the `Ok` half,
2574/// shared with callers that classify the call into their own outcome type
2575/// first (the graph's fixer chain).
2576pub fn output_advances(out: &AgentOutput) -> bool {
2577    out.quota_exhausted() || !out.usable()
2578}
2579
2580fn ids(agents: &[AgentSpec]) -> String {
2581    if agents.is_empty() {
2582        return "no agents at all".to_owned();
2583    }
2584    agents
2585        .iter()
2586        .map(|a| a.id.clone())
2587        .collect::<Vec<_>>()
2588        .join(", ")
2589}
2590
2591/// Isolate post-spawn pressure injection from real admission policy and from
2592/// other concurrent runs. This hook never exists in the shipped executable.
2593#[cfg(all(test, unix))]
2594pub(crate) mod test_watchdog {
2595    use super::*;
2596    static FLOORS: Mutex<BTreeMap<String, u64>> = Mutex::new(BTreeMap::new());
2597
2598    pub(crate) struct Guard(String);
2599
2600    pub(crate) fn set(run: &str, floor: u64) -> Guard {
2601        assert!(
2602            FLOORS
2603                .lock()
2604                .unwrap()
2605                .insert(run.to_owned(), floor)
2606                .is_none()
2607        );
2608        Guard(run.to_owned())
2609    }
2610
2611    pub(super) fn floor(run: &str, configured: u64) -> u64 {
2612        FLOORS
2613            .lock()
2614            .unwrap()
2615            .get(run)
2616            .copied()
2617            .unwrap_or(configured)
2618    }
2619
2620    impl Drop for Guard {
2621        fn drop(&mut self) {
2622            FLOORS.lock().unwrap().remove(&self.0);
2623        }
2624    }
2625}
2626
2627#[cfg(test)]
2628mod tests {
2629    use super::*;
2630
2631    const COMMAND_HELPER_MODE: &str = "MAGI_TEST_COMMAND_HELPER_MODE";
2632
2633    /// Test-only command agent implemented by this test binary itself. Unlike
2634    /// `echo` and `sleep`, it is available wherever the Rust tests run.
2635    fn command_helper(mode: &str) -> AgentSpec {
2636        // Invocation's disk monitor reads run state even without a build cache.
2637        crate::run::pin_test_home();
2638        AgentSpec {
2639            id: "helper".to_owned(),
2640            kind: AgentKind::Command,
2641            model: None,
2642            command: vec![
2643                std::env::current_exe()
2644                    .expect("locate test helper")
2645                    .to_string_lossy()
2646                    .into_owned(),
2647                "--exact".to_owned(),
2648                "agent::tests::command_agent_test_helper".to_owned(),
2649                "--nocapture".to_owned(),
2650            ],
2651            extra_args: Vec::new(),
2652            env: BTreeMap::from([(COMMAND_HELPER_MODE.to_owned(), mode.to_owned())]),
2653            prompt_delivery: None,
2654            max_turn_secs: None,
2655        }
2656    }
2657
2658    #[test]
2659    fn command_agent_test_helper() {
2660        match std::env::var(COMMAND_HELPER_MODE).as_deref() {
2661            Ok("reply") => println!("hello {}", std::env::var("MAGI_SEAT").unwrap()),
2662            Ok("cache") => println!("{}", std::env::var("CARGO_TARGET_DIR").unwrap()),
2663            Ok("no-cache") => println!(
2664                "{}",
2665                std::env::var("CARGO_TARGET_DIR").unwrap_or_else(|_| "ABSENT".to_owned())
2666            ),
2667            Ok("ignore-stdin") => println!("done"),
2668            Ok("chatty-sleep") => {
2669                println!("i-said-something");
2670                std::thread::sleep(Duration::from_secs(30));
2671            }
2672            Ok("sleep") => std::thread::sleep(Duration::from_secs(30)),
2673            Ok(other) => panic!("unknown command helper mode {other}"),
2674            Err(_) => {}
2675        }
2676    }
2677
2678    fn spec(kind: AgentKind, model: Option<&str>) -> AgentSpec {
2679        AgentSpec {
2680            id: "a".to_owned(),
2681            kind,
2682            model: model.map(str::to_owned),
2683            command: vec!["echo".to_owned(), "{label}".to_owned()],
2684            extra_args: Vec::new(),
2685            env: BTreeMap::new(),
2686            prompt_delivery: None,
2687            max_turn_secs: None,
2688        }
2689    }
2690
2691    fn inv<'a>(cwd: &'a Path, art: &'a Path, allow_write: bool) -> Invocation<'a> {
2692        Invocation {
2693            coordination: None,
2694            fetched_base: None,
2695            cwd,
2696            prompt: "do the thing",
2697            timeout: Duration::from_secs(900),
2698            allow_write,
2699            sessions: true,
2700            artifacts: art,
2701            stem: "t",
2702            run: "test-run",
2703            node: "test",
2704            cache_dir: None,
2705            attachments: &[],
2706            writable: &[],
2707        }
2708    }
2709
2710    fn plan_for(kind: AgentKind, seat: &SeatState, allow_write: bool) -> Plan {
2711        build_command(
2712            &spec(kind, None),
2713            seat,
2714            &inv(Path::new("."), Path::new("/art"), allow_write),
2715            Path::new("/art/p.md"),
2716        )
2717        .unwrap()
2718    }
2719
2720    #[test]
2721    fn editing_access_requires_fetch_evidence_and_keeps_snapshot() {
2722        let missing = editing_access_note(None);
2723        assert!(missing.contains("No successful launcher fetch evidence"));
2724        let base = crate::run::FetchedBase {
2725            remote: "origin".into(),
2726            branch: "main".into(),
2727            commit: "0123456789abcdef".into(),
2728            fetched_at: "2026-10-18T00:00:00Z".parse().unwrap(),
2729        };
2730        let note = editing_access_note(Some(&base));
2731        for expected in [
2732            "origin/main",
2733            "0123456789abcdef",
2734            "2026-10-18T00:00:00Z",
2735            "Do not fetch again",
2736        ] {
2737            assert!(note.contains(expected), "missing {expected}");
2738        }
2739        // Editing seats run without an OS sandbox, so nothing tells them
2740        // their network, Git or temporary-directory access is restricted.
2741        for text in [&missing, &note] {
2742            assert!(!text.to_lowercase().contains("sandbox"), "{text}");
2743            assert!(!text.contains("Network access is restricted"), "{text}");
2744        }
2745        let roundtrip: crate::run::FetchedBase =
2746            serde_json::from_str(&serde_json::to_string(&base).unwrap()).unwrap();
2747        assert_eq!(editing_access_note(Some(&roundtrip)), note);
2748    }
2749
2750    #[test]
2751    fn codex_editing_seats_bypass_the_sandbox_on_initial_and_resume() {
2752        const BYPASS: &str = "--dangerously-bypass-approvals-and-sandbox";
2753        let roots = [PathBuf::from("/shared/git"), PathBuf::from("/questions")];
2754        for resumed in [false, true] {
2755            let mut seat = SeatState::new("impl-A", "a", 7);
2756            if resumed {
2757                seat.turns = 1;
2758                seat.captured_session = Some("fixture-thread".into());
2759            }
2760            let build = |invocation: &Invocation<'_>| {
2761                build_command(
2762                    &spec(AgentKind::Codex, None),
2763                    &seat,
2764                    invocation,
2765                    Path::new("/art/p.md"),
2766                )
2767                .unwrap()
2768            };
2769            for node in [
2770                "implement",
2771                "fix",
2772                "graft",
2773                "gate-fix",
2774                "land",
2775                "rebase",
2776                "base-conflict",
2777                crate::queue::CHAT_NODE,
2778                "external-chat",
2779            ] {
2780                let mut invocation = inv(Path::new("."), Path::new("/art"), true);
2781                invocation.node = node;
2782                invocation.writable = &roots;
2783                let plan = build(&invocation);
2784                let at = plan.argv.iter().position(|s| s == BYPASS);
2785                assert!(at.is_some(), "{node}: {:?}", plan.argv);
2786                if resumed {
2787                    let resume = plan.argv.iter().position(|s| s == "resume").unwrap();
2788                    assert!(at.unwrap() < resume, "{node}: {:?}", plan.argv);
2789                }
2790                // No sandbox, approval or sandbox-scoped override survives.
2791                assert!(!plan.argv.iter().any(|s| s == "--sandbox"), "{node}");
2792                assert!(!plan.argv.iter().any(|s| s == "-c"), "{node}");
2793            }
2794            for (node, write) in [
2795                ("review", false),
2796                ("judge", false),
2797                ("advise", false),
2798                ("implement", false),
2799                ("fix", false),
2800                ("dupes", false),
2801                ("conduct", false),
2802                ("waiter", false),
2803                ("talk-title", false),
2804                (crate::queue::CHAT_NODE, false),
2805                ("external-chat", false),
2806                ("deputy", true),
2807            ] {
2808                let mut invocation = inv(Path::new("."), Path::new("/art"), write);
2809                invocation.node = node;
2810                let plan = build(&invocation);
2811                assert!(!plan.argv.iter().any(|s| s == BYPASS), "{node}");
2812                let mode = if write {
2813                    "workspace-write"
2814                } else {
2815                    "read-only"
2816                };
2817                assert!(
2818                    plan.argv.windows(2).any(|w| w == ["--sandbox", mode]),
2819                    "{node}: {:?}",
2820                    plan.argv
2821                );
2822                assert!(
2823                    plan.argv
2824                        .windows(2)
2825                        .any(|w| w == ["-c", "approval_policy=\"never\""]),
2826                    "{node}"
2827                );
2828            }
2829        }
2830    }
2831
2832    #[test]
2833    fn claude_mints_then_resumes_the_same_uuid() {
2834        let mut seat = SeatState::new("judge-1", "a", 7);
2835        let uuid = seat.claude_session.clone().unwrap();
2836        let first = plan_for(AgentKind::Claude, &seat, true);
2837        assert!(first.argv.windows(2).any(|w| w == ["--session-id", &uuid]));
2838        assert!(!first.argv.iter().any(|a| a == "--resume"));
2839
2840        seat.turns = 1;
2841        let second = plan_for(AgentKind::Claude, &seat, true);
2842        assert!(second.argv.windows(2).any(|w| w == ["--resume", &uuid]));
2843        assert!(!second.argv.iter().any(|a| a == "--session-id"));
2844    }
2845
2846    #[test]
2847    fn github_bound_claude_seats_override_the_operators_answer_language() {
2848        let seat = SeatState::new("change-summary", "a", 7);
2849        let art = Path::new("/art");
2850        for (language, name) in [("en", "English"), ("", "English"), ("ja", "Japanese")] {
2851            let claude =
2852                for_github_text(&spec(AgentKind::Claude, None), language, Path::new(".")).unwrap();
2853            let plan = build_command(
2854                &claude,
2855                &seat,
2856                &inv(Path::new("."), art, false),
2857                Path::new("/art/p.md"),
2858            )
2859            .unwrap();
2860            let settings = format!(r#"{{"language":"{name}"}}"#);
2861            assert!(
2862                plan.argv
2863                    .windows(2)
2864                    .any(|w| w == ["--settings", settings.as_str()]),
2865                "{:?}",
2866                plan.argv
2867            );
2868            // The prompt still arrives on stdin, not as an argument a
2869            // variadic flag could swallow.
2870            assert_eq!(plan.stdin.as_deref(), Some("do the thing"));
2871        }
2872        for kind in [
2873            AgentKind::Codex,
2874            AgentKind::Opencode,
2875            AgentKind::Antigravity,
2876            AgentKind::Omp,
2877        ] {
2878            assert!(
2879                for_github_text(&spec(kind, None), "en", Path::new("."))
2880                    .unwrap()
2881                    .extra_args
2882                    .is_empty()
2883            );
2884        }
2885    }
2886
2887    #[test]
2888    fn github_text_preserves_existing_settings() {
2889        let dir = tempfile::tempdir().unwrap();
2890        let original = serde_json::json!({
2891            "language": "Japanese",
2892            "env": { "SEAT_MODE": "configured" },
2893            "apiKeyHelper": "credential-helper",
2894            "hooks": { "Stop": [] }
2895        });
2896        std::fs::write(dir.path().join("seat-settings.json"), original.to_string()).unwrap();
2897        for value in [original.to_string(), "./seat-settings.json".to_owned()] {
2898            for equals in [false, true] {
2899                let mut spec = spec(AgentKind::Claude, None);
2900                // Earlier settings stay earlier; the CLI's last value wins.
2901                spec.extra_args = vec!["--settings={\"language\":\"French\"}".to_owned()];
2902                if equals {
2903                    spec.extra_args.push(format!("--settings={value}"));
2904                } else {
2905                    spec.extra_args
2906                        .extend(["--settings".to_owned(), value.clone()]);
2907                }
2908                spec.extra_args.push("--verbose".to_owned());
2909                let updated = for_github_text(&spec, "en", dir.path()).unwrap();
2910                assert_eq!(updated.extra_args.len(), spec.extra_args.len());
2911                assert_eq!(updated.extra_args[0], spec.extra_args[0]);
2912                assert_eq!(updated.extra_args.last(), spec.extra_args.last());
2913                let value = &updated.extra_args[updated.extra_args.len() - 2];
2914                let actual: serde_json::Value =
2915                    serde_json::from_str(value.strip_prefix("--settings=").unwrap_or(value))
2916                        .unwrap();
2917                let mut expected = original.clone();
2918                expected["language"] = serde_json::json!("English");
2919                assert_eq!(actual, expected);
2920            }
2921        }
2922        let on_disk: serde_json::Value = serde_json::from_str(
2923            &std::fs::read_to_string(dir.path().join("seat-settings.json")).unwrap(),
2924        )
2925        .unwrap();
2926        assert_eq!(on_disk, original);
2927    }
2928
2929    #[test]
2930    fn github_text_settings_are_redacted_from_command_logging() {
2931        let dir = tempfile::tempdir().unwrap();
2932        let settings = serde_json::json!({ "env": { "AUTH_TOKEN": "test-only-secret" } });
2933        std::fs::write(dir.path().join("seat-settings.json"), settings.to_string()).unwrap();
2934        for equals in [false, true] {
2935            let mut spec = spec(AgentKind::Claude, None);
2936            spec.extra_args =
2937                vec!["--settings={\"env\":{\"AUTH_TOKEN\":\"earlier-secret\"}}".to_owned()];
2938            if equals {
2939                spec.extra_args
2940                    .push("--settings=./seat-settings.json".to_owned());
2941            } else {
2942                spec.extra_args
2943                    .extend(["--settings".to_owned(), "./seat-settings.json".to_owned()]);
2944            }
2945            let spec = for_github_text(&spec, "en", dir.path()).unwrap();
2946            let plan = build_command(
2947                &spec,
2948                &SeatState::new("change-summary", "a", 7),
2949                &inv(dir.path(), dir.path(), false),
2950                &dir.path().join("prompt.md"),
2951            )
2952            .unwrap();
2953            // Execution still receives both the configured token and language.
2954            let actual = plan.argv.last().unwrap();
2955            let actual: serde_json::Value =
2956                serde_json::from_str(actual.strip_prefix("--settings=").unwrap_or(actual)).unwrap();
2957            assert_eq!(actual["env"]["AUTH_TOKEN"], "test-only-secret");
2958            assert_eq!(actual["language"], "English");
2959            let logged = format!("{:?}", plan.logged_argv());
2960            assert!(!logged.contains("secret"));
2961            assert!(!logged.contains("AUTH_TOKEN"));
2962            assert!(logged.contains("[redacted]"));
2963            assert_eq!(plan.logged_argv()[0], "claude");
2964            assert!(plan.logged_argv().contains(&"--output-format"));
2965        }
2966    }
2967
2968    #[test]
2969    fn github_text_rejects_unreadable_or_invalid_settings() {
2970        let dir = tempfile::tempdir().unwrap();
2971        std::fs::write(dir.path().join("bad.json"), "invalid json").unwrap();
2972        std::fs::write(dir.path().join("array.json"), "[]").unwrap();
2973        for args in [
2974            vec!["--settings"],
2975            vec!["--settings", "missing.json"],
2976            vec!["--settings=bad.json"],
2977            vec!["--settings", "array.json"],
2978        ] {
2979            let mut spec = spec(AgentKind::Claude, None);
2980            spec.extra_args = args.into_iter().map(str::to_owned).collect();
2981            assert!(for_github_text(&spec, "en", dir.path()).is_err());
2982        }
2983    }
2984
2985    #[test]
2986    fn read_only_seats_cannot_edit() {
2987        let seat = SeatState::new("judge-1", "a", 7);
2988        let claude = plan_for(AgentKind::Claude, &seat, false);
2989        assert!(claude.argv.iter().any(|a| a == "--disallowed-tools"));
2990        assert!(
2991            !plan_for(AgentKind::Claude, &seat, true)
2992                .argv
2993                .iter()
2994                .any(|a| a == "--disallowed-tools")
2995        );
2996
2997        let agy = plan_for(AgentKind::Antigravity, &seat, false);
2998        assert!(agy.argv.windows(2).any(|w| w == ["--mode", "plan"]));
2999        assert!(
3000            !agy.argv
3001                .iter()
3002                .any(|a| a == "--dangerously-skip-permissions")
3003        );
3004        let agy_rw = plan_for(AgentKind::Antigravity, &seat, true);
3005        assert!(
3006            agy_rw
3007                .argv
3008                .windows(2)
3009                .any(|w| w == ["--mode", "accept-edits"])
3010        );
3011        assert!(
3012            agy_rw
3013                .argv
3014                .iter()
3015                .any(|a| a == "--dangerously-skip-permissions")
3016        );
3017        // agy is pointed at its prompt with its own `@<path>` syntax, not with
3018        // prose asking it to read a file. Measured on one trivial task: 17s
3019        // against 73s, because prose costs a tool round-trip before the model
3020        // has even seen its instructions. It is also the form rvpm proved.
3021        let agy_prompt = agy_rw
3022            .argv
3023            .iter()
3024            .position(|a| a == "-p")
3025            .map(|i| agy_rw.argv[i + 1].clone())
3026            .expect("agy takes its prompt with -p");
3027        assert!(
3028            agy_prompt.starts_with('@'),
3029            "agy must get a file reference, got {agy_prompt:?}"
3030        );
3031        assert!(
3032            !agy_prompt.contains("Read the file at"),
3033            "the prose pointer is for CLIs with no file syntax"
3034        );
3035
3036        // opencode is the exception: `--auto` also gates reads, so withholding
3037        // it silently drops the seat out of the panel. Verified against the CLI
3038        // — a read-only judge failed with "the user rejected permission to use
3039        // this specific tool call" while trying to open its own prompt.
3040        for allow_write in [false, true] {
3041            assert!(
3042                plan_for(AgentKind::Opencode, &seat, allow_write)
3043                    .argv
3044                    .iter()
3045                    .any(|a| a == "--auto"),
3046                "opencode needs --auto even to read (allow_write = {allow_write})"
3047            );
3048        }
3049    }
3050
3051    /// The three things about `codex exec` that were established by hand and
3052    /// that a rewrite would silently get wrong.
3053    #[test]
3054    fn codex_gets_extra_writable_roots_only_when_it_may_write() {
3055        let seat = SeatState::new("deputy-x", "a", 7);
3056        let roots = [PathBuf::from("/data/questions")];
3057        let mk = |allow_write: bool| {
3058            let mut i = inv(Path::new("."), Path::new("/art"), allow_write);
3059            i.writable = &roots;
3060            build_command(
3061                &spec(AgentKind::Codex, None),
3062                &seat,
3063                &i,
3064                Path::new("/art/p.md"),
3065            )
3066            .unwrap()
3067        };
3068        let want = "sandbox_workspace_write.writable_roots=[\"/data/questions\"]";
3069        assert!(mk(true).argv.windows(2).any(|w| w == ["-c", want]));
3070        assert!(!mk(false).argv.iter().any(|a| a.contains("writable_roots")));
3071    }
3072
3073    #[test]
3074    fn repository_write_scope_covers_editing_nodes_without_changing_other_roles() {
3075        let mut i = inv(Path::new("."), Path::new("/art"), true);
3076        for node in [
3077            "implement",
3078            "fix",
3079            "graft",
3080            "gate-fix",
3081            "land",
3082            "rebase",
3083            "base-conflict",
3084            "chat",
3085            "external-chat",
3086        ] {
3087            i.node = node;
3088            assert!(repository_writer(&i), "{node}");
3089            i.allow_write = false;
3090            assert!(!repository_writer(&i), "{node}");
3091            i.allow_write = true;
3092        }
3093        for node in ["deputy", "judge", "review", "bump", "conduct", "talk-title"] {
3094            i.node = node;
3095            assert!(!repository_writer(&i), "{node}");
3096        }
3097        i.node = "chat";
3098        let roots = [PathBuf::from("/questions")];
3099        i.writable = &roots;
3100        assert!(
3101            repository_writer(&i),
3102            "explicit roots do not change the role"
3103        );
3104        assert!(
3105            !repository_seat(&i),
3106            "chat turns bypass repository scheduling"
3107        );
3108    }
3109
3110    #[test]
3111    fn coordination_classification_is_independent_of_write_grants() {
3112        let roots = [PathBuf::from("/questions")];
3113        for node in [
3114            crate::queue::CHAT_NODE,
3115            "external-chat",
3116            "implement",
3117            "fix",
3118            "graft",
3119            "gate-fix",
3120            "land",
3121            "rebase",
3122            "base-conflict",
3123            "review",
3124            "judge",
3125            "advise",
3126            "deputy",
3127            "waiter",
3128            "conduct",
3129            "dupes",
3130            "talk-title",
3131        ] {
3132            for allow_write in [false, true] {
3133                for writable in [&[][..], &roots[..]] {
3134                    let mut i = inv(Path::new("."), Path::new("/art"), allow_write);
3135                    i.node = node;
3136                    i.writable = writable;
3137                    assert_eq!(
3138                        repository_seat(&i),
3139                        !matches!(
3140                            node,
3141                            crate::queue::CHAT_NODE
3142                                | "external-chat"
3143                                | "talk-title"
3144                                | "deputy"
3145                                | "conduct"
3146                                | "dupes"
3147                        ),
3148                        "{node}, allow_write={allow_write}, writable={writable:?}"
3149                    );
3150                    if matches!(node, crate::queue::CHAT_NODE | "external-chat") {
3151                        assert_eq!(repository_writer(&i), allow_write);
3152                    }
3153                }
3154            }
3155        }
3156    }
3157
3158    #[test]
3159    fn writable_directories_reach_initial_and_resumed_adapter_commands() {
3160        let roots = [
3161            PathBuf::from("/shared/git"),
3162            PathBuf::from("/state/questions"),
3163        ];
3164        for kind in [AgentKind::Codex, AgentKind::Antigravity] {
3165            for resumed in [false, true] {
3166                let mut seat = SeatState::new("impl-A", "a", 7);
3167                if resumed {
3168                    seat.turns = 1;
3169                    seat.captured_session = Some("session-id".into());
3170                }
3171                for allow_write in [false, true] {
3172                    let mut i = inv(Path::new("."), Path::new("/art"), allow_write);
3173                    i.writable = &roots;
3174                    let plan = build_command(&spec(kind, None), &seat, &i, Path::new("/art/p.md"))
3175                        .unwrap();
3176                    for root in &roots {
3177                        if kind == AgentKind::Antigravity {
3178                            assert_eq!(
3179                                plan.argv.windows(2).any(|w| {
3180                                    w[0] == "--add-dir" && w[1] == root.to_str().unwrap()
3181                                }),
3182                                allow_write,
3183                                "resumed={resumed}: {:?}",
3184                                plan.argv
3185                            );
3186                        }
3187                        assert_eq!(
3188                            plan.argv
3189                                .iter()
3190                                .any(|arg| arg.contains(root.to_str().unwrap())),
3191                            allow_write,
3192                            "{kind:?}, resumed={resumed}: {:?}",
3193                            plan.argv
3194                        );
3195                    }
3196                    if kind == AgentKind::Codex && resumed {
3197                        let at = plan.argv.iter().position(|s| s == "resume").unwrap();
3198                        assert!(!plan.argv[at..].iter().any(|s| s == "-c"));
3199                    }
3200                }
3201            }
3202        }
3203    }
3204
3205    #[test]
3206    fn codex_is_sandboxed_reads_stdin_and_puts_resume_last() {
3207        let mut seat = SeatState::new("judge-1", "a", 7);
3208
3209        // 1. Read-only is enforced by the CLI, not by the prompt - the only
3210        //    roster member for which that is true - and only repository
3211        //    editing seats (see `codex_editing_seats_bypass_the_sandbox_on_initial_and_resume`)
3212        //    ever get the bypass. A seat that may write without editing the
3213        //    repository (a deputy's stores) keeps the workspace sandbox.
3214        let ro = plan_for(AgentKind::Codex, &seat, false);
3215        assert!(ro.argv.windows(2).any(|w| w == ["--sandbox", "read-only"]));
3216        let rw = plan_for(AgentKind::Codex, &seat, true);
3217        assert!(
3218            rw.argv
3219                .windows(2)
3220                .any(|w| w == ["--sandbox", "workspace-write"])
3221        );
3222        for p in [&ro, &rw] {
3223            assert!(
3224                !p.argv
3225                    .iter()
3226                    .any(|a| a == "--dangerously-bypass-approvals-and-sandbox"),
3227                "the bypass defeats the only enforced read-only mode we have"
3228            );
3229            // Nobody is watching to approve anything.
3230            assert!(
3231                p.argv
3232                    .windows(2)
3233                    .any(|w| w == ["-c", "approval_policy=\"never\""]),
3234                "an unattended seat that asks for approval blocks until timeout"
3235            );
3236        }
3237
3238        // 2. The prompt arrives on stdin, and `-` is what makes codex read it.
3239        assert_eq!(ro.stdin.as_deref(), Some("do the thing"));
3240        assert_eq!(
3241            ro.argv.last().map(String::as_str),
3242            Some("-"),
3243            "without the `-` argument codex waits for a prompt it never gets"
3244        );
3245
3246        // 3. `resume` is a subcommand and rejects the options above when they
3247        //    follow it, so it has to be emitted after all of them - and only
3248        //    once the CLI has reported a thread id.
3249        seat.turns = 1;
3250        assert!(!has_session(AgentKind::Codex, &seat, true));
3251        assert!(
3252            !plan_for(AgentKind::Codex, &seat, true)
3253                .argv
3254                .iter()
3255                .any(|a| a == "resume")
3256        );
3257        seat.captured_session = Some("01a07440-4545-7492-85c1-024e3259a90a".to_owned());
3258        let resumed = plan_for(AgentKind::Codex, &seat, true);
3259        let at = resumed
3260            .argv
3261            .iter()
3262            .position(|a| a == "resume")
3263            .expect("resumes by subcommand");
3264        assert_eq!(resumed.argv[at + 1], "01a07440-4545-7492-85c1-024e3259a90a");
3265        assert!(
3266            resumed.argv[..at].iter().any(|a| a == "--sandbox"),
3267            "every option precedes the subcommand"
3268        );
3269        assert_eq!(resumed.argv.last().map(String::as_str), Some("-"));
3270    }
3271
3272    /// The three things about `omp -p --mode=json` that were established by
3273    /// hand against omp 18.1.19 and that a rewrite would silently get wrong.
3274    #[test]
3275    fn omp_reads_stdin_auto_approves_and_resumes_by_id() {
3276        let mut seat = SeatState::new("review-1", "a", 7);
3277
3278        // 1. Print mode plus JSON, and the prompt on stdin: a judging prompt
3279        //    carrying three patches is past the Windows argv cap, so argv
3280        //    delivery is not an option for every node.
3281        let first = plan_for(AgentKind::Omp, &seat, false);
3282        assert!(first.argv.iter().any(|a| a == "-p"));
3283        assert!(first.argv.iter().any(|a| a == "--mode=json"));
3284        assert_eq!(first.stdin.as_deref(), Some("do the thing"));
3285        assert!(
3286            !first.argv.iter().any(|a| a == "do the thing"),
3287            "the prompt reached argv, where Windows caps it"
3288        );
3289
3290        // 2. `--auto-approve` is required (an unattended seat that stops to ask
3291        //    blocks until its node timeout kills it), and it is the *only*
3292        //    permission flag: omp has no read-only mode, so the bypass flag
3293        //    that would throw away codex's one enforced guarantee must never
3294        //    appear here either.
3295        for allow_write in [false, true] {
3296            let p = plan_for(AgentKind::Omp, &seat, allow_write);
3297            assert!(
3298                p.argv.iter().any(|a| a == "--auto-approve"),
3299                "omp needs --auto-approve even to read (allow_write = {allow_write})"
3300            );
3301            assert!(
3302                !p.argv
3303                    .iter()
3304                    .any(|a| a == "--dangerously-bypass-approvals-and-sandbox"),
3305                "nothing ever asks for the bypass"
3306            );
3307        }
3308
3309        // 3. The id omp reports is the only resume token - magi cannot mint it
3310        //    up front, so a seat resumes only once a turn has reported one.
3311        seat.turns = 1;
3312        assert!(!has_session(AgentKind::Omp, &seat, true));
3313        assert!(
3314            !plan_for(AgentKind::Omp, &seat, true)
3315                .argv
3316                .iter()
3317                .any(|a| a == "--resume")
3318        );
3319        seat.captured_session = Some("01a09fe9-4e31-7226-85b3-fda6f46689d5".to_owned());
3320        let resumed = plan_for(AgentKind::Omp, &seat, true);
3321        assert!(
3322            resumed
3323                .argv
3324                .windows(2)
3325                .any(|w| w == ["--resume", "01a09fe9-4e31-7226-85b3-fda6f46689d5"]),
3326            "a captured id is what makes the next turn a resume"
3327        );
3328        // `--continue` opens a *new* session instead of the stored one, which
3329        // would silently drop the seat's memory.
3330        assert!(!resumed.argv.iter().any(|a| a == "--continue"));
3331        // stdin still carries the prompt on a resumed turn.
3332        assert_eq!(resumed.stdin.as_deref(), Some("do the thing"));
3333    }
3334
3335    #[test]
3336    fn omp_terminal_breadcrumbs_are_disabled_only_for_managed_sessions() {
3337        let mut seat = SeatState::new("review-1", "a", 7);
3338        let mut cmd = Command::new("omp");
3339        cmd.envs([
3340            ("ZELLIJ_PANE_ID", "1"),
3341            ("TMUX_PANE", "%2"),
3342            ("CMUX_SURFACE_ID", "terminal"),
3343            ("KITTY_WINDOW_ID", "3"),
3344            ("WEZTERM_PANE", "4"),
3345            ("TERM_SESSION_ID", "terminal"),
3346            ("WT_SESSION", "terminal"),
3347            ("OMP_PROFILE", "work"),
3348        ]);
3349        let envs = |cmd: &Command| {
3350            cmd.as_std()
3351                .get_envs()
3352                .filter(|(_, value)| value.is_some())
3353                .count()
3354        };
3355        OmpSession::Resume.isolate_terminal_history(&mut cmd, &seat);
3356        assert_eq!(envs(&cmd), 8);
3357        OmpSession::Fresh(PathBuf::from("managed")).isolate_terminal_history(&mut cmd, &seat);
3358        assert_eq!(envs(&cmd), 1);
3359        assert!(
3360            cmd.as_std()
3361                .get_envs()
3362                .any(|(key, value)| { key == "OMP_PROFILE" && value == Some(OsStr::new("work")) })
3363        );
3364
3365        seat.omp_session_dir = Some(PathBuf::from("managed"));
3366        cmd.env("WT_SESSION", "terminal");
3367        OmpSession::Resume.isolate_terminal_history(&mut cmd, &seat);
3368        assert_eq!(envs(&cmd), 1);
3369    }
3370
3371    #[test]
3372    fn omp_managed_session_persists_native_path_and_reuses_it_after_reload() {
3373        let tmp = tempfile::tempdir().unwrap();
3374        let home = tmp.path().join("magi home 日本語");
3375        let spec = spec(AgentKind::Omp, None);
3376        let mut seat = SeatState::new("review-1", "a", 7);
3377        let art = tmp.path().join("art");
3378        let cwd = tmp.path().join("other checkout");
3379        let mut invocation = inv(&cwd, &art, false);
3380        let prompt = art.join("p.md");
3381
3382        let fresh = OmpSession::prepare(&spec, &seat, true, || home.clone()).unwrap();
3383        let dir = fresh.dir(&seat).unwrap().to_owned();
3384        assert_eq!(dir.parent().unwrap(), home.join("agent-sessions/omp"));
3385        assert!(dir.is_absolute() && dir.is_dir());
3386        assert!(
3387            !dir.file_name()
3388                .unwrap()
3389                .to_str()
3390                .unwrap()
3391                .contains(&seat.key)
3392        );
3393        let plan = build_command(&spec, &seat, &invocation, &prompt).unwrap();
3394        let args: Vec<_> = plan.args(Some(&dir)).collect();
3395        assert_eq!(&args[..2], [OsStr::new("--session-dir"), dir.as_os_str()]);
3396        assert!(!args.contains(&OsStr::new("--resume")));
3397        fresh
3398            .record(&mut seat, Some("first-id".into()), true)
3399            .unwrap();
3400        seat.turns += 1;
3401
3402        let mut seat: SeatState =
3403            serde_json::from_slice(&serde_json::to_vec(&seat).unwrap()).unwrap();
3404        let resumed = OmpSession::prepare(&spec, &seat, true, || {
3405            panic!("resume must not resolve home")
3406        })
3407        .unwrap();
3408        let plan = build_command(&spec, &seat, &invocation, &prompt).unwrap();
3409        let args: Vec<_> = plan.args(resumed.dir(&seat)).collect();
3410        assert_eq!(&args[..2], [OsStr::new("--session-dir"), dir.as_os_str()]);
3411        assert!(args.windows(2).any(|w| w == ["--resume", "first-id"]));
3412        let before = seat.clone();
3413        assert!(
3414            resumed
3415                .record(&mut seat, Some("other-id".into()), true)
3416                .is_err()
3417        );
3418        assert!(OmpSession::Resume.record(&mut seat, None, true).is_err());
3419        assert_eq!(seat, before);
3420        // Timeout and nonzero exit both reach record with success == false.
3421        OmpSession::Resume.record(&mut seat, None, false).unwrap();
3422        assert_eq!(seat, before);
3423
3424        let fallback = SeatState::new("review-1", "b", 7);
3425        let next = OmpSession::prepare(&spec, &fallback, true, || home.clone()).unwrap();
3426        assert_ne!(next.dir(&fallback).unwrap(), dir);
3427        // A session-disabled turn still persists, but cannot look up the old turn.
3428        invocation.sessions = false;
3429        let fresh = OmpSession::prepare(&spec, &seat, false, || home.clone()).unwrap();
3430        let new_dir = fresh.dir(&seat).unwrap().to_owned();
3431        assert_ne!(new_dir, dir);
3432        assert_ne!(next.dir(&fallback).unwrap(), new_dir);
3433        assert!(
3434            !build_command(&spec, &seat, &invocation, &prompt)
3435                .unwrap()
3436                .args(Some(&new_dir))
3437                .any(|arg| arg == "--resume")
3438        );
3439        fresh
3440            .record(&mut seat, Some("fresh-id".into()), true)
3441            .unwrap();
3442        assert_eq!(seat.omp_session_dir.as_deref(), Some(new_dir.as_path()));
3443        assert_eq!(seat.captured_session.as_deref(), Some("fresh-id"));
3444
3445        std::fs::remove_dir(new_dir).unwrap();
3446        assert!(OmpSession::prepare(&spec, &seat, true, || home.clone()).is_err());
3447    }
3448
3449    #[test]
3450    fn omp_pre_isolation_json_resumes_without_a_session_directory() {
3451        let mut seat: SeatState = serde_json::from_str(
3452            r#"{"key":"review-1","agent":"a","turns":1,"claude_session":null,"captured_session":"legacy-id"}"#,
3453        )
3454        .unwrap();
3455        let resume = OmpSession::prepare(&spec(AgentKind::Omp, None), &seat, true, || {
3456            panic!("legacy resume must not resolve or create a store")
3457        })
3458        .unwrap();
3459        let plan = plan_for(AgentKind::Omp, &seat, false);
3460        let args: Vec<_> = plan.args(resume.dir(&seat)).collect();
3461        assert!(!args.contains(&OsStr::new("--session-dir")));
3462        assert!(args.windows(2).any(|w| w == ["--resume", "legacy-id"]));
3463        resume
3464            .record(&mut seat, Some("continuation-id".into()), true)
3465            .unwrap();
3466        assert!(seat.omp_session_dir.is_none());
3467        assert_eq!(seat.captured_session.as_deref(), Some("continuation-id"));
3468        let plan = plan_for(AgentKind::Omp, &seat, false);
3469        assert!(
3470            plan.args(None)
3471                .zip(plan.args(None).skip(1))
3472                .any(|(flag, id)| flag == "--resume" && id == "continuation-id")
3473        );
3474    }
3475
3476    #[test]
3477    fn omp_managed_resume_tracks_only_local_continuation_lineage() {
3478        let tmp = tempfile::tempdir().unwrap();
3479        let managed = tmp.path().join("managed");
3480        std::fs::create_dir(&managed).unwrap();
3481        let mut seat = SeatState::new("review-1", "a", 7);
3482        seat.turns = 1;
3483        seat.captured_session = Some("original".into());
3484        seat.omp_session_dir = Some(managed.clone());
3485
3486        let write_header = |dir: &Path, id: &str, parent: &str| {
3487            let header = serde_json::json!({
3488                "type": "session", "version": 3, "id": id, "continuationOf": parent,
3489            });
3490            std::fs::write(dir.join(format!("{id}.jsonl")), format!("{header}\n")).unwrap();
3491        };
3492        write_header(tmp.path(), "outside", "original");
3493        write_header(&managed, "unrelated", "other-seat");
3494        write_header(&managed, "middle", "original");
3495        write_header(&managed, "latest", "middle");
3496        for id in ["outside", "unrelated"] {
3497            assert!(
3498                OmpSession::Resume
3499                    .record(&mut seat, Some(id.into()), true)
3500                    .is_err()
3501            );
3502            assert_eq!(seat.captured_session.as_deref(), Some("original"));
3503        }
3504
3505        OmpSession::Resume
3506            .record(&mut seat, Some("latest".into()), true)
3507            .unwrap();
3508        assert_eq!(seat.omp_session_dir.as_deref(), Some(managed.as_path()));
3509        let plan = plan_for(AgentKind::Omp, &seat, false);
3510        assert!(plan.argv.windows(2).any(|w| w == ["--resume", "latest"]));
3511    }
3512
3513    #[test]
3514    fn omp_managed_session_rejects_extra_args_that_override_history() {
3515        let mut spec = spec(AgentKind::Omp, None);
3516        let mut seat = SeatState::new("review-1", "a", 7);
3517        for arg in [
3518            "--session-dir",
3519            "--session-dir=other",
3520            "--no-session",
3521            "--continue",
3522            "--resume=other",
3523            "--session",
3524            "--session=operator.jsonl",
3525            "--fork",
3526            "--fork=operator.jsonl",
3527            "--restore",
3528            "--from-claude",
3529            "--from-codex",
3530            "-c",
3531            "-r=other",
3532        ] {
3533            spec.extra_args = vec![arg.into()];
3534            for sessions in [false, true] {
3535                let error = OmpSession::prepare(&spec, &seat, sessions, || panic!("invalid arg"))
3536                    .err()
3537                    .unwrap();
3538                assert!(error.to_string().contains("omp extra_args"));
3539            }
3540            seat.turns = 1;
3541            seat.captured_session = Some("existing-id".into());
3542            seat.omp_session_dir = Some(PathBuf::from("not-opened"));
3543        }
3544    }
3545
3546    /// The extraction trap that cost three complete reviews when it was done by
3547    /// hand: a turn that ends on a tool call emits **no** `agent_end` line, so
3548    /// keying on `agent_end` finds nothing and the seat reads as one that
3549    /// produced no answer at all.
3550    #[test]
3551    fn omp_takes_the_answer_without_an_agent_end_line() {
3552        let stream = concat!(
3553            r#"{"type":"session","version":3,"id":"01a09fe9-4e31-7226-85b3-fda6f46689d5","cwd":"C:\\w"}"#,
3554            "\n",
3555            r#"{"type":"agent_start"}"#,
3556            "\n",
3557            r#"{"type":"turn_start"}"#,
3558            "\n",
3559            r#"{"type":"message_update","assistantMessageEvent":{"type":"text_delta","contentIndex":1,"delta":"."}}"#,
3560            "\n",
3561            r#"{"type":"message_end","message":{"role":"assistant","content":[{"type":"thinking","thinking":"checking"},{"type":"text","text":"."}]}}"#,
3562            "\n",
3563            r#"{"type":"turn_end","message":{"role":"assistant","content":[{"type":"thinking","thinking":"done"},{"type":"text","text":"{\"vote\":\"approve\"}"}]}}"#,
3564            "\n",
3565        );
3566        let out = extract(AgentKind::Omp, stream);
3567        assert_eq!(
3568            out.text, "{\"vote\":\"approve\"}",
3569            "the last assistant text block is the answer even with no agent_end"
3570        );
3571        assert_eq!(
3572            out.session.as_deref(),
3573            Some("01a09fe9-4e31-7226-85b3-fda6f46689d5")
3574        );
3575    }
3576
3577    /// A stream that *does* carry `agent_end` walks the whole thread, and the
3578    /// last non-empty assistant text still wins over the tool-loop narration
3579    /// that came before it.
3580    #[test]
3581    fn omp_walks_agent_end_and_ignores_tool_loop_narration() {
3582        let stream = concat!(
3583            r#"{"type":"session","version":3,"id":"s1"}"#,
3584            "\n",
3585            "{\"type\":\"agent_end\",\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"review this\"}]},{\"role\":\"assistant\",\"content\":[{\"type\":\"text\",\"text\":\"Looking at the diff…\"}]},{\"role\":\"assistant\",\"content\":[{\"type\":\"thinking\",\"thinking\":\"…\"},{\"type\":\"text\",\"text\":\"## 判定\\n\\n問題ありません。\"}]}]}",
3586            "\n",
3587        );
3588        let out = extract(AgentKind::Omp, stream);
3589        assert_eq!(
3590            out.text, "## 判定\n\n問題ありません。",
3591            "the narration is not the answer, and non-ASCII survives intact"
3592        );
3593        assert_eq!(out.session.as_deref(), Some("s1"));
3594    }
3595
3596    /// A line that is not JSON - a CLI warning, a half-written line - is
3597    /// skipped rather than becoming the answer.
3598    #[test]
3599    fn omp_skips_non_json_lines() {
3600        let stream = concat!(
3601            "Warning: some omp notice\n",
3602            r#"{"type":"session","version":3,"id":"s2"}"#,
3603            "\n",
3604            r#"{"type":"message_end","message":{"role":"assistant","content":[{"type":"text","text":"the answer"}]}}"#,
3605            "\n",
3606            "trailing junk",
3607            "\n",
3608        );
3609        let out = extract(AgentKind::Omp, stream);
3610        assert_eq!(out.text, "the answer");
3611        assert_eq!(out.session.as_deref(), Some("s2"));
3612    }
3613
3614    /// The evidence the implement node reads to tell a reply that did no
3615    /// work from one that did: a stream that answers with text alone reports
3616    /// zero tool calls, one that ran tools reports them, and a stream with no
3617    /// assistant message at all reports nothing.
3618    #[test]
3619    fn omp_reports_tool_activity_only_when_the_stream_shows_it() {
3620        let session = r#"{"type":"session","version":3,"id":"s3"}"#;
3621        let text_only = format!(
3622            "{session}\n{}\n",
3623            r#"{"type":"message_end","message":{"role":"assistant","content":[{"type":"text","text":"Implementation incomplete."}],"stopReason":"stop"}}"#
3624        );
3625        assert_eq!(extract(AgentKind::Omp, &text_only).tool_calls, Some(0));
3626
3627        // The execution events alone are enough.
3628        let ran = format!(
3629            "{session}\n{}\n{}\n",
3630            r#"{"type":"tool_execution_start","toolCallId":"t1","toolName":"read"}"#,
3631            r#"{"type":"message_end","message":{"role":"assistant","content":[{"type":"text","text":"done"}],"stopReason":"stop"}}"#
3632        );
3633        assert_eq!(extract(AgentKind::Omp, &ran).tool_calls, Some(1));
3634
3635        // So are the tool-call parts, counted once although `turn_end`
3636        // repeats the message.
3637        let call = r#"{"role":"assistant","content":[{"type":"toolCall","id":"t1","name":"read"}],"stopReason":"toolUse"}"#;
3638        let parts = format!(
3639            "{session}\n{{\"type\":\"message_end\",\"message\":{call}}}\n{{\"type\":\"turn_end\",\"message\":{call}}}\n"
3640        );
3641        assert_eq!(extract(AgentKind::Omp, &parts).tool_calls, Some(1));
3642
3643        // No assistant message: unknown, never zero.
3644        assert_eq!(extract(AgentKind::Omp, session).tool_calls, None);
3645        assert_eq!(extract(AgentKind::Omp, "").tool_calls, None);
3646    }
3647
3648    /// A `command` agent that relays an omp stream is read like omp; any
3649    /// other output stays plain text with no claim about tools.
3650    #[test]
3651    fn a_command_agent_relaying_an_omp_stream_is_read_as_one() {
3652        let stream = concat!(
3653            r#"{"type":"session","version":3,"id":"s4"}"#,
3654            "\n",
3655            r#"{"type":"message_end","message":{"role":"assistant","content":[{"type":"text","text":"the answer"}],"stopReason":"stop"}}"#,
3656            "\n",
3657        );
3658        let out = extract(AgentKind::Command, stream);
3659        assert_eq!(out.text, "the answer");
3660        assert_eq!(out.tool_calls, Some(0));
3661
3662        let plain = extract(AgentKind::Command, "## SUMMARY\nTITLE: fix: thing\n");
3663        assert_eq!(plain.text, "## SUMMARY\nTITLE: fix: thing");
3664        assert_eq!(plain.tool_calls, None);
3665    }
3666
3667    /// A real `codex exec --json` stream, tracing prefix included.
3668    #[test]
3669    fn codex_takes_the_last_agent_message_and_the_thread_id() {
3670        let stream = concat!(
3671            "2026-09-06T01:05:49.394445Z ERROR codex_models_manager: failed to load models cache\n",
3672            r#"{"type":"thread.started","thread_id":"01a07440-4545-7492-85c1-024e3259a90a"}"#,
3673            "\n",
3674            r#"{"type":"turn.started"}"#,
3675            "\n",
3676            r#"{"type":"item.completed","item":{"id":"item_0","type":"agent_message","text":"Looking into it."}}"#,
3677            "\n",
3678            r#"{"type":"item.completed","item":{"id":"item_1","type":"command_execution","text":"cargo test"}}"#,
3679            "\n",
3680            r#"{"type":"item.completed","item":{"id":"item_2","type":"agent_message","text":"{\"verdict\": \"ok\"}"}}"#,
3681            "\n",
3682            r#"{"type":"turn.completed","usage":{"input_tokens":17137}}"#,
3683            "\n",
3684        );
3685        let out = extract(AgentKind::Codex, stream);
3686        assert_eq!(
3687            out.text, "{\"verdict\": \"ok\"}",
3688            "the last agent message is the answer; earlier ones narrate"
3689        );
3690        assert_eq!(
3691            out.session.as_deref(),
3692            Some("01a07440-4545-7492-85c1-024e3259a90a")
3693        );
3694        assert_eq!(out.status.as_deref(), Some("success"));
3695
3696        let failed = concat!(
3697            r#"{"type":"thread.started","thread_id":"t1"}"#,
3698            "\n",
3699            r#"{"type":"turn.failed","error":{"message":"nope"}}"#,
3700            "\n",
3701        );
3702        assert_eq!(
3703            extract(AgentKind::Codex, failed).status.as_deref(),
3704            Some("error")
3705        );
3706    }
3707
3708    #[test]
3709    fn captured_sessions_resume_only_once_reported() {
3710        let mut seat = SeatState::new("impl-A", "a", 7);
3711        seat.turns = 1;
3712        for kind in [AgentKind::Opencode, AgentKind::Antigravity] {
3713            assert!(!has_session(kind, &seat, true));
3714            let p = plan_for(kind, &seat, true);
3715            assert!(!p.argv.iter().any(|a| a == "-s" || a == "--conversation"));
3716        }
3717
3718        seat.captured_session = Some("sid".to_owned());
3719        assert!(has_session(AgentKind::Opencode, &seat, true));
3720        assert!(
3721            plan_for(AgentKind::Opencode, &seat, true)
3722                .argv
3723                .windows(2)
3724                .any(|w| w == ["-s", "sid"])
3725        );
3726        assert!(
3727            plan_for(AgentKind::Antigravity, &seat, true)
3728                .argv
3729                .windows(2)
3730                .any(|w| w == ["--conversation", "sid"])
3731        );
3732    }
3733
3734    #[test]
3735    fn sessions_disabled_never_resumes() {
3736        let mut seat = SeatState::new("impl-A", "a", 7);
3737        seat.turns = 3;
3738        seat.captured_session = Some("sid".to_owned());
3739        for kind in [
3740            AgentKind::Claude,
3741            AgentKind::Opencode,
3742            AgentKind::Antigravity,
3743        ] {
3744            assert!(!has_session(kind, &seat, false));
3745        }
3746    }
3747
3748    #[test]
3749    fn long_prompts_never_reach_argv_for_file_delivery_clis() {
3750        let seat = SeatState::new("judge-1", "a", 7);
3751        for kind in [AgentKind::Opencode, AgentKind::Antigravity] {
3752            let p = plan_for(kind, &seat, false);
3753            assert!(
3754                p.argv.iter().all(|a| a != "do the thing"),
3755                "{kind:?} put the prompt on the command line"
3756            );
3757            assert!(p.argv.iter().any(|a| a.contains("/art/p.md")));
3758        }
3759        // agy has no text stdin, so its `-p` must always carry something.
3760        let p = plan_for(AgentKind::Antigravity, &seat, false);
3761        let at = p.argv.iter().position(|a| a == "-p").unwrap();
3762        assert!(p.argv.get(at + 1).is_some_and(|v| v.contains("p.md")));
3763        assert!(p.stdin.is_none());
3764    }
3765
3766    #[test]
3767    fn agy_print_timeout_tracks_the_node_budget() {
3768        let seat = SeatState::new("impl-A", "a", 7);
3769        let p = build_command(
3770            &spec(AgentKind::Antigravity, None),
3771            &seat,
3772            &Invocation {
3773                coordination: None,
3774                fetched_base: None,
3775                cwd: Path::new("."),
3776                prompt: "p",
3777                timeout: Duration::from_secs(3600),
3778                allow_write: true,
3779                sessions: true,
3780                artifacts: Path::new("/art"),
3781                stem: "t",
3782                run: "test-run",
3783                node: "test",
3784                cache_dir: None,
3785                attachments: &[],
3786                writable: &[],
3787            },
3788            Path::new("/art/p.md"),
3789        )
3790        .unwrap();
3791        assert!(p.argv.windows(2).any(|w| w == ["--print-timeout", "3600s"]));
3792    }
3793
3794    /// `--add-dir` is what lets antigravity open a file outside the
3795    /// worktree at all. Today that only happens when the delivery mode is
3796    /// already `File`, but an attachment can arrive on a seat whose delivery
3797    /// is `Stdin` or `Argv` (an explicit `prompt_delivery` override), and the
3798    /// image still lives outside `cwd` - so the flag has to widen for that
3799    /// reason too, independent of how the prompt itself is delivered.
3800    #[test]
3801    fn attachments_widen_antigravitys_add_dir_even_off_file_delivery() {
3802        let mut s = spec(AgentKind::Antigravity, None);
3803        s.prompt_delivery = Some(Delivery::Argv);
3804        let seat = SeatState::new("talk", "a", 7);
3805        let atts = [PathBuf::from("/art/attachments/abc.png")];
3806
3807        let without = build_command(
3808            &s,
3809            &seat,
3810            &Invocation {
3811                attachments: &[],
3812                writable: &[],
3813                ..inv(Path::new("."), Path::new("/art"), true)
3814            },
3815            Path::new("/art/p.md"),
3816        )
3817        .unwrap();
3818        assert!(
3819            !without.argv.iter().any(|a| a == "--add-dir"),
3820            "no attachment, no reason to widen the sandbox: {without:?}"
3821        );
3822
3823        let with = build_command(
3824            &s,
3825            &seat,
3826            &Invocation {
3827                attachments: &atts,
3828                writable: &[],
3829                ..inv(Path::new("."), Path::new("/art"), true)
3830            },
3831            Path::new("/art/p.md"),
3832        )
3833        .unwrap();
3834        assert!(
3835            with.argv.windows(2).any(|w| w == ["--add-dir", "/art"]),
3836            "an attachment outside cwd must widen the sandbox even off File delivery: {with:?}"
3837        );
3838    }
3839
3840    /// A chat derived from another one (`chat::derived_background`) can pass
3841    /// `turn` attachment paths that live under the *source* conversation's
3842    /// own artifacts dir, not this invocation's `artifacts`. A single
3843    /// `--add-dir` for `inv.artifacts` alone would leave those unreadable, so
3844    /// each attachment directory outside it must get its own grant.
3845    #[test]
3846    fn an_inherited_attachment_outside_this_conversations_artifacts_dir_gets_its_own_add_dir() {
3847        let seat = SeatState::new("plan", "a", 7);
3848        let atts = [
3849            PathBuf::from("/art/attachments/own.png"),
3850            PathBuf::from("/other-chat/attachments/inherited.png"),
3851        ];
3852
3853        let p = build_command(
3854            &spec(AgentKind::Antigravity, None),
3855            &seat,
3856            &Invocation {
3857                attachments: &atts,
3858                writable: &[],
3859                ..inv(Path::new("."), Path::new("/art"), true)
3860            },
3861            Path::new("/art/p.md"),
3862        )
3863        .unwrap();
3864
3865        assert!(
3866            p.argv.windows(2).any(|w| w == ["--add-dir", "/art"]),
3867            "this conversation's own artifacts dir must still be granted: {p:?}"
3868        );
3869        assert!(
3870            p.argv
3871                .windows(2)
3872                .any(|w| w == ["--add-dir", "/other-chat/attachments"]),
3873            "the inherited attachment's own directory must be granted too: {p:?}"
3874        );
3875    }
3876
3877    #[test]
3878    fn command_agents_get_placeholders_substituted() {
3879        let seat = SeatState::new("impl-A", "a", 7);
3880        let p = plan_for(AgentKind::Command, &seat, true);
3881        assert_eq!(p.argv[0], "echo");
3882        assert_eq!(p.argv[1], "impl-A");
3883        assert_eq!(p.stdin.as_deref(), Some("do the thing"));
3884    }
3885
3886    const EXPIRED_AUTH: &str = r#"{"is_error":true,"terminal_reason":"api_error","result":"Failed to authenticate: OAuth session expired and could not be refreshed"}"#;
3887    const CODEX_LIMIT: &str = r#"{"type":"error","message":"You've hit your usage limit. Visit https://chatgpt.com/settings/usage to purchase more credits or try again at Oct 27th, 2026 6:18 PM."}
3888{"type":"turn.failed","error":{"message":"You've hit your usage limit."}}"#;
3889
3890    #[test]
3891    fn observed_machine_failures_are_detected_conservatively() {
3892        let auth = extract(AgentKind::Claude, EXPIRED_AUTH).quota.unwrap();
3893        assert_eq!(auth.cause, QuotaCause::Authentication);
3894        assert_eq!(auth.reset, None);
3895        let limit = extract(AgentKind::Codex, CODEX_LIMIT).quota.unwrap();
3896        assert_eq!(limit.cause, QuotaCause::UsageLimit);
3897        assert_eq!(limit.reset.as_deref(), Some("Oct 27th, 2026 6:18 PM"));
3898        // Duplicate events still yield one classification.
3899        assert!(
3900            extract(AgentKind::Codex, &format!("{CODEX_LIMIT}\n{CODEX_LIMIT}"))
3901                .quota
3902                .is_some()
3903        );
3904        let without_reset = CODEX_LIMIT.replace(" or try again at Oct 27th, 2026 6:18 PM", "");
3905        assert!(
3906            extract(AgentKind::Codex, &without_reset)
3907                .quota
3908                .unwrap()
3909                .reset
3910                .is_none()
3911        );
3912        for text in [
3913            EXPIRED_AUTH.replace("true", "false"),
3914            EXPIRED_AUTH.replace("api_error", "unknown"),
3915            EXPIRED_AUTH.replace(
3916                "OAuth session expired and could not be refreshed",
3917                "unknown error",
3918            ),
3919        ] {
3920            assert!(extract(AgentKind::Claude, &text).quota.is_none());
3921        }
3922        assert!(
3923            extract(AgentKind::Codex, CODEX_LIMIT.lines().next().unwrap())
3924                .quota
3925                .is_none()
3926        );
3927        assert!(
3928            extract(
3929                AgentKind::Codex,
3930                &CODEX_LIMIT.replace("You've hit your usage limit.", "Something failed.")
3931            )
3932            .quota
3933            .is_none()
3934        );
3935        let quoted = serde_json::json!({"type":"item.completed","item":{"type":"agent_message","text":CODEX_LIMIT}}).to_string();
3936        assert!(extract(AgentKind::Codex, &quoted).quota.is_none());
3937        assert!(extract(AgentKind::Codex, EXPIRED_AUTH).quota.is_none());
3938        assert!(
3939            extract(AgentKind::Antigravity, EXPIRED_AUTH)
3940                .quota
3941                .is_none()
3942        );
3943        let legacy: Quota = serde_json::from_str(r#"{"reset":null}"#).unwrap();
3944        assert_eq!(legacy.cause, QuotaCause::UsageLimit);
3945    }
3946
3947    #[test]
3948    fn claude_rate_limit_is_detected_and_reset_read_when_present() {
3949        // The exact shape observed in the wild (run 20260831-031005-ae94).
3950        let stdout = r#"{"is_error": true, "terminal_reason": "api_error",
3951                        "result": "You've hit your session limit · resets 4:50am (Asia/Tokyo)",
3952                        "session_id": "b8e928f1-754e-4bd3-86c5-0567763654e3"}"#;
3953        let out = extract(AgentKind::Claude, stdout);
3954        let quota = out.quota.as_ref().expect("rate limit must be detected");
3955        assert_eq!(
3956            quota.reset.as_deref(),
3957            Some("4:50am (Asia/Tokyo)"),
3958            "reset time read from the body"
3959        );
3960    }
3961
3962    #[test]
3963    fn claude_rate_limit_without_a_readable_reset_is_still_detected() {
3964        let out = extract(
3965            AgentKind::Claude,
3966            r#"{"is_error":true,"result":"session limit reached"}"#,
3967        );
3968        let quota = out.quota.expect("rate limit detected without a reset");
3969        assert!(quota.reset.is_none(), "unknown reset is kept as unknown");
3970    }
3971
3972    #[test]
3973    fn claude_structured_usage_limit_requires_the_error_and_exact_pair() {
3974        for kind in [AgentKind::Claude, AgentKind::Command] {
3975            for reply in [
3976                r#"{"is_error":true,"api_error_status":429,"api_error":"usage_limit_reached"}"#,
3977                r#"{"is_error":true,"api_error_status":"429","api_error":"usage_limit_reached"}"#,
3978            ] {
3979                assert!(extract(kind, reply).quota.is_some(), "{reply}");
3980            }
3981            for reply in [
3982                r#"{"is_error":false,"api_error_status":429,"api_error":"usage_limit_reached"}"#,
3983                r#"{"is_error":true,"api_error_status":500,"api_error":"usage_limit_reached"}"#,
3984                r#"{"is_error":true,"api_error_status":429,"api_error":"other_error"}"#,
3985                r#"{"is_error":false,"api_error_status":"429","api_error":"usage_limit_reached"}"#,
3986                r#"{"is_error":true,"api_error_status":"500","api_error":"usage_limit_reached"}"#,
3987                r#"{"is_error":true,"api_error_status":"429","api_error":"other_error"}"#,
3988                r#"{"is_error":true,"api_error":"usage_limit_reached"}"#,
3989            ] {
3990                assert!(extract(kind, reply).quota.is_none(), "{reply}");
3991            }
3992        }
3993    }
3994
3995    #[test]
3996    fn ordinary_failures_are_never_quota() {
3997        // A normal failed claude call (is_error with a different message).
3998        let claude_fail = extract(
3999            AgentKind::Claude,
4000            r#"{"is_error":true,"result":"account does not exist"}"#,
4001        );
4002        assert!(claude_fail.quota.is_none());
4003
4004        // A command agent that exits 1 with plain text.
4005        let cmd_fail = extract(AgentKind::Command, "boom");
4006        assert!(cmd_fail.quota.is_none());
4007
4008        // A successful call is not quota even if it mentions the phrase.
4009        let success = extract(
4010            AgentKind::Command,
4011            r#"{"is_error":false,"result":"session limit is fine"}"#,
4012        );
4013        assert!(success.quota.is_none());
4014    }
4015
4016    /// Minimal, anonymised shape of run 20260912-214939-b3bb's
4017    /// artifacts/impl-A.out: `command_execution` items reporting a paired
4018    /// test run as `1 passed, 1 failed` twice, while the final
4019    /// `agent_message` nevertheless claimed the target passed. The point of
4020    /// `CommandEvidence` is that this claim and the CLI's own structured
4021    /// record of what actually ran are now two separate things a caller can
4022    /// compare, rather than the prose being the only account available.
4023    #[test]
4024    fn codex_command_execution_events_are_captured_alongside_the_final_message() {
4025        let stream = concat!(
4026            r#"{"type":"thread.started","thread_id":"t1"}"#,
4027            "\n",
4028            r#"{"type":"item.completed","item":{"id":"item49","type":"command_execution","command":["bash","-lc","cargo test --test graph_cached_gate"],"exit_code":1,"aggregated_output":"test result: 1 passed; 1 failed"}}"#,
4029            "\n",
4030            r#"{"type":"item.completed","item":{"id":"item52","type":"command_execution","command":["bash","-lc","cargo test --test graph_cached_gate a_single_test"],"exit_code":0,"aggregated_output":"test result: 1 passed; 0 failed"}}"#,
4031            "\n",
4032            r#"{"type":"item.completed","item":{"id":"item99","type":"agent_message","text":"Both tests in the target pass."}}"#,
4033            "\n",
4034            r#"{"type":"turn.completed"}"#,
4035            "\n",
4036        );
4037        let out = extract(AgentKind::Codex, stream);
4038        assert_eq!(out.text, "Both tests in the target pass.");
4039        assert_eq!(out.commands.len(), 2, "{:?}", out.commands);
4040
4041        let paired = &out.commands[0];
4042        assert_eq!(paired.id, "item49");
4043        assert_eq!(paired.exit_code, Some(1));
4044        assert!(paired.description.contains("graph_cached_gate"));
4045        assert!(paired.result_summary.contains("1 failed"));
4046
4047        let solo = &out.commands[1];
4048        assert_eq!(solo.exit_code, Some(0));
4049
4050        // The structured evidence disagrees with the final prose - exactly
4051        // what a caller must be able to see instead of trusting the message
4052        // alone: the full target never passed in one command.
4053        assert!(
4054            out.commands
4055                .iter()
4056                .any(|c| c.exit_code != Some(0) && c.description.contains("graph_cached_gate")),
4057            "a failed run of the actual target must still be visible: {:?}",
4058            out.commands
4059        );
4060    }
4061
4062    #[test]
4063    fn command_agent_can_carry_the_claude_quota_shape() {
4064        let out = extract(
4065            AgentKind::Command,
4066            r#"{"is_error":true,"result":"You've hit your session limit · resets 1:00am (UTC)"}"#,
4067        );
4068        assert!(
4069            out.quota.is_some(),
4070            "a wrapper emitting the claude shape counts as quota"
4071        );
4072    }
4073
4074    #[test]
4075    fn claude_json_result_is_extracted() {
4076        let out = extract(
4077            AgentKind::Claude,
4078            r#"{"result":"all done","session_id":"abc","is_error":false}"#,
4079        );
4080        assert_eq!(out.text, "all done");
4081        assert_eq!(out.session.as_deref(), Some("abc"));
4082        assert_eq!(out.status.as_deref(), Some("success"));
4083    }
4084
4085    /// The shape behind fix-2 in run 20260912-114326-d3b8, minimal and
4086    /// anonymised: a Claude CLI turn that ended `subtype: success`,
4087    /// `is_error: false`, `terminal_reason: completed`, `stop_reason:
4088    /// end_turn` — every signal this crate reads as a clean CLI turn — while
4089    /// `result` is a progress update, not the report the fixer node needed,
4090    /// and no `FixReport` JSON is anywhere in it.
4091    ///
4092    /// `AgentOutput::usable()` (a CLI fact: exit 0, not timed out, non-empty
4093    /// text) must stay true here — that is the honest reading of what the
4094    /// CLI reported — while `verdict::extract_json` on the same text must
4095    /// fail. Conflating the two is exactly the bug this fixture reproduces:
4096    /// `run.json` recorded `fix.failed = "unparsable fix report: the reply
4097    /// contained no JSON object"` and moved straight to the next review round
4098    /// with no report ever recovered from that seat.
4099    #[test]
4100    fn a_clean_cli_turn_is_not_the_same_fact_as_the_nodes_own_work_being_done() {
4101        let stdout = r#"{"type":"result","subtype":"success","is_error":false,"terminal_reason":"completed","stop_reason":"end_turn","result":"I'll pause here until the `cargo make check` background run reports back.","session_id":"11111111-1111-1111-1111-111111111111"}"#;
4102        let out = extract(AgentKind::Claude, stdout);
4103        assert_eq!(out.status.as_deref(), Some("success"));
4104        assert!(out.quota.is_none());
4105        assert!(!out.text.trim().is_empty());
4106
4107        let agent_out = AgentOutput {
4108            text: out.text.clone(),
4109            exit_code: Some(0),
4110            timed_out: false,
4111            duration_ms: 500,
4112            artifacts: Vec::new(),
4113            quota: out.quota,
4114            dropped: out.dropped,
4115            commands: out.commands,
4116            context_tokens: None,
4117            tool_calls: None,
4118        };
4119        assert!(
4120            agent_out.usable(),
4121            "the CLI turn itself ended cleanly and must read as usable"
4122        );
4123        assert!(
4124            crate::verdict::extract_json::<crate::verdict::FixReport>(&agent_out.text).is_err(),
4125            "a clean CLI turn is not proof the node's own report ever arrived"
4126        );
4127    }
4128
4129    #[test]
4130    fn opencode_event_stream_is_concatenated() {
4131        let stream = concat!(
4132            r#"{"type":"step_start","sessionID":"ses_1","part":{"type":"step-start"}}"#,
4133            "\n",
4134            r#"{"type":"text","sessionID":"ses_1","part":{"type":"text","text":"first"}}"#,
4135            "\n",
4136            "garbage line\n",
4137            r#"{"type":"text","sessionID":"ses_1","part":{"type":"text","text":"second"}}"#,
4138            "\n"
4139        );
4140        let out = extract(AgentKind::Opencode, stream);
4141        assert_eq!(out.text, "first\nsecond");
4142        assert_eq!(out.session.as_deref(), Some("ses_1"));
4143    }
4144
4145    #[test]
4146    fn agy_json_survives_a_leading_warning_line() {
4147        let stdout = concat!(
4148            "warning: --mode plan has no effect while slash commands are disabled.\n",
4149            r#"{"conversation_id":"eaf2d00a","status":"SUCCESS","response":"persimmon\n"}"#,
4150            "\n"
4151        );
4152        let out = extract(AgentKind::Antigravity, stdout);
4153        assert_eq!(out.text, "persimmon");
4154        assert_eq!(out.session.as_deref(), Some("eaf2d00a"));
4155        assert_eq!(out.status.as_deref(), Some("SUCCESS"));
4156    }
4157
4158    /// Run 26c7's candidate B, verbatim from `artifacts/impl-B.out`.
4159    ///
4160    /// The seat read as an empty candidate. It was seven minutes of work and
4161    /// 14,267 output tokens, billed, that the CLI then declined to hand over.
4162    /// Five such candidates are why `agy` reads as 0 wins in 4 entries, and
4163    /// that number has twice been used to argue the seat out of the roster.
4164    const AGY_DROPPED: &str = concat!(
4165        r#"{"conversation_id":"36743d06-c0b3-4b79-9fa2-23869289d7b6","status":"ERROR","#,
4166        r#""response":"","error":"the connection to the agent was interrupted before "#,
4167        r#"the response finished: subscriber fell behind updates, stalled for 5s","#,
4168        r#""duration_seconds":431.1941803,"num_turns":1,"usage":{"input_tokens":260113,"#,
4169        r#""output_tokens":14267,"thinking_tokens":9695,"cache_read_tokens":2200925,"#,
4170        r#""total_tokens":274380}}"#
4171    );
4172
4173    /// Run 1798's review seat, from `review-1-1.out` / `.err`.
4174    const AGY_QUOTA_OUT: &str = concat!(
4175        r#"{"conversation_id":"323c3b5b-0000","status":"ERROR","response":"","#,
4176        r#""error":"Individual quota reached. Please upgrade your subscription to "#,
4177        r#"increase your limits. Resets in 1h2m49s.","duration_seconds":265.9,"#,
4178        r#""num_turns":2,"usage":{"input_tokens":1000,"output_tokens":50}}"#
4179    );
4180    const AGY_QUOTA_ERR: &str = concat!(
4181        "error: Individual quota reached. Resets in 1h2m49s.\n",
4182        r#"AGY_ERROR: {"short_error":"RESOURCE_EXHAUSTED (code 429): Individual quota "#,
4183        r#"reached.","status":"RESOURCE_EXHAUSTED","error_code":429,"code_kind":"http","#,
4184        r#""retryable":true}"#,
4185        "\n"
4186    );
4187
4188    #[test]
4189    fn agy_out_of_quota_is_a_quota_with_the_reset_hint() {
4190        let both = agy_quota(AGY_QUOTA_OUT, AGY_QUOTA_ERR).expect("both streams");
4191        assert_eq!(both.reset.as_deref(), Some("in 1h2m49s"));
4192        let stdout_only = agy_quota(AGY_QUOTA_OUT, "").expect("stdout alone");
4193        assert_eq!(stdout_only.reset.as_deref(), Some("in 1h2m49s"));
4194        // stderr alone: the hint is not in `short_error`, so none is carried.
4195        let stderr_only = agy_quota("not json", AGY_QUOTA_ERR).expect("stderr alone");
4196        assert!(stderr_only.reset.is_none());
4197    }
4198
4199    #[test]
4200    fn ordinary_agy_failures_are_not_a_quota() {
4201        assert!(agy_quota(AGY_DROPPED, "").is_none());
4202        assert!(agy_quota(r#"{"status":"ERROR","error":"boom"}"#, "").is_none());
4203        assert!(
4204            agy_quota(
4205                "",
4206                r#"AGY_ERROR: {"status":"RESOURCE_EXHAUSTED","error_code":500}"#
4207            )
4208            .is_none()
4209        );
4210        assert!(
4211            agy_quota(
4212                "",
4213                r#"AGY_ERROR: {"status":"UNAVAILABLE","error_code":429}"#
4214            )
4215            .is_none()
4216        );
4217        assert!(agy_quota(r#"{"status":"SUCCESS","response":"ok"}"#, "").is_none());
4218    }
4219
4220    #[test]
4221    fn a_cli_that_hangs_up_on_billed_work_is_not_an_agent_that_produced_nothing() {
4222        let out = extract(AgentKind::Antigravity, AGY_DROPPED);
4223        let dropped = out.dropped.expect("recognised as undelivered work");
4224        assert_eq!(dropped.output_tokens, 14267);
4225        assert!(
4226            dropped.why.contains("subscriber fell behind"),
4227            "the CLI's own words are kept for the record: {}",
4228            dropped.why
4229        );
4230        // And the conversation is still there to resume, which is the whole
4231        // reason this is worth re-asking where a quota is not.
4232        assert_eq!(
4233            out.session.as_deref(),
4234            Some("36743d06-c0b3-4b79-9fa2-23869289d7b6")
4235        );
4236        assert!(out.quota.is_none(), "a dropped stream is not a rate limit");
4237    }
4238
4239    #[test]
4240    fn an_error_with_nothing_produced_stays_an_ordinary_failure() {
4241        // No usage at all: the agent never got going, so there is nothing in
4242        // the conversation to resume and nothing was billed. Treating this as
4243        // undelivered work would buy a second call for no reason.
4244        let bare = r#"{"conversation_id":"c1","status":"ERROR","response":"","error":"boom"}"#;
4245        assert!(extract(AgentKind::Antigravity, bare).dropped.is_none());
4246
4247        // Produced tokens, but it did answer - so there is something to read
4248        // and the status is not our business.
4249        let answered = concat!(
4250            r#"{"conversation_id":"c2","status":"ERROR","response":"here it is","#,
4251            r#""usage":{"output_tokens":10}}"#
4252        );
4253        assert!(extract(AgentKind::Antigravity, answered).dropped.is_none());
4254
4255        // A success is a success.
4256        let ok = concat!(
4257            r#"{"conversation_id":"c3","status":"SUCCESS","response":"done","#,
4258            r#""usage":{"output_tokens":10}}"#
4259        );
4260        assert!(extract(AgentKind::Antigravity, ok).dropped.is_none());
4261    }
4262
4263    #[test]
4264    fn an_undelivered_output_is_not_usable_but_is_worth_asking_again() {
4265        let out = AgentOutput {
4266            text: String::new(),
4267            exit_code: Some(1),
4268            timed_out: false,
4269            duration_ms: 431_194,
4270            artifacts: Vec::new(),
4271            quota: None,
4272            dropped: Some(Dropped {
4273                why: "subscriber fell behind updates".to_owned(),
4274                output_tokens: 14267,
4275            }),
4276            commands: Vec::new(),
4277            context_tokens: None,
4278            tool_calls: None,
4279        };
4280        assert!(!out.usable());
4281        assert!(out.work_undelivered());
4282        // The distinction the retry policy rests on: a quota fails the same way
4283        // until it resets, an abandoned conversation can be picked up.
4284        assert!(!out.quota_exhausted());
4285    }
4286
4287    #[test]
4288    fn non_json_stdout_falls_back_to_raw_text() {
4289        let out = extract(AgentKind::Antigravity, "plain answer\n");
4290        assert_eq!(out.text, "plain answer");
4291        assert!(out.session.is_none());
4292    }
4293
4294    #[tokio::test]
4295    async fn command_agent_round_trip_writes_artifacts() {
4296        let dir = tempfile::tempdir().unwrap();
4297        let art = dir.path().join("artifacts");
4298        let mut seat = SeatState::new("impl-A", "a", 7);
4299        let s = command_helper("reply");
4300        let out = invoke(
4301            &s,
4302            &mut seat,
4303            &Invocation {
4304                coordination: None,
4305                fetched_base: None,
4306                cwd: dir.path(),
4307                prompt: "unused",
4308                timeout: Duration::from_secs(30),
4309                allow_write: true,
4310                sessions: true,
4311                artifacts: &art,
4312                stem: "impl-A",
4313                run: "test-run",
4314                node: "test",
4315                cache_dir: None,
4316                attachments: &[],
4317                writable: &[],
4318            },
4319        )
4320        .await
4321        .unwrap();
4322        assert!(out.usable(), "{out:?}");
4323        assert!(out.text.contains("hello impl-A"), "{}", out.text);
4324        assert_eq!(seat.turns, 1);
4325        assert!(art.join("impl-A.prompt.md").is_file());
4326        assert!(art.join("impl-A.out").is_file());
4327    }
4328
4329    #[tokio::test]
4330    async fn the_invocation_cache_dir_reaches_the_seat_as_cargo_target_dir() {
4331        crate::run::pin_test_home();
4332        // The whole point of threading the cache path through `Invocation`:
4333        // the compile the agent pays for lands in the directory `verify` reads
4334        // back out of its rendered commands, so one cache has one prune.
4335        let dir = tempfile::tempdir().unwrap();
4336        let cache = dir.path().join("magi-cache");
4337        let mut seat = SeatState::new("impl-A", "a", 7);
4338        let s = command_helper("cache");
4339        let out = invoke(
4340            &s,
4341            &mut seat,
4342            &Invocation {
4343                coordination: None,
4344                fetched_base: None,
4345                cwd: dir.path(),
4346                prompt: "unused",
4347                timeout: Duration::from_secs(30),
4348                allow_write: true,
4349                sessions: true,
4350                artifacts: &dir.path().join("artifacts"),
4351                stem: "cache",
4352                run: "test-run",
4353                node: "test",
4354                cache_dir: Some(&cache),
4355                attachments: &[],
4356                writable: &[],
4357            },
4358        )
4359        .await
4360        .unwrap();
4361        assert!(out.usable(), "{out:?}");
4362        assert!(
4363            out.text.contains(cache.to_string_lossy().as_ref()),
4364            "the seat must see CARGO_TARGET_DIR = the shared cache"
4365        );
4366    }
4367
4368    #[tokio::test]
4369    async fn direct_writer_does_not_borrow_another_runs_cache() {
4370        let dir = tempfile::tempdir().unwrap();
4371        let cache = dir.path().join("magi-cache");
4372        let spec = command_helper("no-cache");
4373        let home = crate::run::home();
4374        let owner = crate::cache::Owner::here("other-run", "e2e", "e2e", dir.path(), "");
4375        let crate::cache::AcquireOutcome::Acquired(guard) =
4376            crate::cache::try_acquire(&home, &cache, &owner).unwrap()
4377        else {
4378            panic!("could not acquire fixture cache");
4379        };
4380        let mut seat = SeatState::new("fix", "a", 7);
4381        let inv = Invocation {
4382            coordination: None,
4383            fetched_base: None,
4384            cwd: dir.path(),
4385            prompt: "unused",
4386            timeout: Duration::from_secs(30),
4387            allow_write: true,
4388            sessions: false,
4389            artifacts: &dir.path().join("artifacts"),
4390            stem: "fix",
4391            run: "test-run",
4392            node: "test",
4393            cache_dir: Some(&cache),
4394            attachments: &[],
4395            writable: &[],
4396        };
4397        let out = invoke(&spec, &mut seat, &inv).await.unwrap();
4398        assert!(out.text.contains("ABSENT"), "{}", out.text);
4399        drop(guard);
4400        let wave_owner = crate::cache::Owner::here("test-run", "test", "*", dir.path(), "");
4401        let crate::cache::AcquireOutcome::Acquired(guard) =
4402            crate::cache::try_acquire(&home, &cache, &wave_owner).unwrap()
4403        else {
4404            panic!("could not acquire wave cache");
4405        };
4406        let out = invoke_in_wave(&spec, &mut seat, &inv, Some(&guard))
4407            .await
4408            .unwrap();
4409        assert!(
4410            out.text.contains(cache.to_string_lossy().as_ref()),
4411            "{}",
4412            out.text
4413        );
4414        assert!(crate::cache::in_use(&home, &cache));
4415        drop(guard);
4416        let out = invoke(&spec, &mut seat, &inv).await.unwrap();
4417        assert!(
4418            out.text.contains(cache.to_string_lossy().as_ref()),
4419            "{}",
4420            out.text
4421        );
4422        assert!(!crate::cache::in_use(&home, &cache));
4423    }
4424
4425    #[tokio::test]
4426    async fn cache_dir_none_strips_a_cargo_target_dir_inherited_from_this_process() {
4427        // `Command` inherits the parent's environment by default, so
4428        // `cache_dir: None` alone is not the same as a seat never seeing
4429        // `CARGO_TARGET_DIR` - it also has to be true when *this* process
4430        // (standing in for the real magi process, which normally does have
4431        // one set, from its own `[verify]` config) already has the variable
4432        // set. Simulating that is the only way to exercise the inheritance
4433        // path at all.
4434        let previous = std::env::var("CARGO_TARGET_DIR").ok();
4435        // SAFETY: this crate's tests run single-threaded
4436        // (`RUST_TEST_THREADS=1`); see
4437        // `updater::tests::env_kill_switch_semantics` for the same
4438        // reasoning applied to another process-global env var.
4439        unsafe {
4440            std::env::set_var("CARGO_TARGET_DIR", "/should/never/reach/a/read-only/seat");
4441        }
4442        let dir = tempfile::tempdir().unwrap();
4443        let mut seat = SeatState::new("review-1", "a", 7);
4444        let s = command_helper("no-cache");
4445        let result = invoke(
4446            &s,
4447            &mut seat,
4448            &Invocation {
4449                coordination: None,
4450                fetched_base: None,
4451                cwd: dir.path(),
4452                prompt: "unused",
4453                timeout: Duration::from_secs(30),
4454                allow_write: false,
4455                sessions: true,
4456                artifacts: &dir.path().join("artifacts"),
4457                stem: "no-cache",
4458                run: "test-run",
4459                node: "test",
4460                cache_dir: None,
4461                attachments: &[],
4462                writable: &[],
4463            },
4464        )
4465        .await;
4466        // Restored before any assertion that could panic, so a failure here
4467        // never leaks a bogus `CARGO_TARGET_DIR` into whichever test runs
4468        // next in this same process.
4469        // SAFETY: see above.
4470        unsafe {
4471            match &previous {
4472                Some(v) => std::env::set_var("CARGO_TARGET_DIR", v),
4473                None => std::env::remove_var("CARGO_TARGET_DIR"),
4474            }
4475        }
4476        let out = result.unwrap();
4477        assert!(out.usable(), "{out:?}");
4478        assert!(
4479            out.text.contains("ABSENT"),
4480            "a read-only seat must never inherit the process's own CARGO_TARGET_DIR: {}",
4481            out.text
4482        );
4483    }
4484
4485    #[tokio::test]
4486    async fn a_prompt_larger_than_the_pipe_buffer_does_not_deadlock() {
4487        let dir = tempfile::tempdir().unwrap();
4488        let mut seat = SeatState::new("impl-A", "a", 7);
4489        // The helper never reads stdin, so an inline write_all would block once
4490        // the OS pipe buffer filled — long before the process could be waited on.
4491        let s = command_helper("ignore-stdin");
4492        let big = "x".repeat(1_000_000);
4493        let out = invoke(
4494            &s,
4495            &mut seat,
4496            &Invocation {
4497                coordination: None,
4498                fetched_base: None,
4499                cwd: dir.path(),
4500                prompt: &big,
4501                timeout: Duration::from_secs(60),
4502                allow_write: true,
4503                sessions: true,
4504                artifacts: &dir.path().join("artifacts"),
4505                stem: "big",
4506                run: "test-run",
4507                node: "test",
4508                cache_dir: None,
4509                attachments: &[],
4510                writable: &[],
4511            },
4512        )
4513        .await
4514        .unwrap();
4515        assert!(out.usable(), "{out:?}");
4516        assert!(out.text.contains("done"), "{}", out.text);
4517    }
4518
4519    #[tokio::test]
4520    async fn agent_turn_cap_limits_a_direct_invocation() {
4521        let dir = tempfile::tempdir().unwrap();
4522        let artifacts = dir.path().join("artifacts");
4523        let mut seat = SeatState::new("impl-A", "helper", 7);
4524        let mut s = command_helper("sleep");
4525        s.max_turn_secs = Some(2);
4526        let out = invoke(&s, &mut seat, &inv(dir.path(), &artifacts, false))
4527            .await
4528            .unwrap();
4529        assert!(out.timed_out, "{out:?}");
4530        // The caller supplies 900 seconds and the helper sleeps for 30:
4531        // neither may override the short per-agent cap.
4532        assert!(out.duration_ms < 20_000, "{out:?}");
4533    }
4534
4535    #[tokio::test]
4536    async fn timeout_is_reported_not_hung() {
4537        let dir = tempfile::tempdir().unwrap();
4538        let mut seat = SeatState::new("impl-A", "a", 7);
4539        let s = command_helper("sleep");
4540        let out = invoke(
4541            &s,
4542            &mut seat,
4543            &Invocation {
4544                coordination: None,
4545                fetched_base: None,
4546                cwd: dir.path(),
4547                prompt: "unused",
4548                timeout: Duration::from_millis(300),
4549                allow_write: true,
4550                sessions: true,
4551                artifacts: &dir.path().join("artifacts"),
4552                stem: "slow",
4553                run: "test-run",
4554                node: "test",
4555                cache_dir: None,
4556                attachments: &[],
4557                writable: &[],
4558            },
4559        )
4560        .await
4561        .unwrap();
4562        assert!(out.timed_out);
4563        assert!(!out.usable());
4564    }
4565
4566    #[tokio::test]
4567    async fn a_timeout_keeps_what_the_agent_had_already_printed() {
4568        // The old implementation cancelled `wait_with_output`, which dropped
4569        // the buffers it owned, so `<stem>.out` was written empty on every
4570        // timeout. "It printed nothing" and "we discarded what it printed"
4571        // looked identical on disk — and one real hour-long stall was
4572        // diagnosed wrongly twice because of it.
4573        let dir = tempfile::tempdir().unwrap();
4574        let artifacts = dir.path().join("artifacts");
4575        let mut seat = SeatState::new("impl-A", "a", 7);
4576        let s = command_helper("chatty-sleep");
4577        let out = invoke(
4578            &s,
4579            &mut seat,
4580            &Invocation {
4581                coordination: None,
4582                fetched_base: None,
4583                cwd: dir.path(),
4584                prompt: "unused",
4585                // Wide enough to cover process-spawn latency inside a loaded
4586                // parallel test run, not merely the helper's first write. At
4587                // two seconds this passed alone and failed in the full suite,
4588                // which is a dice roll rather than a test.
4589                timeout: Duration::from_secs(10),
4590                allow_write: true,
4591                sessions: true,
4592                artifacts: &artifacts,
4593                stem: "chatty",
4594                run: "test-run",
4595                node: "test",
4596                cache_dir: None,
4597                attachments: &[],
4598                writable: &[],
4599            },
4600        )
4601        .await
4602        .unwrap();
4603
4604        assert!(out.timed_out, "{out:?}");
4605        assert!(!out.usable(), "a cut-off answer is still not an answer");
4606        let recorded = std::fs::read_to_string(artifacts.join("chatty.out")).unwrap();
4607        assert!(
4608            recorded.contains("i-said-something"),
4609            "the artifact must keep what arrived before the kill, got {recorded:?}"
4610        );
4611        assert!(
4612            out.text.contains("i-said-something"),
4613            "and the graph must be able to see it too, got {:?}",
4614            out.text
4615        );
4616    }
4617
4618    #[test]
4619    fn missing_programs_reports_command_binaries() {
4620        let mut s = spec(AgentKind::Command, None);
4621        s.command = vec!["definitely-not-a-real-binary-xyz".to_owned()];
4622        assert_eq!(
4623            missing_programs(&[s]),
4624            ["definitely-not-a-real-binary-xyz".to_owned()]
4625        );
4626    }
4627
4628    fn pick_spec(id: &str, kind: AgentKind) -> AgentSpec {
4629        AgentSpec {
4630            id: id.to_owned(),
4631            kind,
4632            model: None,
4633            command: Vec::new(),
4634            extra_args: Vec::new(),
4635            env: BTreeMap::new(),
4636            prompt_delivery: None,
4637            max_turn_secs: None,
4638        }
4639    }
4640
4641    /// Availability stub: an agent is runnable unless its id was listed as
4642    /// missing. Keeps the selection tests off `PATH` entirely.
4643    fn without<'a>(missing: &'a [&'a str]) -> impl Fn(&AgentSpec) -> bool + 'a {
4644        move |a: &AgentSpec| !missing.contains(&a.id.as_str())
4645    }
4646
4647    #[test]
4648    fn pick_prefers_the_claude_seat_even_when_it_is_not_first_in_the_roster() {
4649        let agents = [
4650            pick_spec("oc", AgentKind::Opencode),
4651            pick_spec("opus", AgentKind::Claude),
4652            pick_spec("agy", AgentKind::Antigravity),
4653        ];
4654        let got = pick(&agents, None, &without(&[])).expect("a pick");
4655        assert_eq!(got.id, "opus");
4656    }
4657
4658    #[test]
4659    fn pick_falls_back_to_the_first_installed_agent_in_roster_order() {
4660        let agents = [
4661            pick_spec("opus", AgentKind::Claude),
4662            pick_spec("oc", AgentKind::Opencode),
4663            pick_spec("agy", AgentKind::Antigravity),
4664        ];
4665        let got = pick(&agents, None, &without(&["opus", "oc"])).expect("a pick");
4666        assert_eq!(got.id, "agy");
4667    }
4668
4669    #[test]
4670    fn pick_on_an_empty_roster_says_what_to_install() {
4671        let msg = pick(&[], None, &without(&[]))
4672            .expect_err("nobody to ask")
4673            .to_string();
4674        assert!(msg.contains("roster is empty"), "{msg}");
4675        assert!(msg.contains("claude"), "{msg}");
4676        assert!(msg.contains("magi.toml"), "{msg}");
4677    }
4678
4679    #[test]
4680    fn pick_on_a_roster_with_nothing_installed_names_the_programs_that_are_missing() {
4681        let agents = [
4682            pick_spec("opus", AgentKind::Claude),
4683            pick_spec("oc", AgentKind::Opencode),
4684        ];
4685        let err = pick(&agents, None, &without(&["opus", "oc"])).expect_err("nothing runnable");
4686        let msg = format!("{err:#}");
4687        assert!(msg.contains("claude"), "{msg}");
4688        assert!(msg.contains("opencode"), "{msg}");
4689    }
4690
4691    #[test]
4692    fn an_explicitly_named_agent_wins_over_the_claude_preference() {
4693        let agents = [
4694            pick_spec("opus", AgentKind::Claude),
4695            pick_spec("oc", AgentKind::Opencode),
4696        ];
4697        let got = pick(&agents, Some("oc"), &without(&[])).expect("a pick");
4698        assert_eq!(got.id, "oc");
4699    }
4700
4701    #[test]
4702    fn an_unknown_agent_id_lists_the_ids_that_do_exist() {
4703        let agents = [
4704            pick_spec("opus", AgentKind::Claude),
4705            pick_spec("oc", AgentKind::Opencode),
4706        ];
4707        let msg = pick(&agents, Some("gemini"), &without(&[]))
4708            .expect_err("no such agent")
4709            .to_string();
4710        assert!(msg.contains("gemini"), "{msg}");
4711        assert!(msg.contains("opus, oc"), "{msg}");
4712    }
4713
4714    #[test]
4715    fn an_explicitly_named_agent_that_is_not_installed_is_an_error_not_a_fallback() {
4716        let agents = [
4717            pick_spec("opus", AgentKind::Claude),
4718            pick_spec("oc", AgentKind::Opencode),
4719        ];
4720        let msg = pick(&agents, Some("oc"), &without(&["oc"]))
4721            .expect_err("must not silently substitute another model")
4722            .to_string();
4723        assert!(msg.contains("opencode"), "{msg}");
4724        assert!(msg.contains("--agent"), "{msg}");
4725    }
4726
4727    fn named(id: &str) -> AgentSpec {
4728        AgentSpec {
4729            id: id.to_owned(),
4730            ..spec(AgentKind::Command, None)
4731        }
4732    }
4733
4734    fn output(text: &str, exit: i32, quota: bool) -> AgentOutput {
4735        AgentOutput {
4736            text: text.to_owned(),
4737            exit_code: Some(exit),
4738            timed_out: false,
4739            duration_ms: 0,
4740            artifacts: Vec::new(),
4741            quota: quota.then_some(Quota {
4742                reset: None,
4743                cause: QuotaCause::UsageLimit,
4744                agent: String::new(),
4745            }),
4746            dropped: None,
4747            commands: Vec::new(),
4748            context_tokens: None,
4749            tool_calls: None,
4750        }
4751    }
4752
4753    #[test]
4754    fn a_chain_keeps_the_written_order_and_a_string_is_a_chain_of_one() {
4755        let agents = [named("a"), named("b"), named("c")];
4756        let all = |_: &AgentSpec| true;
4757        let chain = AgentChoice::Chain(vec!["c".into(), "a".into()]);
4758        let got = pick_chain(&agents, Some(&chain), &all, "synthesizer").unwrap();
4759        assert_eq!(
4760            got.iter().map(|s| s.id.as_str()).collect::<Vec<_>>(),
4761            ["c", "a"]
4762        );
4763
4764        let one = AgentChoice::from("b");
4765        let got = pick_chain(&agents, Some(&one), &all, "synthesizer").unwrap();
4766        assert_eq!(got.len(), 1);
4767        assert_eq!(got[0].id, "b");
4768
4769        let got = pick_chain(&agents, None, &all, "synthesizer").unwrap();
4770        assert_eq!(got.len(), 1, "unset keeps pick's default");
4771        assert_eq!(got[0].id, "a");
4772        let empty = AgentChoice::Chain(Vec::new());
4773        assert_eq!(
4774            pick_chain(&agents, Some(&empty), &all, "x").unwrap()[0].id,
4775            "a"
4776        );
4777    }
4778
4779    #[test]
4780    fn a_chain_skips_unknown_and_uninstalled_ids_and_tries_each_once() {
4781        let agents = [named("a"), named("b")];
4782        let not_a = |s: &AgentSpec| s.id != "a";
4783        let chain = AgentChoice::Chain(
4784            ["a", "ghost", "b", "b"]
4785                .iter()
4786                .map(|s| (*s).to_owned())
4787                .collect(),
4788        );
4789        let got = pick_chain(&agents, Some(&chain), &not_a, "chatter").unwrap();
4790        assert_eq!(got.iter().map(|s| s.id.as_str()).collect::<Vec<_>>(), ["b"]);
4791
4792        let dup = AgentChoice::Chain(vec!["b".into(), "a".into(), "b".into()]);
4793        let got = pick_chain(&agents, Some(&dup), &|_| true, "chatter").unwrap();
4794        assert_eq!(
4795            got.iter().map(|s| s.id.as_str()).collect::<Vec<_>>(),
4796            ["b", "a"]
4797        );
4798    }
4799
4800    #[test]
4801    fn a_chain_with_nothing_runnable_names_the_role() {
4802        let agents = [named("a")];
4803        let chain = AgentChoice::Chain(vec!["a".into(), "ghost".into()]);
4804        let err = pick_chain(&agents, Some(&chain), &|_| false, "conductor")
4805            .unwrap_err()
4806            .to_string();
4807        assert!(err.contains("conductor"), "{err}");
4808    }
4809
4810    #[test]
4811    fn a_chain_advances_on_error_quota_or_an_unusable_answer_only() {
4812        assert!(chain_advances(&Err(anyhow::anyhow!("spawn failed"))));
4813        assert!(chain_advances(&Ok(output("limit", 0, true))));
4814        assert!(chain_advances(&Ok(output("", 0, false))));
4815        assert!(chain_advances(&Ok(output("x", 1, false))));
4816        assert!(!chain_advances(&Ok(output("answer", 0, false))));
4817    }
4818
4819    #[test]
4820    fn claude_context_tokens_are_unknown_because_usage_is_aggregated() {
4821        for out in [
4822            r#"{"result":"ok","num_turns":1,"usage":{"input_tokens":10,"cache_read_input_tokens":3000}}"#,
4823            r#"{"result":"ok","num_turns":3,"usage":{"input_tokens":10}}"#,
4824            r#"{"result":"ok"}"#,
4825            "not json",
4826        ] {
4827            assert_eq!(context_tokens(AgentKind::Claude, out), None, "{out}");
4828        }
4829    }
4830
4831    #[test]
4832    fn opencode_context_tokens_take_the_last_step_finish() {
4833        let out = concat!(
4834            r#"{"type":"step_finish","sessionID":"s","part":{"type":"step-finish","tokens":{"input":100,"output":5,"cache":{"read":1000,"write":50}}}}"#,
4835            "\n",
4836            r#"{"type":"text","part":{"type":"text","text":"hi"}}"#,
4837            "\n",
4838            r#"{"type":"step_finish","sessionID":"s","part":{"type":"step-finish","tokens":{"input":120,"output":9,"cache":{"read":1500}}}}"#,
4839            "\n"
4840        );
4841        assert_eq!(context_tokens(AgentKind::Opencode, out), Some(1620));
4842        let none = r#"{"type":"step_finish","part":{"type":"step-finish"}}"#;
4843        assert_eq!(context_tokens(AgentKind::Opencode, none), None);
4844        assert_eq!(context_tokens(AgentKind::Opencode, ""), None);
4845    }
4846
4847    #[test]
4848    fn agy_context_tokens_are_unknown_because_usage_is_aggregated() {
4849        let out = r#"{"conversation_id":"c","status":"OK","response":"x","usage":{"input_tokens":260113,"cache_read_tokens":2200925}}"#;
4850        assert_eq!(context_tokens(AgentKind::Antigravity, out), None);
4851    }
4852
4853    #[test]
4854    fn codex_context_tokens_are_unknown_because_usage_is_cumulative() {
4855        let out = concat!(
4856            r#"{"type":"turn.completed","usage":{"input_tokens":1000,"cached_input_tokens":900}}"#,
4857            "\n"
4858        );
4859        assert_eq!(context_tokens(AgentKind::Codex, out), None);
4860    }
4861
4862    #[test]
4863    fn omp_context_tokens_come_from_messages_without_an_agent_end() {
4864        let out = concat!(
4865            r#"{"type":"session","id":"s"}"#,
4866            "\n",
4867            r#"{"type":"message_end","message":{"role":"assistant","content":[],"usage":{"input":50,"cacheRead":400,"cacheWrite":10}}}"#,
4868            "\n",
4869            r#"{"type":"turn_end","message":{"role":"assistant","content":[],"usage":{"input":70,"cacheRead":500}}}"#,
4870            "\n"
4871        );
4872        assert_eq!(context_tokens(AgentKind::Omp, out), Some(570));
4873        let user_only = r#"{"type":"message_end","message":{"role":"user","usage":{"input":9}}}"#;
4874        assert_eq!(context_tokens(AgentKind::Omp, user_only), None);
4875        let no_usage = r#"{"type":"message_end","message":{"role":"assistant","content":[]}}"#;
4876        assert_eq!(context_tokens(AgentKind::Omp, no_usage), None);
4877    }
4878
4879    #[test]
4880    fn command_agents_report_no_context_tokens() {
4881        let out = r#"{"usage":{"input_tokens":5}}"#;
4882        assert_eq!(context_tokens(AgentKind::Command, out), None);
4883    }
4884}