Skip to main content

magi/
agent.rs

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