crew-watch 0.2.1

Terminal monitor for firstmate fleets: htop-style system overview plus one row per running AI agent session, with subtree-aggregated CPU and memory, task and activity.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
//! Quota data layer: parsing `quota-axi --json`, an ISO-8601 → epoch helper for
//! `resetsAt`, and the background poller.
//!
//! ## Cadence and isolation contract
//!
//! `quota-axi --json` is a Node subprocess that takes ~0.8s wall even when it
//! answers from its own cache, and can stall unboundedly when a provider fetch
//! really goes to the network. It is therefore **never** invoked on the 2s
//! `/proc` tick path: [`spawn_poller`] runs it on a background thread at its
//! own cadence (default 5 min, see the floor note on [`fetch_once`] / the
//! `--quota-interval` clamp in `cli.rs`), and each call is bounded by a 10s
//! kill-timeout. Results cross over an `mpsc` channel; the main loop drains it
//! non-blockingly. Every failure leg reduces to a [`QuotaFetch::Failed`], so a
//! missing/wedged quota-axi can never stall or kill the core monitor.
//!
//! ## Schema tolerance
//!
//! `quota-axi` has shipped two JSON shapes: schema 3 (windows carry
//! `percentUsed`, providers carry `label`) and schema 5 (windows carry
//! `percentRemaining`, the provider `label` is gone, `state` survives). There
//! is **no hard version gate** (D10): parsing is best-effort against whatever
//! fields are present — unknown fields are ignored, optional ones default, and
//! each window's percent-used is taken from whichever field it carries
//! (`percentUsed` verbatim, else `100 − percentRemaining`). A genuinely
//! unparseable payload fails with a message carrying the recovered
//! `schemaVersion`, so an additive v6 still works and a broken one reports
//! clearly.

use std::process::{Command, Stdio};
use std::sync::mpsc::Sender;
use std::thread;
use std::time::Duration;

use serde::Deserialize;

// ---------------------------------------------------------------------------
// Public model (clean, typed; built from the private serde structs below)
// ---------------------------------------------------------------------------

/// One complete `quota-axi --json` report.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct QuotaReport {
    pub schema_version: Option<u64>,
    pub generated_at: String,
    pub providers: Vec<ProviderQuota>,
}

/// One provider's slice of the report.
#[derive(Debug, Clone, PartialEq)]
pub struct ProviderQuota {
    pub id: String,
    pub label: String,
    pub plan: Option<String>,
    pub windows: Vec<QuotaWindow>,
    pub status: ProviderStatus,
    /// `state.stale` — quota-axi's own per-provider freshness flag, independent
    /// of our fetch age.
    pub stale: bool,
    pub error: Option<String>,
}

/// A single usage window (e.g. `five_hour` / "session", `model:fable`).
#[derive(Debug, Clone, PartialEq)]
pub struct QuotaWindow {
    pub id: String,
    pub label: String,
    pub percent_used: f64,
    pub resets_at: Option<String>,
}

/// Per-provider `state.status`, parsed to the values quota-axi emits today; any
/// future value is preserved verbatim as [`ProviderStatus::Unknown`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProviderStatus {
    Fresh,
    Error,
    AuthRequired,
    Unknown(String),
}

