Skip to main content

magi/
agent.rs

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