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