Skip to main content

agentmux_srv_core/agents/
failure.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Classification of agent (Claude CLI) run failures into a small,
5//! stable taxonomy with a human-readable explanation.
6//!
7//! `classify()` is a **pure** function: it takes the exit code, the
8//! terminating signal, the tail of the child's stderr, and an optional
9//! terminal `result` frame, and returns an [`AgentFailure`]. It does no
10//! IO and is exhaustively unit-tested against the real Anthropic error
11//! phrasings, so the "why" behind a non-zero exit can be surfaced to the
12//! user instead of a bare `exit 1`.
13//!
14//! See `docs/specs/SPEC_AGENT_FAILURE_DIAGNOSTICS_2026_06_11.md`. This
15//! is the P1 (capture + classify) slice; live-stream emission and UI
16//! banners are P2/P3.
17
18use serde::{Deserialize, Serialize};
19use serde_json::Value;
20
21/// Stable failure taxonomy. Wire format is snake_case to match the rest
22/// of the agent event surface (`frontend/types/srv-types.d.ts`).
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
24#[ts(export, export_to = "../../../frontend/types/rpc/")]
25#[serde(rename_all = "snake_case")]
26pub enum FailureClass {
27    /// Server-side rate limit (HTTP 429). Transient, not the account quota.
28    RateLimited,
29    /// API overloaded (HTTP 529). Transient.
30    Overloaded,
31    /// Plan / usage / billing limit reached. Not transient.
32    UsageLimit,
33    /// Credentials rejected (HTTP 401).
34    Auth,
35    /// Conversation exceeded the model's context window.
36    ContextExceeded,
37    /// Hit the configured `--max-turns` cap.
38    MaxTurns,
39    /// Network / connectivity error reaching the API.
40    Network,
41    /// Killed by a signal (OOM killer or external stop).
42    Killed,
43    /// Exited cleanly but produced no final result.
44    NoOutput,
45    /// Could not launch the `claude` binary at all.
46    SpawnFailure,
47    /// Non-zero exit with no recognized cause.
48    UnknownNonZero,
49    /// The identity spawn gate refused: the pane's agent was deleted
50    /// (`SpawnGateError::AgentDeleted`, #3577). No process ran, and a retry
51    /// is refused identically — the pane is done.
52    AgentDeleted,
53    /// This agent is running in another AgentMux instance on this host, or
54    /// was just taken over by one
55    /// (`docs/specs/SPEC_AGENT_SINGLE_LIVE_INSTANCE_2026_09_24.md`). No
56    /// process ran here; a Retry is refused identically while the other
57    /// instance holds it — the recovery is Take over.
58    LiveElsewhere,
59    /// This agent is already open in another pane of this AgentMux, so this
60    /// pane cannot run it. No process ran here; a Retry is refused identically
61    /// while the other pane holds it. The recovery is to go to that pane
62    /// (`AgentFailure::holder_block_id`) or move the agent here.
63    OpenInOtherPane,
64}
65
66/// A classified agent failure: the class, a user-facing title + detail,
67/// the raw exit evidence, the stderr tail, and whether a retry is
68/// worth attempting.
69#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ts_rs::TS)]
70#[ts(export, export_to = "../../../frontend/types/rpc/")]
71#[serde(rename_all = "camelCase")]
72pub struct AgentFailure {
73    pub code: FailureClass,
74    pub title: String,
75    pub detail: String,
76    #[serde(skip_serializing_if = "Option::is_none")]
77    #[ts(optional)]
78    pub exit_code: Option<i32>,
79    #[serde(skip_serializing_if = "Option::is_none")]
80    #[ts(optional)]
81    pub signal: Option<i32>,
82    #[serde(skip_serializing_if = "String::is_empty")]
83    #[ts(as = "Option<String>", optional)]
84    pub stderr_tail: String,
85    pub retryable: bool,
86    /// When a `UsageLimit` lifts (unix ms), if the provider said
87    /// (`agents::limit_reset`). Set when the failure is stored, not by
88    /// [`classify`].
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    #[ts(optional, type = "number")]
91    pub resets_at_ms: Option<u64>,
92    /// The provider's name for the limit's window, such as `five_hour` or
93    /// `seven_day`.
94    #[serde(default, skip_serializing_if = "Option::is_none")]
95    #[ts(optional)]
96    pub limit_window: Option<String>,
97    /// For `OpenInOtherPane`: the block of the pane that holds the agent.
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    #[ts(optional)]
100    pub holder_block_id: Option<String>,
101}
102
103/// The title of a `UsageLimit` failure whose cause is a model route with no credits left (HTTP 402).
104pub const ROUTE_CREDITS_TITLE: &str = "The model route is out of credits";
105
106/// How long a route that answered 402 is held before a message may probe it again.
107pub(crate) const ROUTE_CREDITS_RETRY_MS: u64 = 10 * 60 * 1000;
108
109impl AgentFailure {
110    /// Whether this is the route-out-of-credits failure: the route's key has no balance, whoever asks.
111    pub(crate) fn is_route_credits(&self) -> bool {
112        self.code == FailureClass::UsageLimit && self.title == ROUTE_CREDITS_TITLE
113    }
114
115    /// Render the single-string explanation that becomes a run's
116    /// terminal error (drone `error` column, sidecar log, future agent
117    /// pane banner). Title + detail + exit evidence + retryable hint,
118    /// followed by the raw stderr tail so the original text is never
119    /// more than a glance away.
120    pub fn explain(&self) -> String {
121        let mut s = self.title.clone();
122        if !self.detail.is_empty() {
123            s.push_str(" — ");
124            s.push_str(&self.detail);
125        }
126        match (self.signal, self.exit_code) {
127            (Some(sig), _) => s.push_str(&format!(" [signal {sig}]")),
128            (None, Some(code)) => s.push_str(&format!(" [exit {code}]")),
129            (None, None) => {}
130        }
131        if self.retryable {
132            s.push_str(" (retryable)");
133        }
134        if !self.stderr_tail.is_empty() {
135            s.push_str("\n--- claude stderr (tail) ---\n");
136            s.push_str(&self.stderr_tail);
137        }
138        s
139    }
140}
141
142/// Classify an agent run failure.
143///
144/// `exit_code` / `signal` come from the child's `ExitStatus`. `stderr`
145/// is the captured (capped) child stderr. `result_frame` is the
146/// terminal stream-json `result` object when one was seen — the CLI
147/// sometimes reports an error there while still exiting 0, so it is
148/// folded into the evidence.
149pub fn classify(
150    exit_code: Option<i32>,
151    signal: Option<i32>,
152    stderr: &str,
153    result_frame: Option<&Value>,
154) -> AgentFailure {
155    let frame_reported_error = result_frame.is_some_and(is_error_result_frame);
156    let frame_text = result_frame.map(frame_error_text).unwrap_or_default();
157
158    let combined = if frame_text.is_empty() {
159        stderr.to_string()
160    } else {
161        format!("{stderr}\n{frame_text}")
162    };
163    let tail = tail_lines(&combined, 24, 1600);
164    let hay = combined.to_ascii_lowercase();
165
166    let evidence = rules::Evidence { exit_code, signal, result_frame, frame_reported_error, combined, hay, tail };
167    rules::RULES.iter().find_map(|rule| rule(&evidence)).unwrap_or_else(|| rules::fallback(&evidence))
168}
169
170/// Whether `hay` (lower-cased) says the plan itself is out: the phrases a usage limit uses, without
171/// the broad words (`quota`, `billing`, `insufficient`) the limit branch also takes.
172fn names_plan_limit(hay: &str) -> bool {
173    hay.contains("usage limit")
174        || hay.contains("weekly limit")
175        || hay.contains("session limit")
176        || hay.contains("spend limit")
177        || hay.contains("out of credits")
178        // "You've hit your limit", "hit your 5-hour limit", "hit your Opus limit": whatever window it names.
179        || names_hit_your_limit(hay)
180        || ["5-hour limit", "five-hour limit", "5 hour limit", "daily limit", "monthly limit"].iter().any(|w| hay.contains(w))
181}
182
183/// "hit your <window> limit": the plan's, unless what it names is a rate: "You've hit your rate limit" (or a
184/// requests-, tokens- or concurrency limit) clears in seconds and is the transient class.
185fn names_hit_your_limit(hay: &str) -> bool {
186    let Some(at) = hay.find("hit your") else { return false };
187    let rest = &hay[at + "hit your".len()..];
188    let Some(end) = rest.find("limit") else { return false };
189    let named = &rest[..end];
190    !["rate", "request", "token", "concurren", "per minute", "per second"].iter().any(|w| named.contains(w))
191}
192
193/// Whether `hay` (lower-cased) is the server's own throttle, which says in so many words that it is not the plan's
194/// limit ("temporarily limiting requests (not your usage limit)"): it contains "usage limit" and must not read as one.
195fn names_server_throttle(hay: &str) -> bool {
196    hay.contains("not your usage limit") || hay.contains("not your plan limit") || hay.contains("not your quota")
197}
198
199/// Whether `hay` (lower-cased) is a provider saying the key's balance is empty: HTTP 402 with a credit or balance
200/// word, or the phrases routes use for it ("This request would exceed your available credits", DeepSeek's
201/// "Insufficient Balance"). A plan limit that tells the person to buy credits ("purchase more credits") is not it.
202fn names_route_credits(hay: &str) -> bool {
203    (mentions_http_status(hay, "402") && ["credit", "balance", "payment", "fund"].iter().any(|w| hay.contains(w)))
204        || hay.contains("payment required")
205        || hay.contains("exceed your available credits")
206        || hay.contains("requires more credits")
207        || hay.contains("insufficient credits")
208        || hay.contains("insufficient balance")
209}
210
211#[allow(clippy::too_many_arguments)]
212fn build(
213    code: FailureClass,
214    title: &str,
215    detail: &str,
216    retryable: bool,
217    exit_code: Option<i32>,
218    signal: Option<i32>,
219    tail: &str,
220) -> AgentFailure {
221    AgentFailure {
222        code,
223        title: title.to_string(),
224        detail: detail.to_string(),
225        exit_code,
226        signal,
227        stderr_tail: tail.to_string(),
228        retryable,
229        resets_at_ms: None,
230        limit_window: None,
231        holder_block_id: None,
232    }
233}
234
235/// Pulls the provider id out of `SpawnGateError::MissingCredentials`'s own
236/// Display wording ("no credentials for {provider}: the bound account was
237/// deleted or is unresolvable. Bind an account for this provider in
238/// Connectors → Accounts." — identity/resolver/errors.rs). Returns `None` on any mismatch
239/// (e.g. that wording drifts) rather than guessing — callers fall back to
240/// generic phrasing instead of asserting a specific, possibly wrong,
241/// provider name.
242fn extract_spawn_gate_provider(combined: &str) -> Option<String> {
243    let marker = "no credentials for ";
244    let start = combined.find(marker)? + marker.len();
245    let rest = &combined[start..];
246    let end = rest.find(':')?;
247    let provider = rest[..end].trim();
248    if provider.is_empty() {
249        None
250    } else {
251        Some(provider.to_string())
252    }
253}
254
255/// Pulls the provider id out of
256/// `SpawnGateError::AmbientHomeDirNotAllowed`'s own Display wording
257/// ("this agent's {provider} identity points directly at your personal …" —
258/// identity/resolver/errors.rs). Same "return None on any mismatch rather
259/// than guessing" contract as `extract_spawn_gate_provider` above.
260fn extract_ambient_home_provider(combined: &str) -> Option<String> {
261    let marker = "this agent's ";
262    let start = combined.find(marker)? + marker.len();
263    let rest = &combined[start..];
264    let end = rest.find(" identity points directly")?;
265    let provider = rest[..end].trim();
266    if provider.is_empty() {
267        None
268    } else {
269        Some(provider.to_string())
270    }
271}
272
273/// Pulls the provider id out of
274/// `SpawnGateError::ClaudeMdSeedFailed`'s own Display wording ("could not
275/// isolate this agent's {provider} config directory (…): …").
276fn extract_claude_md_seed_provider(combined: &str) -> Option<String> {
277    let marker = "could not isolate this agent's ";
278    let start = combined.find(marker)? + marker.len();
279    let rest = &combined[start..];
280    let end = rest.find(" config directory")?;
281    let provider = rest[..end].trim();
282    if provider.is_empty() {
283        None
284    } else {
285        Some(provider.to_string())
286    }
287}
288
289/// Title-cases a raw provider id ("claude" -> "Claude") for the
290/// spawn-gate message. reagent P2 on PR #2413: the raw lowercase slug
291/// read poorly next to catalog.ts's real display names ("Claude Code",
292/// "Gemini CLI"); this doesn't reach for those (Rust has no access to
293/// the frontend catalog and duplicating/syncing the full display-name
294/// table across languages is disproportionate for one error string) —
295/// just enough prettification that the message reads as a proper noun.
296fn capitalize_provider(id: &str) -> String {
297    let mut chars = id.chars();
298    match chars.next() {
299        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
300        None => id.to_string(),
301    }
302}
303
304/// Best-effort error text from a terminal stream-json `result` frame: every field that can carry the cause
305/// (`error.message`, a string `error`, a string `result`, the first of `errors`), each once, one per line; the
306/// `subtype` only when none of them says anything. The CLI puts a cause in one of them and a generic word in
307/// another, so reading only the first hid a limit sentence in `result` behind an `error` of "rate_limit"'s kind.
308fn frame_error_text(frame: &Value) -> String {
309    let fields = [
310        frame.pointer("/error/message").and_then(|v| v.as_str()),
311        frame.get("error").and_then(|v| v.as_str()),
312        frame.get("result").and_then(|v| v.as_str()),
313        first_cli_error(frame),
314    ];
315    let mut parts: Vec<&str> = Vec::new();
316    for text in fields.into_iter().flatten().filter(|t| !t.trim().is_empty()) {
317        if !parts.contains(&text) {
318            parts.push(text);
319        }
320    }
321    if parts.is_empty() {
322        return frame.get("subtype").and_then(|v| v.as_str()).unwrap_or_default().to_string();
323    }
324    parts.join("\n")
325}
326
327/// The first entry of a result frame's `errors` list, where Claude Code puts
328/// its own failures before any turn ("No conversation found with session ID:
329/// …").
330pub(crate) fn first_cli_error(frame: &Value) -> Option<&str> {
331    frame.get("errors")?.as_array()?.iter().find_map(|e| e.as_str().filter(|s| !s.is_empty()))
332}
333
334/// What a turn that ended with a tool call still pending reads as.
335pub(crate) const CUT_OFF_TEXT: &str = "This turn was cut off mid-tool, so it didn't finish.";
336
337/// A `result` line the CLI wrote for a turn it found cut off with a tool call
338/// pending (a restart or an upgrade interrupted it): `Error [ede_diagnostic]
339/// result_type=user last_content_type=n/a stop_reason=tool_use`. It is not a
340/// failure of the agent, so it is returned as an ordinary end of turn saying
341/// so, with the CLI's own text beside it for the log. `None` for any other line.
342pub(crate) fn plain_cut_off(line: &str) -> Option<(String, String)> {
343    if !line.contains("[ede_diagnostic]") {
344        return None;
345    }
346    let mut frame: Value = serde_json::from_str(line).ok()?;
347    // An error result only: a turn that finished and quotes the diagnostic is left as it is.
348    if frame.get("type").and_then(|v| v.as_str()) != Some("result") || !is_error_result_frame(&frame) {
349        return None;
350    }
351    let diagnostic = frame_error_text(&frame);
352    if !(diagnostic.contains("[ede_diagnostic]") && diagnostic.contains("stop_reason=tool_use")) {
353        return None;
354    }
355    let object = frame.as_object_mut()?;
356    object.insert("is_error".into(), Value::Bool(false));
357    object.insert("subtype".into(), Value::String("success".into()));
358    object.insert("result".into(), Value::String(CUT_OFF_TEXT.into()));
359    object.remove("errors");
360    object.remove("error");
361    Some((diagnostic, frame.to_string()))
362}
363
364/// True if a terminal `result` frame represents a failure.
365pub(crate) fn is_error_result_frame(frame: &Value) -> bool {
366    frame.get("is_error").and_then(|v| v.as_bool()).unwrap_or(false)
367        || frame
368            .get("subtype")
369            .and_then(|v| v.as_str())
370            .is_some_and(|s| s.starts_with("error"))
371}
372
373/// Last `max_lines` non-empty lines of `s`, further capped to the last
374/// `max_chars` characters (char-safe — never slices mid-codepoint).
375fn tail_lines(s: &str, max_lines: usize, max_chars: usize) -> String {
376    let mut lines: Vec<&str> = s
377        .lines()
378        .map(|l| l.trim_end())
379        .filter(|l| !l.is_empty())
380        .collect();
381    if lines.len() > max_lines {
382        lines = lines.split_off(lines.len() - max_lines);
383    }
384    let joined = lines.join("\n");
385    let n = joined.chars().count();
386    if n > max_chars {
387        joined.chars().skip(n - max_chars).collect()
388    } else {
389        joined
390    }
391}
392
393/// True if `hay` mentions HTTP status `code` in a status-like context
394/// (e.g. "http 429", "status 429", "error 429", "[429]"). Anchoring on a
395/// context word avoids the false positives a bare substring would hit —
396/// an ISO date like `2026-04-29` contains "429". (reagent P2 on #1353.)
397fn mentions_http_status(hay: &str, code: &str) -> bool {
398    [
399        format!("http {code}"),
400        format!("http/1.1 {code}"),
401        format!("http/2 {code}"),
402        format!("status {code}"),
403        format!("status: {code}"),
404        format!("status code {code}"),
405        format!("code {code}"),
406        format!("code: {code}"),
407        format!("error {code}"),
408        format!("error: {code}"),
409        format!("[{code}]"),
410        format!("({code})"),
411    ]
412    .iter()
413    .any(|p| hay.contains(p.as_str()))
414}
415
416/// The block id in `held_elsewhere_error`'s "already open in another pane (block X)" refusal, when
417/// `text` is that refusal. The wording is ours, built in one place, so this reads it back.
418pub fn open_in_other_pane_holder(text: &str) -> Option<String> {
419    const MARKER: &str = "is already open in another pane (block ";
420    let rest = &text[text.find(MARKER)? + MARKER.len()..];
421    let id = rest[..rest.find(')')?].trim();
422    (!id.is_empty()).then(|| id.to_string())
423}
424
425#[path = "failure_rules.rs"]
426pub mod rules;
427
428#[cfg(test)]
429#[path = "failure_order_tests.rs"]
430mod order_tests;
431
432#[cfg(test)]
433mod tests {
434    use super::*;
435    use serde_json::json;
436
437    #[test]
438    fn rate_limit_incident_string_classifies_retryable() {
439        // The exact string this work was motivated by.
440        let stderr =
441            "API Error: Server is temporarily limiting requests (not your usage limit) · Rate limited";
442        let f = classify(Some(1), None, stderr, None);
443        assert_eq!(f.code, FailureClass::RateLimited);
444        assert!(f.retryable);
445        let e = f.explain();
446        assert!(e.contains("Rate-limited"), "explain: {e}");
447        assert!(e.contains("retryable"), "explain: {e}");
448        assert!(e.to_lowercase().contains("rate limited"), "explain: {e}");
449    }
450
451    #[test]
452    fn not_your_usage_limit_does_not_classify_as_usage_limit() {
453        // Guard: the rate-limit message contains "usage limit"; it must
454        // win as RateLimited (checked first), not UsageLimit.
455        let f = classify(
456            Some(1),
457            None,
458            "temporarily limiting requests (not your usage limit) · Rate limited",
459            None,
460        );
461        assert_eq!(f.code, FailureClass::RateLimited);
462    }
463
464    /// Claude's plan limits name no "usage limit": the account is out of
465    /// quota all the same (AgentMux saw this one on 2026-10-16).
466    #[test]
467    fn a_weekly_or_session_limit_is_the_plans_usage_limit() {
468        for stderr in [
469            "You've hit your weekly limit · resets Oct 19, 7pm (America/Los_Angeles)",
470            "You've hit your session limit · resets 3pm",
471            "Claude AI usage limit reached|1792156633",
472            // Extra usage capped: it works again when the exhausted window resets.
473            "You've hit your monthly spend limit · raise it at claude.ai/settings/usage",
474        ] {
475            let f = classify(Some(1), None, stderr, None);
476            assert_eq!(f.code, FailureClass::UsageLimit, "{stderr}");
477            assert!(!f.retryable, "{stderr}");
478        }
479    }
480
481    /// A context failure whose compaction died on the plan's limit is the limit: failover moves the
482    /// agent, and the next turn compacts on an account with quota (seen on a container agent, 0.60.7).
483    #[test]
484    fn a_compaction_that_failed_on_the_weekly_limit_is_a_usage_limit() {
485        let stderr = "Prompt is too long · automatic compaction failed: You've hit your weekly limit · resets Nov 3";
486        let f = classify(Some(1), None, stderr, None);
487        assert_eq!(f.code, FailureClass::UsageLimit, "{f:?}");
488        assert!(!f.retryable);
489        // The same phrases with no limit in them are still the context window.
490        for plain in ["Prompt is too long", "model_context_window_exceeded", "automatic compaction failed: prompt is too long"] {
491            assert_eq!(classify(Some(1), None, plain, None).code, FailureClass::ContextExceeded, "{plain}");
492        }
493    }
494
495    #[test]
496    fn iso_date_in_stderr_does_not_false_positive() {
497        // "2026-04-29" contains "429"; "2026-04-01" -> "401";
498        // "2026-05-29" -> "529". A bare substring match would misclassify
499        // these; anchored matching must not. (reagent P2 on #1353.)
500        for stderr in [
501            "panic at 2026-04-29T10:00:00: unexpected eof",
502            "build 2026-04-01 failed: assertion",
503            "ts=2026-05-29 fatal: segfault",
504        ] {
505            let f = classify(Some(2), None, stderr, None);
506            assert_eq!(
507                f.code,
508                FailureClass::UnknownNonZero,
509                "stderr {stderr:?} must not match an HTTP status"
510            );
511        }
512    }
513
514    #[test]
515    fn anchored_http_status_still_classifies() {
516        assert_eq!(
517            classify(Some(1), None, "Error: HTTP 429 Too Many Requests", None).code,
518            FailureClass::RateLimited
519        );
520        assert_eq!(
521            classify(Some(1), None, "request failed with status 401", None).code,
522            FailureClass::Auth
523        );
524    }
525
526    #[test]
527    fn overloaded_is_retryable() {
528        let f = classify(Some(1), None, "overloaded_error: please retry", None);
529        assert_eq!(f.code, FailureClass::Overloaded);
530        assert!(f.retryable);
531    }
532
533    #[test]
534    fn invalid_api_key_is_auth_not_retryable() {
535        let f = classify(Some(1), None, "authentication_error: Invalid API key provided", None);
536        assert_eq!(f.code, FailureClass::Auth);
537        assert!(!f.retryable);
538    }
539
540    #[test]
541    fn sigkill_is_killed() {
542        let f = classify(None, Some(9), "", None);
543        assert_eq!(f.code, FailureClass::Killed);
544        assert_eq!(f.signal, Some(9));
545        assert!(f.explain().contains("[signal 9]"));
546    }
547
548    #[test]
549    fn exit_137_is_killed() {
550        let f = classify(Some(137), None, "", None);
551        assert_eq!(f.code, FailureClass::Killed);
552    }
553
554    #[test]
555    fn context_window_exceeded_classifies() {
556        let f = classify(
557            Some(1),
558            None,
559            "prompt is too long: 1200000 tokens > 200000 maximum context window",
560            None,
561        );
562        assert_eq!(f.code, FailureClass::ContextExceeded);
563    }
564
565    #[test]
566    fn network_error_is_retryable() {
567        let f = classify(Some(1), None, "APIConnectionError: Connection error.", None);
568        assert_eq!(f.code, FailureClass::Network);
569        assert!(f.retryable);
570    }
571
572    const CONNECTION_REFUSED: &str =
573        "API Error: Connection refused — a firewall or proxy may be blocking it (ECONNREFUSED)";
574
575    #[test]
576    fn connection_refused_after_the_cli_gave_up_is_network() {
577        let f = classify(Some(1), None, CONNECTION_REFUSED, None);
578        assert_eq!(f.code, FailureClass::Network);
579        assert!(f.retryable);
580        // The same text in the result frame the persistent controller classifies.
581        let frame = json!({
582            "type": "result",
583            "subtype": "success",
584            "is_error": true,
585            "result": CONNECTION_REFUSED,
586        });
587        let f = classify(None, None, "", Some(&frame));
588        assert_eq!(f.code, FailureClass::Network);
589        assert!(f.retryable);
590    }
591
592    #[test]
593    fn unable_to_connect_is_network() {
594        for text in [
595            "Unable to connect to API (ConnectionRefused)",
596            "Unable to connect to API (ECONNRESET)",
597        ] {
598            let f = classify(Some(1), None, text, None);
599            assert_eq!(f.code, FailureClass::Network, "{text}");
600            assert!(f.retryable, "{text}");
601        }
602    }
603
604    #[test]
605    fn unable_to_connect_elsewhere_is_not_network() {
606        let f = classify(Some(1), None, "Unable to connect to MCP server", None);
607        assert_ne!(f.code, FailureClass::Network);
608    }
609
610    #[test]
611    fn socket_error_codes_are_network() {
612        for code in ["ECONNREFUSED", "ENOTFOUND", "ENETUNREACH", "EHOSTUNREACH", "ETIMEDOUT"] {
613            let f = classify(Some(1), None, &format!("Error: connect {code} api.anthropic.com"), None);
614            assert_eq!(f.code, FailureClass::Network, "{code}");
615            assert!(f.retryable, "{code}");
616        }
617    }
618
619    #[test]
620    fn clean_exit_no_output_is_no_output() {
621        let f = classify(Some(0), None, "", None);
622        assert_eq!(f.code, FailureClass::NoOutput);
623        assert!(!f.retryable);
624    }
625
626    #[test]
627    fn unknown_nonzero_is_default() {
628        let f = classify(Some(2), None, "something unexpected happened", None);
629        assert_eq!(f.code, FailureClass::UnknownNonZero);
630        assert!(f.explain().contains("[exit 2]"));
631    }
632
633    #[test]
634    fn authentication_failed_string_is_auth() {
635        // In-band 401: claude wraps the error in a synthetic assistant message
636        // with `"error":"authentication_failed"`. The inband_text is appended
637        // to the stderr tail before classify() is called, so it must match.
638        let f = classify(
639            Some(0),
640            None,
641            "authentication_failed Failed to authenticate. API Error: 401 Invalid authentication credentials",
642            None,
643        );
644        assert_eq!(f.code, FailureClass::Auth);
645        assert!(!f.retryable);
646    }
647
648    /// A login that expired and couldn't refresh is a sign-in failure, also when it is the compaction that
649    /// found out (so a move to a valid login follows, and the next turn compacts again).
650    #[test]
651    fn an_expired_login_is_auth_also_when_a_compaction_found_out() {
652        for stderr in [
653            "Failed to authenticate: OAuth session expired and could not be refreshed",
654            "Prompt is too long · automatic compaction failed: Failed to authenticate: OAuth session expired and could not be refreshed",
655        ] {
656            assert_eq!(classify(Some(1), None, stderr, None).code, FailureClass::Auth, "{stderr}");
657        }
658        assert_eq!(classify(Some(1), None, "Prompt is too long", None).code, FailureClass::ContextExceeded);
659    }
660
661    #[test]
662    fn invalid_authentication_credentials_is_auth() {
663        let f = classify(Some(0), None, "invalid authentication credentials", None);
664        assert_eq!(f.code, FailureClass::Auth);
665    }
666
667    #[test]
668    fn api_error_colon_401_is_auth() {
669        // "API Error: 401" lowercased → "api error: 401" → matches "error: 401".
670        let f = classify(Some(0), None, "api error: 401 invalid authentication credentials", None);
671        assert_eq!(f.code, FailureClass::Auth);
672    }
673
674    /// #3577: the gate's deleted-agent refusal gets its own class and no
675    /// Retry — a retry is refused identically, a dead end.
676    #[test]
677    fn spawn_gate_agent_deleted_is_its_own_class_and_not_retryable() {
678        let msg = crate::identity::resolver::SpawnGateError::AgentDeleted {
679            agent_id: "uid-x".to_string(),
680        }
681        .to_string();
682        let f = classify(None, None, &msg, None);
683        assert_eq!(f.code, FailureClass::AgentDeleted);
684        assert!(!f.retryable);
685    }
686
687    /// SPEC_AGENT_SINGLE_LIVE_INSTANCE_2026_09_24 Phase 2: a refusal because
688    /// the agent runs elsewhere gets its own class — the row offers Take
689    /// over, never a Retry that is refused identically.
690    #[test]
691    fn a_single_live_instance_refusal_is_its_own_class() {
692        let msg = crate::backend::agent_admission::denied_message("Agent3", None);
693        let f = classify(None, None, &msg, None);
694        assert_eq!(f.code, FailureClass::LiveElsewhere);
695        assert_eq!(f.title, "Running in another AgentMux instance");
696        assert_eq!(f.detail, msg, "the detail is the refusal itself, naming the holder");
697        assert!(!f.retryable);
698        // Wrapped the way run_agent_turn persists it.
699        let framed = format!("[AgentMux] {msg}");
700        assert_eq!(classify(None, None, &framed, None).code, FailureClass::LiveElsewhere);
701        let taken = "Agent3 was taken over by another AgentMux instance on this host (channel x).";
702        assert_eq!(classify(None, None, taken, None).title, "Taken over by another AgentMux instance");
703        assert_eq!(serde_json::to_value(FailureClass::LiveElsewhere).unwrap(), "live_elsewhere");
704    }
705
706    #[test]
707    fn spawn_gate_missing_credentials_is_auth_not_unknown() {
708        // Exact frame shape agent_handlers/input.rs emits for a
709        // SpawnGateError::MissingCredentials refusal (identity/resolver/
710        // errors.rs's Display impl) — before this branch existed, this
711        // frame had no recognized keyword and fell through to
712        // UnknownNonZero, which offers only "Retry" against a gate that
713        // blocks every respawn identically: a permanently stuck pane with
714        // no relogin affordance.
715        let frame = json!({
716            "type": "result",
717            "is_error": true,
718            "subtype": "error_during_execution",
719            "error": { "message": "[AgentMux] no credentials for claude: the bound account was deleted or is unresolvable. Bind an account for this provider in Connectors → Accounts." }
720        });
721        let f = classify(Some(1), None, "", Some(&frame));
722        assert_eq!(f.code, FailureClass::Auth);
723        assert!(f.detail.contains("Claude"), "detail: {}", f.detail);
724    }
725
726    /// Both wordings of the refusal, an agent with no link and a link to a
727    /// gone account, classify the same way, from the gate's own Display.
728    #[test]
729    fn spawn_gate_refusal_classifies_the_same_with_or_without_a_link() {
730        use crate::identity::resolver::SpawnGateError;
731        for linked in [false, true] {
732            let refusal = SpawnGateError::MissingCredentials { provider: "codex".to_string(), linked };
733            let frame = json!({
734                "type": "result",
735                "is_error": true,
736                "subtype": "error_during_execution",
737                "error": { "message": format!("[AgentMux] {refusal}") }
738            });
739            let f = classify(Some(1), None, "", Some(&frame));
740            assert_eq!(f.code, FailureClass::Auth, "linked={linked}: {refusal}");
741            assert!(f.detail.contains("Codex"), "linked={linked}: {}", f.detail);
742        }
743        let unlinked = SpawnGateError::MissingCredentials { provider: "claude".to_string(), linked: false };
744        assert!(!unlinked.to_string().contains("deleted"), "{unlinked}");
745    }
746
747    #[test]
748    fn spawn_gate_missing_credentials_from_before_the_armory_split_still_classifies() {
749        // A failure recorded while the message still said "in the Armory".
750        let frame = json!({
751            "type": "result",
752            "is_error": true,
753            "subtype": "error_during_execution",
754            "error": { "message": "[AgentMux] no credentials for codex: the bound account was deleted or is unresolvable. Bind an account for this provider in the Armory." }
755        });
756        let f = classify(Some(1), None, "", Some(&frame));
757        assert_eq!(f.code, FailureClass::Auth);
758        assert!(f.detail.contains("Codex"), "detail: {}", f.detail);
759    }
760
761    #[test]
762    fn spawn_gate_missing_credentials_names_the_actual_provider_not_claude() {
763        // codex P2 on PR #2413: this branch matches EVERY oauth-class
764        // provider's refusal, not just Claude's — a prior version
765        // hardcoded "No Claude account is bound" regardless of which
766        // provider the gate actually named.
767        let frame = json!({
768            "type": "result",
769            "is_error": true,
770            "subtype": "error_during_execution",
771            "error": { "message": "[AgentMux] no credentials for gemini: the bound account was deleted or is unresolvable. Bind an account for this provider in Connectors → Accounts." }
772        });
773        let f = classify(Some(1), None, "", Some(&frame));
774        assert_eq!(f.code, FailureClass::Auth);
775        assert!(f.detail.contains("Gemini"), "detail: {}", f.detail);
776        assert!(!f.detail.contains("Claude"), "detail: {}", f.detail);
777    }
778
779    #[test]
780    fn spawn_gate_ambient_home_dir_is_auth_not_unknown() {
781        // docs/specs/SPEC_BLOCK_AMBIENT_HOME_DIR_IDENTITY_BINDING_2026_08_25.md
782        // — same "must not fall through to a dead-end Retry" reasoning as
783        // the MissingCredentials branch above, for the sibling
784        // AmbientHomeDirNotAllowed gate refusal (identity/resolver/errors.rs).
785        let frame = json!({
786            "type": "result",
787            "is_error": true,
788            "subtype": "error_during_execution",
789            "error": { "message": "[AgentMux] this agent's claude identity points directly at your personal claude config directory (C:\\Users\\user\\.claude) instead of an isolated AgentMux account — AgentMux no longer allows spawning an agent against your own global CLI login. Re-bind this identity to an isolated account in Connectors \u{2192} Accounts (delete the current claude account and log in again to create a fresh, isolated one), then retry." }
790        });
791        let f = classify(Some(1), None, "", Some(&frame));
792        assert_eq!(f.code, FailureClass::Auth);
793        assert!(!f.retryable, "a bare retry can never succeed against this gate");
794        assert!(f.detail.contains("Claude"), "detail: {}", f.detail);
795        assert!(f.title.to_lowercase().contains("identity"), "title: {}", f.title);
796    }
797
798    #[test]
799    fn spawn_gate_ambient_home_dir_names_the_actual_provider_not_claude() {
800        let frame = json!({
801            "type": "result",
802            "is_error": true,
803            "subtype": "error_during_execution",
804            "error": { "message": "[AgentMux] this agent's codex identity points directly at your personal codex config directory (/home/user/.codex) instead of an isolated AgentMux account — AgentMux no longer allows spawning an agent against your own global CLI login. Re-bind this identity to an isolated account in Connectors \u{2192} Accounts (delete the current codex account and log in again to create a fresh, isolated one), then retry." }
805        });
806        let f = classify(Some(1), None, "", Some(&frame));
807        assert_eq!(f.code, FailureClass::Auth);
808        assert!(f.detail.contains("Codex"), "detail: {}", f.detail);
809        assert!(!f.detail.contains("Claude"), "detail: {}", f.detail);
810    }
811
812    #[test]
813    fn spawn_gate_claude_md_seed_failed_is_auth_not_unknown() {
814        // docs/specs/SPEC_ISOLATE_HOST_CLAUDE_MD_2026_08_31.md — ReAgent P2
815        // on PR #2854: this newer SpawnGateError variant had no
816        // classification branch, so it fell through to the generic
817        // UnknownNonZero "Agent failed" instead of the guidance its own
818        // Display text already carries. Same "must not fall through to a
819        // dead-end Retry" reasoning as its MissingCredentials/
820        // AmbientHomeDirNotAllowed siblings above.
821        let frame = json!({
822            "type": "result",
823            "is_error": true,
824            "subtype": "error_during_execution",
825            "error": { "message": "[AgentMux] could not isolate this agent's claude config directory (C:\\Users\\user\\.agentmux\\shared\\identities\\id-1\\claude): permission denied. Refusing to spawn with an unprotected config dir — retry, and check the directory's permissions if it persists." }
826        });
827        let f = classify(Some(1), None, "", Some(&frame));
828        assert_eq!(f.code, FailureClass::Auth);
829        assert!(!f.retryable, "a bare retry may not succeed against a persistent permissions issue");
830        assert!(f.detail.contains("Claude"), "detail: {}", f.detail);
831        assert!(f.title.to_lowercase().contains("isolate"), "title: {}", f.title);
832    }
833
834    #[test]
835    fn spawn_gate_claude_md_seed_failed_names_the_actual_provider_not_claude() {
836        let frame = json!({
837            "type": "result",
838            "is_error": true,
839            "subtype": "error_during_execution",
840            "error": { "message": "[AgentMux] could not isolate this agent's codex config directory (/home/user/.agentmux/shared/providers/codex): permission denied. Refusing to spawn with an unprotected config dir — retry, and check the directory's permissions if it persists." }
841        });
842        let f = classify(Some(1), None, "", Some(&frame));
843        assert_eq!(f.code, FailureClass::Auth);
844        assert!(f.detail.contains("Codex"), "detail: {}", f.detail);
845        assert!(!f.detail.contains("Claude"), "detail: {}", f.detail);
846    }
847
848    #[test]
849    fn extract_claude_md_seed_provider_reads_the_provider_out_of_the_gate_wording() {
850        assert_eq!(
851            extract_claude_md_seed_provider(
852                "could not isolate this agent's gemini config directory (/x): some io error."
853            ),
854            Some("gemini".to_string()),
855        );
856    }
857
858    #[test]
859    fn extract_claude_md_seed_provider_returns_none_on_wording_mismatch() {
860        assert_eq!(extract_claude_md_seed_provider("some unrelated error text"), None);
861    }
862
863    #[test]
864    fn extract_ambient_home_provider_reads_the_provider_out_of_the_gate_wording() {
865        assert_eq!(
866            extract_ambient_home_provider(
867                "this agent's gemini identity points directly at your personal gemini config directory (/x)."
868            ),
869            Some("gemini".to_string()),
870        );
871    }
872
873    #[test]
874    fn extract_ambient_home_provider_returns_none_on_wording_mismatch() {
875        assert_eq!(extract_ambient_home_provider("some unrelated error text"), None);
876    }
877
878    #[test]
879    fn capitalize_provider_title_cases_the_raw_id() {
880        assert_eq!(capitalize_provider("claude"), "Claude");
881        assert_eq!(capitalize_provider("gemini"), "Gemini");
882        assert_eq!(capitalize_provider(""), "");
883    }
884
885    #[test]
886    fn spawn_gate_injection_unavailable_is_not_auth() {
887        // The gate's OTHER error variant — a task-join/panic failure, not a
888        // credentials problem — must not be swept into the same match.
889        let frame = json!({
890            "type": "result",
891            "is_error": true,
892            "subtype": "error_during_execution",
893            "error": { "message": "[AgentMux] credential injection could not run (panic); the spawn was refused rather than falling back to the global CLI login. Retry, and check `muxlog auth` if it persists." }
894        });
895        let f = classify(Some(1), None, "", Some(&frame));
896        assert_eq!(f.code, FailureClass::UnknownNonZero);
897    }
898
899    #[test]
900    fn result_frame_max_turns_subtype() {
901        let frame = json!({ "type": "result", "is_error": true, "subtype": "error_max_turns" });
902        let f = classify(Some(0), None, "", Some(&frame));
903        assert_eq!(f.code, FailureClass::MaxTurns);
904    }
905
906    #[test]
907    fn result_frame_error_message_feeds_classification() {
908        // CLI reported an overload on stdout but exited 0 — must still
909        // classify, not fall through to NoOutput.
910        let frame = json!({
911            "type": "result",
912            "is_error": true,
913            "subtype": "error_during_execution",
914            "error": { "message": "overloaded_error: upstream busy" }
915        });
916        let f = classify(Some(0), None, "", Some(&frame));
917        assert_eq!(f.code, FailureClass::Overloaded);
918    }
919
920    #[test]
921    fn tail_lines_keeps_last_lines_char_safe() {
922        let s = (0..100).map(|i| format!("line{i}")).collect::<Vec<_>>().join("\n");
923        let t = tail_lines(&s, 5, 1000);
924        assert_eq!(t.lines().count(), 5);
925        assert!(t.contains("line99"));
926        assert!(!t.contains("line0\n"));
927    }
928
929    #[test]
930    fn extract_spawn_gate_provider_reads_the_provider_out_of_the_gate_wording() {
931        assert_eq!(
932            extract_spawn_gate_provider(
933                "no credentials for codex: the bound account was deleted or is unresolvable."
934            ),
935            Some("codex".to_string()),
936        );
937    }
938
939    #[test]
940    fn extract_spawn_gate_provider_returns_none_on_wording_mismatch() {
941        assert_eq!(extract_spawn_gate_provider("some unrelated error text"), None);
942    }
943
944    /// The agent is open in another pane of this AgentMux: its own class, with that pane's block,
945    /// and never a Retry (the refusal is identical while the holder runs).
946    #[test]
947    fn open_in_another_pane_is_its_own_class_naming_the_holder() {
948        let msg = "This conversation is already open in another pane (block 96a441d2). Close it there, or switch to it, instead of opening a second copy.";
949        let f = classify(None, None, msg, None);
950        assert_eq!(f.code, FailureClass::OpenInOtherPane);
951        assert_eq!(f.holder_block_id.as_deref(), Some("96a441d2"));
952        assert!(!f.retryable);
953        let framed = classify(None, None, &format!("[AgentMux] {msg}"), None);
954        assert_eq!(framed.holder_block_id.as_deref(), Some("96a441d2"));
955        assert_eq!(serde_json::to_value(FailureClass::OpenInOtherPane).unwrap(), "open_in_other_pane");
956        assert_eq!(serde_json::to_value(&f).unwrap()["holderBlockId"], "96a441d2");
957        // The closing variant is a wait, not a pane to go to.
958        let closing = "This conversation's previous process (block 96a441d2) is still shutting down. Try again in a few seconds.";
959        assert_eq!(classify(None, None, closing, None).holder_block_id, None);
960    }
961
962    #[test]
963    fn serializes_snake_case_code_camel_fields() {
964        let f = classify(Some(1), None, "Rate limited", None);
965        let v = serde_json::to_value(&f).unwrap();
966        assert_eq!(v["code"], json!("rate_limited"));
967        assert_eq!(v["retryable"], json!(true));
968        assert!(v.get("stderrTail").is_some(), "camelCase stderrTail expected: {v}");
969    }
970
971    #[test]
972    fn a_turn_the_cli_found_cut_off_is_an_ordinary_end_of_turn_with_a_plain_text() {
973        let raw = r#"{"type":"result","subtype":"error_during_execution","is_error":true,"session_id":"s1","errors":["Error [ede_diagnostic] result_type=user last_content_type=n/a stop_reason=tool_use"]}"#;
974        let (diagnostic, plain) = plain_cut_off(raw).expect("a cut-off turn");
975        assert!(diagnostic.starts_with("Error [ede_diagnostic] result_type=user"), "{diagnostic}");
976        let frame: Value = serde_json::from_str(&plain).unwrap();
977        assert_eq!(frame["is_error"], Value::Bool(false));
978        assert_eq!(frame["result"], CUT_OFF_TEXT);
979        assert_eq!(frame["session_id"], "s1", "the rest of the line is kept");
980        assert!(frame.get("errors").is_none(), "{plain}");
981        assert!(!plain.contains("ede_diagnostic"), "{plain}");
982        // The text can be in `result` too.
983        let in_result = r#"{"type":"result","is_error":true,"result":"Error [ede_diagnostic] result_type=user last_content_type=n/a stop_reason=tool_use"}"#;
984        assert!(plain_cut_off(in_result).is_some());
985    }
986
987    #[test]
988    fn only_that_diagnostic_on_a_result_line_is_rewritten() {
989        // A real failure stays a failure.
990        assert!(plain_cut_off(r#"{"type":"result","is_error":true,"result":"API Error: 529 overloaded"}"#).is_none());
991        // Another diagnostic (not a pending tool call) stays as it is.
992        assert!(plain_cut_off(r#"{"type":"result","is_error":true,"result":"Error [ede_diagnostic] result_type=assistant stop_reason=end_turn"}"#).is_none());
993        // Not a result line: an assistant that quotes it is left alone.
994        assert!(plain_cut_off(r#"{"type":"assistant","message":{"content":[{"type":"text","text":"Error [ede_diagnostic] stop_reason=tool_use"}]}}"#).is_none());
995        assert!(plain_cut_off("not json [ede_diagnostic]").is_none());
996        assert!(plain_cut_off(r#"{"type":"result","is_error":false,"result":"done"}"#).is_none());
997        // A turn that finished and quotes the diagnostic in its answer is not one that was cut off.
998        assert!(plain_cut_off(r#"{"type":"result","subtype":"success","is_error":false,"result":"The CLI said Error [ede_diagnostic] result_type=user stop_reason=tool_use"}"#).is_none());
999    }
1000}
1001
1002/// The one line of `text` that carries a single-live-instance refusal, with
1003/// any `[AgentMux] ` prefix removed — the row's detail. Falls back to the
1004/// whole trimmed text.
1005fn frame_or_stderr_line(text: &str) -> &str {
1006    text.lines()
1007        .find(|l| crate::backend::agent_admission::is_admission_refusal(l))
1008        .map(|l| l.trim().trim_start_matches("[AgentMux]").trim())
1009        .unwrap_or_else(|| text.trim())
1010}