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