// ---------------------------------------------------------------------------
// Private serde structs (camelCase, lenient; unknown fields ignored)
// ---------------------------------------------------------------------------

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct RawReport {
    #[serde(default)]
    schema_version: Option<u64>,
    #[serde(default)]
    generated_at: String,
    #[serde(default, rename = "providers")]
    providers: Vec<RawProvider>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct RawProvider {
    #[serde(default)]
    provider: String,
    #[serde(default)]
    label: String,
    #[serde(default)]
    plan: Option<String>,
    #[serde(default)]
    windows: Vec<RawWindow>,
    #[serde(default)]
    state: RawState,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct RawWindow {
    #[serde(default)]
    id: String,
    #[serde(default)]
    label: String,
    /// Schema ≤3 field; absent in schema 5.
    #[serde(default)]
    percent_used: Option<f64>,
    /// Schema 5 field; absent in schema 3. Presence is independent of
    /// `percent_used` — see [`window_percent_used`] for precedence.
    #[serde(default)]
    percent_remaining: Option<f64>,
    #[serde(default)]
    resets_at: Option<String>,
}

#[derive(Deserialize, Default)]
#[serde(rename_all = "camelCase")]
struct RawState {
    #[serde(default)]
    status: Option<String>,
    #[serde(default)]
    stale: bool,
    #[serde(default)]
    error: Option<String>,
}

fn parse_status(s: &str) -> ProviderStatus {
    match s {
        "fresh" => ProviderStatus::Fresh,
        "error" => ProviderStatus::Error,
        "auth_required" => ProviderStatus::AuthRequired,
        other => ProviderStatus::Unknown(other.to_string()),
    }
}

/// Percent-used for a window from whichever field its schema carries:
/// `percentUsed` verbatim (schema ≤3), else `100 − percentRemaining` (schema
/// 5), else 0. The explicit used value wins when both are present (schema 3
/// emitted both, in agreement).
fn window_percent_used(used: Option<f64>, remaining: Option<f64>) -> f64 {
    used.or_else(|| remaining.map(|r| 100.0 - r)).unwrap_or(0.0)
}

/// Parse a `quota-axi --json` document. Lenient on optional/unknown fields;
/// returns `Err` carrying the recovered schema version only when the input is
/// not valid JSON or not a JSON object.
pub fn parse_report(input: &str) -> Result<QuotaReport, String> {
    let raw: RawReport = serde_json::from_str(input).map_err(|e| {
        // Recover the schema version (if any) for a clearer failure message.
        let schema = serde_json::from_str::<serde_json::Value>(input)
            .ok()
            .and_then(|v| v.get("schemaVersion").and_then(|s| s.as_u64()));
        match schema {
            Some(v) => format!("unrecognized output (schema v{v}): {e}"),
            None => format!("unrecognized output (no schema): {e}"),
        }
    })?;
    Ok(QuotaReport {
        schema_version: raw.schema_version,
        generated_at: raw.generated_at,
        providers: raw
            .providers
            .into_iter()
            .map(|p| {
                let id = p.provider;
                ProviderQuota {
                    // Schema 5 dropped the provider `label`; fall back to the
                    // id so the struct never carries an empty name.
                    label: if p.label.is_empty() {
                        id.clone()
                    } else {
                        p.label
                    },
                    id,
                    plan: p.plan,
                    windows: p
                        .windows
                        .into_iter()
                        .map(|w| QuotaWindow {
                            id: w.id,
                            label: w.label,
                            percent_used: window_percent_used(w.percent_used, w.percent_remaining),
                            resets_at: w.resets_at,
                        })
                        .collect(),
                    status: p
                        .state
                        .status
                        .as_deref()
                        .map(parse_status)
                        .unwrap_or(ProviderStatus::Unknown("missing".to_string())),
                    stale: p.state.stale,
                    error: p.state.error,
                }
            })
            .collect(),
    })
}

/// True iff this provider carries at least one usage window to render bars for.
/// The single definition shared by the auto-selection seed (D7), the row, its
/// colouring, and `--once`, so they can never disagree.
///
/// Deliberately independent of [`ProviderStatus`]: quota-axi reports
/// `state.status = stale` whenever a live fetch failed and it served its cache,
/// which can happen at any moment. Freshness is a *display* signal (dim styling
/// / a `stale` suffix), never a visibility filter — hiding on it would blank the
/// row exactly when the last known reading matters most.
pub fn has_usage_windows(p: &ProviderQuota) -> bool {
    !p.windows.is_empty()
}

// ---------------------------------------------------------------------------
// ISO-8601 → UTC epoch seconds
// ---------------------------------------------------------------------------

/// Parse an ISO-8601 timestamp as seen in `quota-axi` output into UTC epoch
/// seconds. Handles `Z`, `±HH:MM` offsets, and optional fractional seconds;
/// returns `None` on anything else. Pure and deterministic so it can be
/// unit-tested without a system clock.
///
/// Implemented with Howard Hinnant's `days_from_civil` algorithm (no date
/// crate, matching the project's tested-pure-parser ethos).
pub fn parse_iso8601_utc_epoch(input: &str) -> Option<u64> {
    let b = input.as_bytes();
    // YYYY-MM-DDTHH:MM:SS  — 19 chars minimum for the local part.
    if b.len() < 19 {
        return None;
    }
    let two = |start: usize| -> Option<u64> {
        let s = std::str::from_utf8(b.get(start..start + 2)?).ok()?;
        s.parse::<u64>().ok()
    };
    if b[4] != b'-'
        || b[7] != b'-'
        || (b[10] != b'T' && b[10] != b' ')
        || b[13] != b':'
        || b[16] != b':'
    {
        return None;
    }
    // Year is 4 digits; read all four to support years > 2099 correctly.
    let year = std::str::from_utf8(b.get(0..4)?)
        .ok()?
        .parse::<i64>()
        .ok()?;
    let month = two(5)? as i64;
    let day = two(8)? as i64;
    let hour = two(11)?;
    let minute = two(14)?;
    let second = two(17)?;

    // Skip optional fractional seconds ".fff".
    let mut idx = 19;
    if idx < b.len() && b[idx] == b'.' {
        idx += 1;
        while idx < b.len() && b[idx].is_ascii_digit() {
            idx += 1;
        }
    }

    // Optional timezone: Z (UTC) or ±HH:MM offset. Absent ⇒ treat as UTC.
    let mut offset_secs: i64 = 0;
    if idx < b.len() {
        match b[idx] {
            b'Z' | b'z' => {}
            b'+' | b'-' => {
                let sign = if b[idx] == b'+' { 1 } else { -1 };
                if idx + 6 > b.len() || b[idx + 3] != b':' {
                    return None;
                }
                let oh = std::str::from_utf8(b.get(idx + 1..idx + 3)?)
                    .ok()?
                    .parse::<i64>()
                    .ok()?;
                let om = std::str::from_utf8(b.get(idx + 4..idx + 6)?)
                    .ok()?
                    .parse::<i64>()
                    .ok()?;
                offset_secs = sign * (oh * 3600 + om * 60);
            }
            _ => return None,
        }
    }

    let days = days_from_civil(year, month, day)?;
    let local_secs = days * 86_400 + (hour as i64) * 3600 + (minute as i64) * 60 + (second as i64);
    // Convert local → UTC by subtracting the offset, then clamp to non-negative.
    let utc = local_secs - offset_secs;
    if utc < 0 {
        None
    } else {
        Some(utc as u64)
    }
}

/// Howard Hinnant's `days_from_civil`: days since 1970-01-01 for a proleptic
/// Gregorian date. Returns `None` for an out-of-range month/day so callers can't
/// feed it garbage.
fn days_from_civil(year: i64, month: i64, day: i64) -> Option<i64> {
    if !(1..=12).contains(&month) || day < 1 {
        return None;
    }
    let y = if month <= 2 { year - 1 } else { year };
    let era = (if y >= 0 { y } else { y - 399 }) / 400;
    let yoe = y - era * 400; // [0, 399]
    let m_adj = if month > 2 { month - 3 } else { month + 9 };
    let doy = (153 * m_adj + 2) / 5 + day - 1; // [0, 365]
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096]
    Some(era * 146_097 + doe - 719_468)
}

// ---------------------------------------------------------------------------
// Fetch + poller
// ---------------------------------------------------------------------------

/// One result crossing the poller → main-loop channel.
#[derive(Debug, Clone)]
pub enum QuotaFetch {
    Report(QuotaReport),
    Failed(String),
}

/// Run `quota-axi --json` once, bounded by `timeout`. Never panics: every
/// failure (binary absent, timeout, non-zero exit, unparseable output) reduces
/// to [`QuotaFetch::Failed`].
///
/// **Pipe note:** stdout is read *after* the child exits. Today's payload is
/// ~8 KiB (well under the 64 KiB pipe buffer). If quota-axi ever emits more
/// than the buffer, the child blocks on the full pipe until the timeout SIGKILLs
/// it, after which the partial read fails to parse → `Failed`. Bounded badness;
/// accepted over the complexity of a concurrent stdout reader.
pub fn fetch_once(timeout: Duration) -> QuotaFetch {
    let mut cmd = match Command::new("quota-axi")
        .arg("--json")
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
    {
        Ok(c) => c,
        Err(e) => {
            let msg = if e.kind() == std::io::ErrorKind::NotFound {
                "quota-axi not found".to_string()
            } else {
                format!("quota-axi spawn failed: {e}")
            };
            return QuotaFetch::Failed(msg);
        }
    };

    // Poll for exit up to `timeout`, then SIGKILL + reap. try_wait never blocks.
    let deadline = std::time::Instant::now() + timeout;
    let exit_status = loop {
        match cmd.try_wait() {
            Ok(Some(status)) => break Ok(status),
            Ok(None) => {
                if std::time::Instant::now() >= deadline {
                    let _ = cmd.kill();
                    let _ = cmd.wait();
                    break Err("timed out".to_string());
                }
                std::thread::sleep(Duration::from_millis(50));
            }
            Err(e) => {
                let _ = cmd.kill();
                let _ = cmd.wait();
                break Err(format!("quota-axi wait failed: {e}"));
            }
        }
    };

    let status = match exit_status {
        Ok(s) => s,
        Err(msg) => return QuotaFetch::Failed(msg),
    };
    if !status.success() {
        let stderr = cmd
            .stderr
            .take()
            .and_then(|s| std::io::read_to_string(s).ok())
            .unwrap_or_default();
        let first_line = stderr.lines().next().unwrap_or("").trim();
        let msg = if first_line.is_empty() {
            format!("quota-axi exited {status}")
        } else {
            // Truncate to keep the failure line readable.
            let truncated: String = first_line.chars().take(60).collect();
            truncated
        };
        return QuotaFetch::Failed(msg);
    }

    let stdout = cmd
        .stdout
        .take()
        .and_then(|s| std::io::read_to_string(s).ok())
        .unwrap_or_default();
    match parse_report(&stdout) {
        Ok(r) => QuotaFetch::Report(r),
        Err(e) => QuotaFetch::Failed(e),
    }
}

/// Spawn the background poller thread. Loops `fetch → send → sleep(interval)`;
/// exits cleanly when the receiver is dropped (send fails). Detached — process
/// exit reaps it. The fetch timeout is fixed at 10s regardless of cadence.
pub fn spawn_poller(interval: Duration, tx: Sender<QuotaFetch>) -> thread::JoinHandle<()> {
    thread::spawn(move || loop {
        let fetch = fetch_once(Duration::from_secs(10));
        if tx.send(fetch).is_err() {
            return; // receiver gone (app shutting down)
        }
        thread::sleep(interval);
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    // Trimmed but structurally complete capture of `quota-axi --json` (schema 3,
    // the pre-0.1.30 shape) covering the live shape (claude, 3 windows) and
    // every failure shape seen on the captain's machine at the time. Retained
    // deliberately: schema 3 homes must keep parsing across quota-axi
    // upgrades. Mirrors the meta.rs SAMPLE idiom.
    const SAMPLE: &str = r#"{
  "generatedAt": "2026-08-13T13:54:46.385Z",
  "schemaVersion": 3,
  "providers": [
    {
      "provider": "claude", "label": "Claude", "source": "oauth", "plan": "max",
      "windows": [
        { "id": "five_hour",   "label": "session",    "kind": "session",
          "percentUsed": 5,  "percentRemaining": 95,
          "resetsAt": "2026-08-13T15:40:00.000000+00:00", "windowSeconds": 18000,
          "pace": { "status": "behind" } },
        { "id": "seven_day",   "label": "week",       "kind": "weekly",
          "percentUsed": 48, "resetsAt": "2026-08-17T12:00:00.000000+00:00" },
        { "id": "model:fable", "label": "Fable week", "kind": "model",
          "percentUsed": 45, "resetsAt": "2026-08-17T12:00:00.000000+00:00" }
      ],
      "state": { "status": "fresh", "stale": false, "refreshedAt": "2026-08-13T13:54:46.846Z",
                 "sourcesTried": ["oauth-file", "oauth-profile"] },
      "quotaSemantics": { "status": "known" }
    },
    { "provider": "codex",   "label": "Codex",   "source": "unavailable", "windows": [],
      "state": { "status": "error", "stale": false, "error": "Codex quota unavailable" } },
    { "provider": "cursor",  "label": "Cursor",  "source": "unavailable", "windows": [],
      "state": { "status": "error", "stale": false, "error": "sqlite3_unavailable" } },
    { "provider": "copilot", "label": "GitHub Copilot", "source": "unavailable", "windows": [],
      "state": { "status": "auth_required", "stale": false, "error": "GitHub Copilot sign-in required" } },
    { "provider": "grok",    "label": "Grok",    "source": "unavailable", "windows": [],
      "state": { "status": "auth_required", "stale": false, "error": "Grok sign-in required" } },
        { "provider": "kimi",    "label": "Kimi",    "source": "unavailable", "windows": [],
      "state": { "status": "auth_required", "stale": false, "error": "kimi_credential_unavailable" } }
    ]
}"#;

    // Verbatim live capture of `quota-axi --json` from quota-axi 0.1.30
    // (schema 5) on the captain's machine: windows carry `percentRemaining`
    // (no `percentUsed`), providers carry no `label`, `state` survives, and a
    // `quotaSemantics` block with `effectiveAvailability`/`pace` sub-objects
    // rides along (all ignored by the parser). Contains only percentages and
    // timestamps — nothing to redact.
    const SAMPLE_V5: &str = r#"{
  "generatedAt": "2026-08-22T20:44:31.900Z",
  "schemaVersion": 5,
  "providers": [
    {
      "provider": "claude",
      "plan": "max",
      "windows": [
        {
          "id": "five_hour",
          "label": "session",
          "kind": "session",
          "resetsAt": "2026-08-22T23:30:00.306600+00:00",
          "percentRemaining": 98,
          "pace": {
            "status": "behind",
            "reservePercentPoints": 42.8422,
            "burnMultiple": 0.0446
          }
        },
        {
          "id": "seven_day",
          "label": "week",
          "kind": "weekly",
          "resetsAt": "2026-08-24T12:00:00.306623+00:00",
          "percentRemaining": 29,
          "pace": {
            "status": "behind",
            "reservePercentPoints": 5.6322,
            "burnMultiple": 0.9265
          }
        },
        {
          "id": "model:fable",
          "label": "Fable week",
          "kind": "model",
          "resetsAt": "2026-08-24T12:00:00.306855+00:00",
          "percentRemaining": 37,
          "pace": {
            "status": "behind",
            "reservePercentPoints": 13.6322,
            "burnMultiple": 0.8221
          }
        }
      ],
      "state": {
        "status": "fresh",
        "stale": false
      },
      "quotaSemantics": {
        "status": "known",
        "effectiveAvailability": [
          {
            "scope": "all_models",
            "status": "known",
            "effectivePercentRemaining": 29,
            "boundedBy": [
              "five_hour",
              "seven_day"
            ],
            "limitingWindowIds": [
              "seven_day"
            ],
            "pace": {
              "status": "behind",
              "worstReservePercentPoints": 5.6322,
              "worstReserveWindowId": "seven_day"
            },
            "runway": {
              "status": "through_reset",
              "projectionConfidence": "established"
            },
            "selection": {
              "status": "known",
              "spendPriority": 0.3555
            }
          },
          {
            "scope": "model:fable",
            "status": "known",
            "effectivePercentRemaining": 29,
            "boundedBy": [
              "five_hour",
              "seven_day",
              "model:fable"
            ],
            "limitingWindowIds": [
              "seven_day"
            ],
            "pace": {
              "status": "behind",
              "worstReservePercentPoints": 5.6322,
              "worstReserveWindowId": "seven_day"
            },
            "runway": {
              "status": "through_reset",
              "projectionConfidence": "established"
            },
            "selection": {
              "status": "known",
              "spendPriority": 0.5554
            }
          }
        ]
      }
    },
    {
      "provider": "codex",
      "windows": [],
      "state": {
        "status": "error",
        "stale": false,
        "error": "Codex quota unavailable"
      },
      "quotaSemantics": {
        "status": "unknown",
        "effectiveAvailability": []
      }
    },
    {
      "provider": "cursor",
      "windows": [],
      "state": {
        "status": "error",
        "stale": false,
        "error": "sqlite3_unavailable"
      },
      "quotaSemantics": {
        "status": "unknown",
        "effectiveAvailability": []
      }
    },
    {
      "provider": "copilot",
      "windows": [],
      "state": {
        "status": "auth_required",
        "stale": false,
        "error": "GitHub Copilot sign-in required"
      },
      "quotaSemantics": {
        "status": "unknown",
        "effectiveAvailability": [],
        "unresolvedWindowIds": []
      }
    },
    {
      "provider": "grok",
      "windows": [],
      "state": {
        "status": "auth_required",
        "stale": false,
        "error": "Grok sign-in required",
        "authStatus": "unusable"
      },
      "quotaSemantics": {
        "status": "unknown",
        "effectiveAvailability": []
      }
    },
    {
      "provider": "kimi",
      "windows": [],
      "state": {
        "status": "auth_required",
        "stale": false,
        "error": "kimi_credential_unavailable"
      },
      "quotaSemantics": {
        "status": "unknown",
        "effectiveAvailability": []
      }
    },
    {
      "provider": "zai",
      "plan": "max",
      "windows": [
        {
          "id": "mcp_month",
          "label": "MCP month",
          "kind": "monthly",
          "percentRemaining": 100,
          "resetsAt": "2026-08-25T02:00:20.998Z",
          "pace": {
            "status": "unknown",
            "reason": "missing_cycle"
          }
        },
        {
          "id": "five_hour",
          "label": "session",
          "kind": "session",
          "percentRemaining": 70,
          "resetsAt": "2026-08-22T22:07:26.949Z",
          "pace": {
            "status": "behind",
            "reservePercentPoints": 42.3608,
            "burnMultiple": 0.4146
          }
        },
        {
          "id": "weekly",
          "label": "week",
          "kind": "weekly",
          "percentRemaining": 92,
          "resetsAt": "2026-08-29T02:00:20.976Z",
          "pace": {
            "status": "behind",
            "reservePercentPoints": 3.1526,
            "burnMultiple": 0.7173
          }
        }
      ],
      "state": {
        "status": "fresh",
        "stale": false
      },
      "quotaSemantics": {
        "status": "known",
        "effectiveAvailability": [
          {
            "scope": "all_models",
            "status": "known",
            "effectivePercentRemaining": 70,
            "boundedBy": [
              "five_hour",
              "weekly"
            ],
            "limitingWindowIds": [
              "five_hour"
            ],
            "pace": {
              "status": "behind",
              "worstReservePercentPoints": 3.1526,
              "worstReserveWindowId": "weekly"
            },
            "runway": {
              "status": "through_reset",
              "projectionConfidence": "established"
            },
            "selection": {
              "status": "known",
              "spendPriority": 0.3702
            }
          },
          {
            "scope": "tools",
            "status": "known",
            "effectivePercentRemaining": 100,
            "boundedBy": [
              "mcp_month"
            ],
            "limitingWindowIds": [
              "mcp_month"
            ],
            "pace": {
              "status": "unknown",
              "unknownWindowIds": [
                "mcp_month"
              ]
            },
            "runway": {
              "status": "unknown",
              "unmeasurableWindowIds": [
                "mcp_month"
              ]
            },
            "selection": {
              "status": "unknown",
              "unmeasurableWindowIds": [
                "mcp_month"
              ]
            }
          }
        ]
      }
    },
    {
      "provider": "agy",
      "windows": [],
      "state": {
        "status": "error",
        "stale": false,
        "error": "Antigravity process discovery failed"
      },
      "quotaSemantics": {
        "status": "unknown",
        "effectiveAvailability": [],
        "unresolvedWindowIds": []
      }
    }
  ]
}"#;

    #[test]
    fn parse_full_fixture() {
        let r = parse_report(SAMPLE).expect("fixture must parse");
        assert_eq!(r.schema_version, Some(3));
        assert_eq!(r.providers.len(), 6);

        let claude = &r.providers[0];
        assert_eq!(claude.id, "claude");
        assert_eq!(claude.label, "Claude");
        assert_eq!(claude.plan.as_deref(), Some("max"));
        assert_eq!(claude.status, ProviderStatus::Fresh);
        assert!(!claude.stale);
        assert!(has_usage_windows(claude));
        assert_eq!(claude.windows.len(), 3);
        assert_eq!(claude.windows[0].id, "five_hour");
        assert_eq!(claude.windows[0].label, "session");
        assert!((claude.windows[0].percent_used - 5.0).abs() < 1e-9);
        assert_eq!(
            claude.windows[0].resets_at.as_deref(),
            Some("2026-08-13T15:40:00.000000+00:00")
        );
        // model: window id preserved verbatim (label rule is the row's job).
        assert_eq!(claude.windows[2].id, "model:fable");
    }

    #[test]
    fn parse_failure_shapes() {
        let r = parse_report(SAMPLE).unwrap();
        let by = |id: &str| r.providers.iter().find(|p| p.id == id).unwrap();
        assert_eq!(by("codex").status, ProviderStatus::Error);
        assert_eq!(
            by("codex").error.as_deref(),
            Some("Codex quota unavailable")
        );
        assert!(!has_usage_windows(by("codex")));
        assert_eq!(by("copilot").status, ProviderStatus::AuthRequired);
        assert!(!has_usage_windows(by("copilot")));
        // claude is the only provider carrying windows in the fixture
        let with_windows: Vec<&str> = r
            .providers
            .iter()
            .filter(|p| has_usage_windows(p))
            .map(|p| p.id.as_str())
            .collect();
        assert_eq!(with_windows, vec!["claude"]);
    }

    // --- schema 5 (quota-axi 0.1.30 live shape) ---

    #[test]
    fn parse_v5_live_fixture() {
        let r = parse_report(SAMPLE_V5).expect("v5 fixture must parse");
        assert_eq!(r.schema_version, Some(5));
        assert_eq!(r.providers.len(), 8);
        assert_eq!(r.generated_at, "2026-08-22T20:44:31.900Z");

        let claude = &r.providers[0];
        assert_eq!(claude.id, "claude");
        // Schema 5 dropped provider labels; the parser falls back to the id.
        assert_eq!(claude.label, "claude");
        assert_eq!(claude.plan.as_deref(), Some("max"));
        assert_eq!(claude.status, ProviderStatus::Fresh);
        assert!(!claude.stale);
        assert!(has_usage_windows(claude));
        assert_eq!(claude.windows.len(), 3);
        // percentRemaining → percent used (100 − remaining).
        assert_eq!(claude.windows[0].id, "five_hour");
        assert_eq!(claude.windows[0].label, "session");
        assert!((claude.windows[0].percent_used - 2.0).abs() < 1e-9); // 98 remaining
        assert!((claude.windows[1].percent_used - 71.0).abs() < 1e-9); // 29 remaining
        assert!((claude.windows[2].percent_used - 63.0).abs() < 1e-9); // 37 remaining
        assert_eq!(
            claude.windows[0].resets_at.as_deref(),
            Some("2026-08-22T23:30:00.306600+00:00")
        );
        assert_eq!(claude.windows[2].id, "model:fable");

        let zai = r.providers.iter().find(|p| p.id == "zai").unwrap();
        assert_eq!(zai.windows.len(), 3);
        assert!((zai.windows[0].percent_used - 0.0).abs() < 1e-9); // mcp_month: 100 remaining
        assert!((zai.windows[1].percent_used - 30.0).abs() < 1e-9); // session: 70 remaining
        assert!((zai.windows[2].percent_used - 8.0).abs() < 1e-9); // week: 92 remaining
    }

    #[test]
    fn parse_v5_failure_shapes_preserved() {
        let r = parse_report(SAMPLE_V5).unwrap();
        let by = |id: &str| r.providers.iter().find(|p| p.id == id).unwrap();
        assert_eq!(by("codex").status, ProviderStatus::Error);
        assert_eq!(
            by("codex").error.as_deref(),
            Some("Codex quota unavailable")
        );
        assert_eq!(by("grok").status, ProviderStatus::AuthRequired);
        assert_eq!(by("agy").status, ProviderStatus::Error);
        assert!(!has_usage_windows(by("codex")));
        // claude and zai are the live providers in the v5 capture.
        let live: Vec<&str> = r
            .providers
            .iter()
            .filter(|p| has_usage_windows(p))
            .map(|p| p.id.as_str())
            .collect();
        assert_eq!(live, vec!["claude", "zai"]);
    }

    #[test]
    fn percent_used_wins_when_both_fields_present() {
        // Schema 3 emitted both fields (in agreement); if they ever disagree,
        // the explicit used value is authoritative.
        let r = parse_report(
            r#"{ "providers": [ { "provider": "x",
              "windows": [ { "id": "five_hour", "percentUsed": 10, "percentRemaining": 50 } ] } ] }"#,
        )
        .unwrap();
        assert!((r.providers[0].windows[0].percent_used - 10.0).abs() < 1e-9);
    }

    #[test]
    fn v5_fractional_remaining_maps_fractionally() {
        let r = parse_report(
            r#"{ "schemaVersion": 5, "providers": [ { "provider": "x",
              "windows": [ { "id": "five_hour", "percentRemaining": 42.5 } ] } ] }"#,
        )
        .unwrap();
        assert!((r.providers[0].windows[0].percent_used - 57.5).abs() < 1e-9);
    }

    #[test]
    fn window_with_neither_percent_field_defaults_zero() {
        let r = parse_report(
            r#"{ "schemaVersion": 5, "providers": [ { "provider": "x",
              "windows": [ { "id": "five_hour", "label": "session",
                             "resetsAt": "2026-08-22T23:30:00Z" } ] } ] }"#,
        )
        .unwrap();
        assert!(r.providers[0].windows[0].percent_used.abs() < 1e-9);
        assert!(has_usage_windows(&r.providers[0]));
    }

    #[test]
    fn windows_visible_regardless_of_status() {
        // A provider serving cached windows (state.status = stale) or reporting a
        // status crew-watch has never seen must still count as renderable: status
        // is a display signal, not a visibility filter.
        let r = parse_report(
            r#"{ "providers": [
              { "provider": "claude", "windows": [ { "id": "five_hour", "percentUsed": 40 } ],
                "state": { "status": "stale", "stale": true } },
              { "provider": "zai", "windows": [ { "id": "five_hour", "percentUsed": 12 } ] }
            ] }"#,
        )
        .unwrap();
        assert_eq!(
            r.providers[0].status,
            ProviderStatus::Unknown("stale".to_string())
        );
        assert!(r.providers[0].stale);
        assert!(has_usage_windows(&r.providers[0]));
        // No `state` block at all ⇒ Unknown("missing"), still renderable.
        assert_eq!(
            r.providers[1].status,
            ProviderStatus::Unknown("missing".to_string())
        );
        assert!(has_usage_windows(&r.providers[1]));
    }

    #[test]
    fn parse_unknown_fields_ignored_and_optionals_default() {
        // Unknown top-level field, provider missing plan/state, window missing resetsAt.
        let mini = r#"{
          "schemaVersion": 3, "futureKey": 99,
          "providers": [
            { "provider": "zai", "label": "Z.AI",
              "windows": [ { "id": "five_hour", "label": "session", "percentUsed": 12 } ] }
          ]
        }"#;
        let r = parse_report(mini).unwrap();
        assert_eq!(r.providers.len(), 1);
        let p = &r.providers[0];
        assert_eq!(p.id, "zai");
        assert!(p.plan.is_none());
        assert_eq!(p.status, ProviderStatus::Unknown("missing".to_string()));
        assert!(p.windows[0].resets_at.is_none());
        assert!((p.windows[0].percent_used - 12.0).abs() < 1e-9);
    }

    #[test]
    fn parse_empty_providers_ok() {
        let r = parse_report(r#"{ "schemaVersion": 3, "providers": [] }"#).unwrap();
        assert!(r.providers.is_empty());
    }

    #[test]
    fn parse_garbage_returns_err_with_schema() {
        let err =
            parse_report(r#"{ "schemaVersion": 7, "providers": "not an array" }"#).unwrap_err();
        assert!(err.contains("schema v7"), "got: {err}");
    }

    #[test]
    fn parse_garbage_no_schema() {
        let err = parse_report("not json at all").unwrap_err();
        assert!(err.contains("no schema"), "got: {err}");
    }

    #[test]
    fn parse_unknown_status_preserved() {
        let r = parse_report(
            r#"{ "providers": [ { "provider": "x", "state": { "status": "weird_new_one" } } ] }"#,
        )
        .unwrap();
        assert_eq!(
            r.providers[0].status,
            ProviderStatus::Unknown("weird_new_one".to_string())
        );
    }

    // --- parse_iso8601_utc_epoch ---

    #[test]
    fn iso_zulu() {
        // 2026-08-13T13:55:00Z == 1786629300 (verified via the civil formula).
        assert_eq!(
            parse_iso8601_utc_epoch("2026-08-13T13:55:00Z"),
            Some(1_786_629_300)
        );
    }

    #[test]
    fn iso_zero_offset_same_as_zulu() {
        assert_eq!(
            parse_iso8601_utc_epoch("2026-08-13T13:55:00.000000+00:00"),
            Some(1_786_629_300)
        );
    }

    #[test]
    fn iso_positive_offset() {
        // 15:00 local at +02:00 == 13:00 UTC.
        assert_eq!(
            parse_iso8601_utc_epoch("2026-08-13T15:00:00+02:00"),
            parse_iso8601_utc_epoch("2026-08-13T13:00:00Z")
        );
    }

    #[test]
    fn iso_negative_offset() {
        // 10:30 local at -05:30 == 16:00 UTC.
        assert_eq!(
            parse_iso8601_utc_epoch("2026-08-13T10:30:00-05:30"),
            parse_iso8601_utc_epoch("2026-08-13T16:00:00Z")
        );
    }

    #[test]
    fn iso_fractional_seconds_ignored() {
        assert_eq!(
            parse_iso8601_utc_epoch("2026-08-17T12:00:00.547442+00:00"),
            parse_iso8601_utc_epoch("2026-08-17T12:00:00Z")
        );
    }

    #[test]
    fn iso_garbage_returns_none() {
        assert_eq!(parse_iso8601_utc_epoch("garbage"), None);
        assert_eq!(parse_iso8601_utc_epoch("2026-08-13"), None);
        assert_eq!(parse_iso8601_utc_epoch(""), None);
    }
}