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