Skip to main content

agentmux_srv_core/agents/
limit_reset.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! When an agent's usage limit lifts: `AgentFailure::resets_at_ms` and
5//! `limit_window`, filled in when a `UsageLimit` failure is stored
6//! (`docs/specs/SPEC_UNRESPONSIVE_AGENTS_2026_10_23.md` §3.4).
7//!
8//! The sources, in order:
9//! 1. Claude's `rate_limit_event`, whose `status` is exactly `"rejected"`:
10//!    Claude Code sends one with every request, and a rejected one comes just
11//!    before the limit error, carrying the exhausted window's `resetsAt`
12//!    (unix seconds) and `rateLimitType`. The persistent stdout reader hands
13//!    every frame to [`observe_frame`], which keeps the latest per block.
14//!    `overageStatus` is often `"rejected"` while `status` is `"allowed"`; it
15//!    is never read.
16//! 2. The error text, `resets Oct 26, 7pm (America/Los_Angeles)` or
17//!    `resets 3:10am (UTC)` or `resets 7pm`, read in the zone it names (any
18//!    IANA name or `UTC`, from the `chrono-tz` data) or, with none, in this
19//!    machine's own; a zone that is not a name is left unknown. Codex
20//!    words it `... or try again at 9:44 PM.` (the machine's own zone, with the
21//!    date and year when it is not today: `Nov 3rd, 2025 9:44 PM`);
22//!    [`codex_failure_text`] picks that text out of Codex's `error` and
23//!    `turn.failed` frames.
24//!
25//! A reset outside `(now, now + 8 days]` is dropped: an unknown reset still
26//! leaves the agent limited, just with no time shown.
27
28use std::collections::HashMap;
29use std::sync::LazyLock;
30
31use chrono::{DateTime, Datelike, Local, NaiveDate, NaiveTime, TimeZone};
32use serde_json::Value;
33
34use super::failure::{AgentFailure, FailureClass, ROUTE_CREDITS_RETRY_MS};
35
36/// The longest a reset may lie ahead: a weekly limit plus a day.
37const MAX_AHEAD_MS: u64 = 8 * 24 * 60 * 60 * 1000;
38
39/// A `rate_limit_event`'s `rate_limit_info`, the fields this reads.
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct RateLimitInfo {
42    pub status: String,
43    pub resets_at_s: Option<u64>,
44    pub window: Option<String>,
45}
46
47impl RateLimitInfo {
48    /// The info a `rate_limit_event` frame carries, or `None` for any other frame.
49    pub fn of_frame(frame: &Value) -> Option<Self> {
50        if frame.get("type").and_then(Value::as_str) != Some("rate_limit_event") {
51            return None;
52        }
53        let info = frame.get("rate_limit_info")?;
54        Some(Self {
55            status: info.get("status").and_then(Value::as_str).unwrap_or_default().to_string(),
56            resets_at_s: info.get("resetsAt").and_then(Value::as_u64),
57            window: info.get("rateLimitType").and_then(Value::as_str).map(str::to_string),
58        })
59    }
60}
61
62static LATEST: LazyLock<parking_lot::Mutex<HashMap<String, RateLimitInfo>>> = LazyLock::new(Default::default);
63
64/// Keep `frame` as `block_id`'s latest rate-limit info if it is a
65/// `rate_limit_event`; any other frame is ignored.
66pub fn observe_frame(block_id: &str, frame: &Value) {
67    if let Some(info) = RateLimitInfo::of_frame(frame) {
68        LATEST.lock().insert(block_id.to_string(), info);
69    }
70}
71
72/// Forget `block_id`'s rate-limit info: its pane closed
73/// (`blockcontroller::release_block_processes`).
74pub fn forget(block_id: &str) {
75    LATEST.lock().remove(block_id);
76}
77
78/// `failure` with its reset filled in from what is known for `block_id`, at
79/// this machine's clock and time zone. Unchanged unless it is a `UsageLimit`
80/// with no reset yet.
81pub fn with_reset(block_id: &str, failure: &AgentFailure) -> AgentFailure {
82    if failure.code != FailureClass::UsageLimit || failure.resets_at_ms.is_some() {
83        return failure.clone();
84    }
85    let latest = LATEST.lock().get(block_id).cloned();
86    let zone = iana_time_zone::get_timezone().ok();
87    fill_reset(failure, latest.as_ref(), Local::now(), zone.as_deref())
88}
89
90/// [`with_reset`]'s rule, with its inputs passed in.
91pub fn fill_reset(
92    failure: &AgentFailure,
93    latest: Option<&RateLimitInfo>,
94    now: DateTime<Local>,
95    local_zone: Option<&str>,
96) -> AgentFailure {
97    let mut out = failure.clone();
98    if failure.code != FailureClass::UsageLimit || failure.resets_at_ms.is_some() {
99        return out;
100    }
101    let now_ms = u64::try_from(now.timestamp_millis()).unwrap_or(0);
102    // A route with no credits has no reset to read: hold for a while, then let a turn probe it.
103    if failure.is_route_credits() {
104        out.resets_at_ms = Some(now_ms.saturating_add(ROUTE_CREDITS_RETRY_MS));
105        return out;
106    }
107    let in_range = |ms: u64| ms > now_ms && ms <= now_ms.saturating_add(MAX_AHEAD_MS);
108    if let Some(info) = latest.filter(|i| i.status == "rejected") {
109        if let Some(ms) = info.resets_at_s.map(|s| s.saturating_mul(1000)).filter(|ms| in_range(*ms)) {
110            out.resets_at_ms = Some(ms);
111            out.limit_window = info.window.clone();
112            return out;
113        }
114    }
115    let text = format!("{}\n{}", failure.stderr_tail, failure.detail);
116    out.resets_at_ms = reset_from_text(&text, now, local_zone).filter(|ms| in_range(*ms));
117    out
118}
119
120/// The reset a limit message names (`resets Oct 26, 7pm (America/Los_Angeles)`,
121/// `resets 7:30pm`, `resets 3:10am (UTC)`), in unix ms, or `None`. A named zone
122/// is read as that zone's clock (`local_zone` is this machine's, read as local);
123/// with none named the time is local (the CLI writes it in the machine's zone).
124/// A time with no date is its next occurrence after `now`;
125/// a date with no year, likewise.
126pub fn reset_from_text(text: &str, now: DateTime<Local>, local_zone: Option<&str>) -> Option<u64> {
127    claude_reset(text, now, local_zone).or_else(|| codex_reset(text, now))
128}
129
130/// The message of a Codex `error` or `turn.failed` frame, or `None` for any
131/// other frame and for the `Reconnecting...` retry notices, which are not
132/// failures.
133pub fn codex_failure_text(frame: &Value) -> Option<String> {
134    let message = match frame.get("type").and_then(Value::as_str)? {
135        "turn.failed" => frame.pointer("/error/message").and_then(Value::as_str),
136        "error" => frame.get("message").and_then(Value::as_str),
137        _ => None,
138    }?;
139    (!message.contains("Reconnecting...")).then(|| message.to_string())
140}
141
142/// What `classify` should read from a frame the stdout reader kept as the run's
143/// in-band error: a Claude synthetic assistant message, or a Codex failure.
144pub fn inband_error_text(frame: &Value) -> String {
145    if let Some(text) = codex_failure_text(frame) {
146        return text;
147    }
148    let error = frame.get("error").and_then(Value::as_str).unwrap_or("");
149    let content = frame.pointer("/message/content/0/text").and_then(Value::as_str).unwrap_or("");
150    format!("{error} {content}")
151}
152
153/// Whether `frame` is the synthetic assistant message Claude Code writes when the login failed
154/// (`"error": "authentication_failed"`). The result frame that ends the turn carries only prose
155/// ("Failed to authenticate: OAuth session expired and could not be refreshed"), so this is what
156/// tells an expired login from any other failure whatever the wording.
157pub fn is_login_failure_frame(frame: &Value) -> bool {
158    frame.get("type").and_then(Value::as_str) == Some("assistant")
159        && frame.get("error").and_then(Value::as_str) == Some("authentication_failed")
160}
161
162/// What a synthetic assistant message says failed, for the result frame that ends its turn: Claude Code writes
163/// the cause there (`"error": "rate_limit"` with "You've hit your 5-hour limit · resets 8:10pm", `authentication_failed`)
164/// and its result frame carries only a generic error. A login failure keeps its fixed word; any other message with
165/// an `error` field gives that field and its text; an ordinary assistant message gives nothing.
166pub fn assistant_error_evidence(frame: &Value) -> String {
167    if frame.get("type").and_then(Value::as_str) != Some("assistant") {
168        return String::new();
169    }
170    if is_login_failure_frame(frame) {
171        return "authentication_failed".to_string();
172    }
173    match frame.get("error").and_then(Value::as_str) {
174        Some(error) if !error.is_empty() => inband_error_text(frame).trim().to_string(),
175        _ => String::new(),
176    }
177}
178
179/// Codex's `try again at 9:44 PM.` / `try again at Nov 3rd, 2025 9:44 PM.`.
180/// A time with no date is its next occurrence after `now`: Codex leaves the
181/// date out only for today.
182fn codex_reset(text: &str, now: DateTime<Local>) -> Option<u64> {
183    const MARK: &str = "try again at ";
184    let rest = &text[text.find(MARK)? + MARK.len()..];
185    let line = rest.lines().next().unwrap_or_default().split('"').next().unwrap_or_default();
186    let when = line.trim().trim_end_matches('.');
187    let words: Vec<&str> = when.split(|c: char| c == ',' || c.is_whitespace()).filter(|w| !w.is_empty()).collect();
188    let clock = |time: &str, meridiem: &str| parse_clock(&format!("{time}{meridiem}"));
189    let today = now.date_naive();
190    let at = match words.as_slice() {
191        [time, meridiem] => {
192            let t = Local.from_local_datetime(&today.and_time(clock(time, meridiem)?)).earliest()?;
193            if t > now { t } else { Local.from_local_datetime(&today.succ_opt()?.and_time(clock(time, meridiem)?)).earliest()? }
194        }
195        [month, day, year, time, meridiem] => {
196            let digits = day.trim_end_matches(|c: char| c.is_ascii_alphabetic());
197            let date = NaiveDate::from_ymd_opt(year.parse().ok()?, month_number(month)?, digits.parse().ok()?)?;
198            Local.from_local_datetime(&date.and_time(clock(time, meridiem)?)).earliest()?
199        }
200        _ => return None,
201    };
202    u64::try_from(at.timestamp_millis()).ok()
203}
204
205fn claude_reset(text: &str, now: DateTime<Local>, local_zone: Option<&str>) -> Option<u64> {
206    let start = text.find("resets ")? + "resets ".len();
207    let rest = &text[start..];
208    let line = rest.lines().next().unwrap_or_default();
209    let (when, zone) = match line.find('(') {
210        Some(open) => {
211            let close = line[open..].find(')').map(|c| open + c)?;
212            (line[..open].trim(), Some(line[open + 1..close].trim()))
213        }
214        None => (line.trim(), None),
215    };
216    // "Oct 26, 7pm", "Oct 26 at 7pm" or "7pm"
217    let words: Vec<&str> = when.split(|c: char| c == ',' || c.is_whitespace()).filter(|w| !w.is_empty() && *w != "at").collect();
218    let (date, time_word) = match words.as_slice() {
219        [time] => (None, *time),
220        [month, day, time] => (Some((month_number(month)?, day.parse::<u32>().ok()?)), *time),
221        _ => return None,
222    };
223    let time = parse_clock(time_word)?;
224    let at_ms = match zone.filter(|z| Some(*z) != local_zone) {
225        // A zone other than this machine's (a UTC reset read on a Pacific host): the clock is that zone's.
226        Some(named) => {
227            let tz: chrono_tz::Tz = named.parse().ok()?;
228            next_occurrence(&now.with_timezone(&tz), date, time)?.timestamp_millis()
229        }
230        None => next_occurrence(&now, date, time)?.timestamp_millis(),
231    };
232    u64::try_from(at_ms).ok()
233}
234
235/// The next time after `now` that the clock in `now`'s zone reads `time` (on `date`, month and day, when named).
236fn next_occurrence<Z: TimeZone>(now: &DateTime<Z>, date: Option<(u32, u32)>, time: NaiveTime) -> Option<DateTime<Z>> {
237    let zone = now.timezone();
238    let today = now.date_naive();
239    let candidate = |d: NaiveDate| zone.from_local_datetime(&d.and_time(time)).earliest();
240    match date {
241        None => {
242            let t = candidate(today)?;
243            if t > *now { Some(t) } else { candidate(today.succ_opt()?) }
244        }
245        Some((month, day)) => {
246            let this_year = candidate(NaiveDate::from_ymd_opt(today.year(), month, day)?)?;
247            if this_year > *now {
248                Some(this_year)
249            } else {
250                candidate(NaiveDate::from_ymd_opt(today.year() + 1, month, day)?)
251            }
252        }
253    }
254}
255
256fn month_number(word: &str) -> Option<u32> {
257    const MONTHS: [&str; 12] = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
258    let lower = word.to_ascii_lowercase();
259    let prefix = lower.get(..3)?;
260    MONTHS.iter().position(|m| *m == prefix).map(|i| i as u32 + 1)
261}
262
263/// `7pm`, `7:30pm`, `12am`, `19:00`.
264fn parse_clock(word: &str) -> Option<NaiveTime> {
265    let lower = word.to_ascii_lowercase();
266    let (digits, meridiem) = if let Some(d) = lower.strip_suffix("am") {
267        (d, Some(false))
268    } else if let Some(d) = lower.strip_suffix("pm") {
269        (d, Some(true))
270    } else {
271        (lower.as_str(), None)
272    };
273    let (hour, minute) = match digits.split_once(':') {
274        Some((h, m)) => (h.parse::<u32>().ok()?, m.parse::<u32>().ok()?),
275        None => (digits.parse::<u32>().ok()?, 0),
276    };
277    let hour = match meridiem {
278        Some(pm) if (1..=12).contains(&hour) => (hour % 12) + if pm { 12 } else { 0 },
279        Some(_) => return None,
280        None => hour,
281    };
282    NaiveTime::from_hms_opt(hour, minute, 0)
283}
284
285#[cfg(test)]
286mod tests {
287    use super::*;
288    use crate::agents::failure::classify;
289    use serde_json::json;
290
291    const ZONE: &str = "America/Los_Angeles";
292
293    fn at(y: i32, mo: u32, d: u32, h: u32, mi: u32) -> DateTime<Local> {
294        Local.from_local_datetime(&NaiveDate::from_ymd_opt(y, mo, d).unwrap().and_hms_opt(h, mi, 0).unwrap()).earliest().unwrap()
295    }
296
297    fn ms(t: DateTime<Local>) -> u64 {
298        u64::try_from(t.timestamp_millis()).unwrap()
299    }
300
301    fn weekly() -> AgentFailure {
302        classify(Some(1), None, "You've hit your weekly limit · resets Oct 26, 7pm (America/Los_Angeles)", None)
303    }
304
305    fn rejected(resets: DateTime<Local>, window: &str) -> RateLimitInfo {
306        RateLimitInfo { status: "rejected".into(), resets_at_s: Some(ms(resets) / 1000), window: Some(window.into()) }
307    }
308
309    #[test]
310    fn a_rate_limit_event_is_read_and_other_frames_are_not() {
311        let frame = json!({"type": "rate_limit_event", "rate_limit_info": {
312            "status": "rejected", "resetsAt": 1792886400, "rateLimitType": "seven_day",
313            "overageStatus": "rejected", "unifiedWindows": {"seven_day": {"utilization": 1, "resetsAt": 1792886400}}}});
314        assert_eq!(
315            RateLimitInfo::of_frame(&frame),
316            Some(RateLimitInfo { status: "rejected".into(), resets_at_s: Some(1792886400), window: Some("seven_day".into()) })
317        );
318        assert_eq!(RateLimitInfo::of_frame(&json!({"type": "result", "is_error": true})), None);
319    }
320
321    #[test]
322    fn the_latest_frame_per_block_is_kept() {
323        let b = format!("b-{}", uuid::Uuid::new_v4());
324        observe_frame(&b, &json!({"type": "rate_limit_event", "rate_limit_info": {"status": "allowed", "resetsAt": 1}}));
325        observe_frame(&b, &json!({"type": "assistant"}));
326        observe_frame(&b, &json!({"type": "rate_limit_event", "rate_limit_info": {"status": "rejected", "resetsAt": 2}}));
327        assert_eq!(LATEST.lock().get(&b).map(|i| (i.status.clone(), i.resets_at_s)), Some(("rejected".into(), Some(2))));
328        forget(&b);
329        assert!(LATEST.lock().get(&b).is_none());
330    }
331
332    const CODEX_LIMIT: &str = "You've hit your usage limit. Upgrade to Pro (https://chatgpt.com/explore/pro), visit https://chatgpt.com/codex/settings/usage to purchase more credits or try again at 9:44 PM.";
333
334    #[test]
335    fn codex_wording_gives_the_reset() {
336        let now = at(2026, 10, 25, 9, 0);
337        assert_eq!(reset_from_text(CODEX_LIMIT, now, Some(ZONE)), Some(ms(at(2026, 10, 25, 21, 44))), "today");
338        assert_eq!(reset_from_text(CODEX_LIMIT, at(2026, 10, 25, 22, 0), Some(ZONE)), Some(ms(at(2026, 10, 26, 21, 44))), "a time already past is tomorrow's");
339        assert_eq!(reset_from_text("or try again at 8:19 AM.", now, None), Some(ms(at(2026, 10, 26, 8, 19))));
340        assert_eq!(reset_from_text("or try again at Oct 29th, 2026 9:44 PM.", now, None), Some(ms(at(2026, 10, 29, 21, 44))), "a date and year");
341        assert_eq!(reset_from_text("or try again at Nov 3rd, 2026 12:05 AM.", now, None), Some(ms(at(2026, 11, 3, 0, 5))));
342        assert_eq!(reset_from_text("or try again later.", now, None), None, "no time named");
343        assert_eq!(reset_from_text("or try again at soon.", now, None), None);
344    }
345
346    #[test]
347    fn an_assistant_message_with_an_error_field_is_the_evidence_for_its_result_frame() {
348        let limit = serde_json::json!({
349            "type": "assistant", "error": "rate_limit",
350            "message": { "content": [{ "type": "text", "text": "You've hit your 5-hour limit · resets 8:10pm (America/Los_Angeles)" }] }
351        });
352        let said = assistant_error_evidence(&limit);
353        assert!(said.starts_with("rate_limit") && said.contains("5-hour limit"), "{said}");
354        let login = serde_json::json!({ "type": "assistant", "error": "authentication_failed" });
355        assert_eq!(assistant_error_evidence(&login), "authentication_failed");
356        // An ordinary reply, a reply with an empty error, and any other frame give nothing.
357        let plain = serde_json::json!({ "type": "assistant", "message": { "content": [{ "type": "text", "text": "done" }] } });
358        assert_eq!(assistant_error_evidence(&plain), "");
359        assert_eq!(assistant_error_evidence(&serde_json::json!({ "type": "assistant", "error": "" })), "");
360        assert_eq!(assistant_error_evidence(&serde_json::json!({ "type": "result", "error": "rate_limit" })), "");
361    }
362
363    #[test]
364    fn only_the_synthetic_assistant_message_marks_a_failed_login() {
365        let failed = json!({"type": "assistant", "error": "authentication_failed", "is_api_error_message": true,
366            "message": {"content": [{"type": "text", "text": "Failed to authenticate: OAuth session expired and could not be refreshed"}]}});
367        assert!(is_login_failure_frame(&failed));
368        let limited = json!({"type": "assistant", "error": "rate_limit", "message": {"content": [{"type": "text", "text": "You've hit your limit"}]}});
369        let result = json!({"type": "result", "is_error": true, "error": "authentication_failed"});
370        let said_so = json!({"type": "assistant", "message": {"content": [{"type": "text", "text": "authentication_failed"}]}});
371        for other in [limited, result, said_so] {
372            assert!(!is_login_failure_frame(&other), "{other}");
373        }
374    }
375
376    #[test]
377    fn codex_frames_carry_the_failure_text_and_retry_notices_do_not() {
378        let failed = json!({"type": "turn.failed", "error": {"message": CODEX_LIMIT}});
379        let error = json!({"type": "error", "message": CODEX_LIMIT});
380        assert_eq!(codex_failure_text(&failed).as_deref(), Some(CODEX_LIMIT));
381        assert_eq!(codex_failure_text(&error).as_deref(), Some(CODEX_LIMIT));
382        assert_eq!(codex_failure_text(&json!({"type": "error", "message": "Reconnecting... 2/5"})), None);
383        assert_eq!(codex_failure_text(&json!({"type": "turn.completed"})), None);
384        assert_eq!(inband_error_text(&failed), CODEX_LIMIT);
385        assert_eq!(inband_error_text(&json!({"error": "authentication_failed", "message": {"content": [{"text": "401"}]}})), "authentication_failed 401");
386    }
387
388    #[test]
389    fn a_codex_limit_failure_is_a_usage_limit_with_its_reset() {
390        let now = at(2026, 10, 25, 9, 0);
391        let f = classify(Some(1), None, CODEX_LIMIT, None);
392        assert_eq!(f.code, FailureClass::UsageLimit);
393        assert_eq!(fill_reset(&f, None, now, Some(ZONE)).resets_at_ms, Some(ms(at(2026, 10, 25, 21, 44))));
394    }
395
396    #[test]
397    fn a_codex_reset_outside_the_next_eight_days_is_dropped() {
398        let now = at(2026, 10, 25, 9, 0);
399        let far = classify(Some(1), None, "You've hit your usage limit. try again at Nov 20th, 2026 9:44 PM.", None);
400        assert_eq!(fill_reset(&far, None, now, Some(ZONE)).resets_at_ms, None, "more than 8 days ahead");
401        let past = classify(Some(1), None, "You've hit your usage limit. try again at Oct 20th, 2026 9:44 PM.", None);
402        assert_eq!(fill_reset(&past, None, now, Some(ZONE)).resets_at_ms, None, "already past");
403        let week = classify(Some(1), None, "You've hit your usage limit. try again at Nov 1st, 2026 9:44 PM.", None);
404        assert_eq!(fill_reset(&week, None, now, Some(ZONE)).resets_at_ms, Some(ms(at(2026, 11, 1, 21, 44))), "a week out is kept");
405    }
406
407    #[test]
408    fn a_rejected_event_gives_the_reset_and_the_window() {
409        let now = at(2026, 10, 23, 9, 0);
410        let reset = at(2026, 10, 26, 19, 0);
411        let f = fill_reset(&weekly(), Some(&rejected(reset, "seven_day")), now, Some(ZONE));
412        assert_eq!(f.resets_at_ms, Some(ms(reset)));
413        assert_eq!(f.limit_window.as_deref(), Some("seven_day"));
414    }
415
416    #[test]
417    fn an_allowed_event_is_not_a_reset_even_with_overage_rejected() {
418        let now = at(2026, 10, 23, 9, 0);
419        let allowed = RateLimitInfo { status: "allowed".into(), ..rejected(at(2026, 10, 23, 14, 0), "five_hour") };
420        let f = fill_reset(&weekly(), Some(&allowed), now, Some("Europe/Paris"));
421        assert_eq!(f.resets_at_ms, Some(ms_in(chrono_tz::America::Los_Angeles, (2026, 10, 26), (19, 0))), "no rejected event: the text's own zone");
422        assert_eq!(f.limit_window, None);
423    }
424
425    #[test]
426    fn the_text_is_the_fallback_read_in_the_zone_it_names() {
427        let now = at(2026, 10, 23, 9, 0);
428        assert_eq!(fill_reset(&weekly(), None, now, Some(ZONE)).resets_at_ms, Some(ms(at(2026, 10, 26, 19, 0))));
429        let pacific = Some(ms_in(chrono_tz::America::Los_Angeles, (2026, 10, 26), (19, 0)));
430        assert_eq!(fill_reset(&weekly(), None, now, Some("Europe/Paris")).resets_at_ms, pacific, "another machine zone");
431        assert_eq!(fill_reset(&weekly(), None, now, None).resets_at_ms, pacific, "local zone unknown");
432        let unknown = classify(Some(1), None, "You've hit your weekly limit · resets Oct 26, 7pm (Mars/Olympus)", None);
433        assert_eq!(fill_reset(&unknown, None, now, Some(ZONE)).resets_at_ms, None, "not a zone name");
434    }
435
436    /// The text of the outage that started #48173: a 429 that names the 5-hour window, reset in UTC.
437    const FIVE_HOUR: &str = "HTTP 429 You've hit your 5-hour limit · resets 3:10am (UTC)";
438
439    #[test]
440    fn a_429_naming_the_five_hour_window_is_a_usage_limit_with_its_utc_reset() {
441        let f = classify(Some(1), None, FIVE_HOUR, None);
442        assert_eq!(f.code, FailureClass::UsageLimit);
443        assert!(!f.retryable);
444        // 02:00 UTC on a day: the next 03:10 UTC is that morning, whatever zone the machine is in.
445        let now = chrono_tz::UTC.with_ymd_and_hms(2026, 11, 20, 2, 0, 0).unwrap().with_timezone(&Local);
446        for local in [Some(ZONE), Some("Europe/Paris"), None] {
447            let reset = fill_reset(&f, None, now, local).resets_at_ms;
448            assert_eq!(reset, Some(ms_in(chrono_tz::UTC, (2026, 11, 20), (3, 10))), "{local:?}");
449        }
450        // Past 03:10 UTC it is the next day's.
451        let later = chrono_tz::UTC.with_ymd_and_hms(2026, 11, 20, 4, 0, 0).unwrap().with_timezone(&Local);
452        assert_eq!(fill_reset(&f, None, later, None).resets_at_ms, Some(ms_in(chrono_tz::UTC, (2026, 11, 21), (3, 10))));
453    }
454
455    fn ms_in(tz: chrono_tz::Tz, (y, mo, d): (i32, u32, u32), (h, mi): (u32, u32)) -> u64 {
456        u64::try_from(tz.with_ymd_and_hms(y, mo, d, h, mi, 0).unwrap().timestamp_millis()).unwrap()
457    }
458
459    #[test]
460    fn text_without_a_date_or_year_is_the_next_occurrence() {
461        let now = at(2026, 10, 23, 16, 0);
462        assert_eq!(reset_from_text("resets 3pm", now, None), Some(ms(at(2026, 10, 24, 15, 0))), "3pm has passed today");
463        assert_eq!(reset_from_text("resets 7:30pm (America/Los_Angeles)", now, Some(ZONE)), Some(ms(at(2026, 10, 23, 19, 30))));
464        assert_eq!(reset_from_text("resets Jan 2, 9am", now, None), Some(ms(at(2027, 1, 2, 9, 0))), "next January");
465        assert_eq!(reset_from_text("resets Oct 23 at 12am", now, None), Some(ms(at(2027, 10, 23, 0, 0))));
466        assert_eq!(reset_from_text("no reset here", now, None), None);
467        assert_eq!(reset_from_text("resets soon", now, None), None);
468        assert_eq!(reset_from_text("resets 13pm", now, None), None);
469    }
470
471    #[test]
472    fn a_reset_out_of_range_is_dropped() {
473        let now = at(2026, 10, 23, 9, 0);
474        // No reset in the text either, so a dropped event leaves none.
475        let bare = classify(Some(1), None, "You've hit your weekly limit", None);
476        let past = fill_reset(&bare, Some(&rejected(at(2026, 10, 22, 9, 0), "seven_day")), now, None);
477        assert_eq!(past.resets_at_ms, None);
478        let far = fill_reset(&bare, Some(&rejected(at(2026, 11, 5, 9, 0), "seven_day")), now, None);
479        assert_eq!(far.resets_at_ms, None, "more than 8 days ahead");
480        // Exactly 8 days of milliseconds, whatever DST does that week.
481        let edge = Local.timestamp_millis_opt((ms(now) + MAX_AHEAD_MS) as i64).unwrap();
482        assert_eq!(fill_reset(&weekly(), Some(&rejected(edge, "seven_day")), now, None).resets_at_ms, Some(ms(edge)), "exactly 8 days");
483    }
484
485    #[test]
486    fn only_a_usage_limit_without_a_reset_is_filled() {
487        let now = at(2026, 10, 23, 9, 0);
488        let reset = rejected(at(2026, 10, 23, 14, 0), "five_hour");
489        let auth = classify(Some(1), None, "authentication_error: Invalid API key provided", None);
490        assert_eq!(fill_reset(&auth, Some(&reset), now, Some(ZONE)), auth);
491        let known = AgentFailure { resets_at_ms: Some(42), ..weekly() };
492        assert_eq!(fill_reset(&known, Some(&reset), now, Some(ZONE)).resets_at_ms, Some(42));
493    }
494
495    #[test]
496    fn a_route_out_of_credits_is_held_for_ten_minutes_whatever_else_is_known() {
497        let now = at(2026, 10, 23, 9, 0);
498        let f = classify(Some(1), None, "API Error: 402 This request would exceed your available credits", None);
499        assert!(f.is_route_credits());
500        let held = Some(ms(now) + ROUTE_CREDITS_RETRY_MS);
501        assert_eq!(fill_reset(&f, None, now, Some(ZONE)).resets_at_ms, held);
502        let stale = rejected(at(2026, 10, 25, 9, 0), "seven_day");
503        assert_eq!(fill_reset(&f, Some(&stale), now, Some(ZONE)).resets_at_ms, held, "a plan window from an earlier request is not its reset");
504    }
505
506    #[test]
507    fn the_server_rate_limit_is_not_a_usage_limit_and_gets_no_reset() {
508        let now = at(2026, 10, 23, 9, 0);
509        let f = classify(Some(1), None, "API Error: Server is temporarily limiting requests (not your usage limit) · Rate limited", None);
510        assert_eq!(f.code, FailureClass::RateLimited);
511        assert_eq!(fill_reset(&f, Some(&rejected(at(2026, 10, 23, 10, 0), "five_hour")), now, None).resets_at_ms, None);
512    }
513
514    #[test]
515    fn old_meta_without_the_new_fields_still_reads_and_none_is_not_written() {
516        // As an older build stored it (with its stderr tail; the state code
517        // reads only code, title and resetsAtMs, which works either way).
518        let old = json!({"code": "usage_limit", "title": "Usage limit reached", "detail": "", "exitCode": 1,
519                         "stderrTail": "You've hit your weekly limit", "retryable": false});
520        let f: AgentFailure = serde_json::from_value(old).unwrap();
521        assert_eq!((f.resets_at_ms, f.limit_window.clone()), (None, None));
522        let v = serde_json::to_value(&f).unwrap();
523        assert!(v.get("resetsAtMs").is_none() && v.get("limitWindow").is_none());
524        let with = AgentFailure { resets_at_ms: Some(5), limit_window: Some("seven_day".into()), ..f };
525        let v = serde_json::to_value(&with).unwrap();
526        assert_eq!((v["resetsAtMs"].clone(), v["limitWindow"].clone()), (json!(5), json!("seven_day")));
527    }
528}