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