1use serde::{Deserialize, Serialize};
19use serde_json::Value;
20
21#[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 RateLimited,
29 Overloaded,
31 UsageLimit,
33 Auth,
35 ContextExceeded,
37 MaxTurns,
39 Network,
41 Killed,
43 NoOutput,
45 SpawnFailure,
47 UnknownNonZero,
49 AgentDeleted,
53 LiveElsewhere,
59 OpenInOtherPane,
64}
65
66#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
90 #[ts(optional, type = "number")]
91 pub resets_at_ms: Option<u64>,
92 #[serde(default, skip_serializing_if = "Option::is_none")]
95 #[ts(optional)]
96 pub limit_window: Option<String>,
97 #[serde(default, skip_serializing_if = "Option::is_none")]
99 #[ts(optional)]
100 pub holder_block_id: Option<String>,
101}
102
103pub const ROUTE_CREDITS_TITLE: &str = "The model route is out of credits";
105
106pub(crate) const ROUTE_CREDITS_RETRY_MS: u64 = 10 * 60 * 1000;
108
109impl AgentFailure {
110 pub(crate) fn is_route_credits(&self) -> bool {
112 self.code == FailureClass::UsageLimit && self.title == ROUTE_CREDITS_TITLE
113 }
114
115 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
142pub 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
170fn 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 || 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
183fn 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
193fn 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
199fn 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
235fn 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
255fn 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
273fn 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
289fn 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
304fn 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
327pub(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
334pub(crate) const CUT_OFF_TEXT: &str = "This turn was cut off mid-tool, so it didn't finish.";
336
337pub(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 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
364pub(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
373fn 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
393fn 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
416pub 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 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 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 #[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 "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 #[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 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 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 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 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 #[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 let f = classify(Some(0), None, "api error: 401 invalid authentication credentials", None);
671 assert_eq!(f.code, FailureClass::Auth);
672 }
673
674 #[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 #[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 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 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 #[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 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 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 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 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 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 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 #[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 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 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 assert!(plain_cut_off(r#"{"type":"result","is_error":true,"result":"API Error: 529 overloaded"}"#).is_none());
991 assert!(plain_cut_off(r#"{"type":"result","is_error":true,"result":"Error [ede_diagnostic] result_type=assistant stop_reason=end_turn"}"#).is_none());
993 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 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
1002fn 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}