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