claude-smart 0.2.2

Cross-platform Claude Code smart session manager
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
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
//! Usage fetch transport — hub-local fast path, positive/negative TTL cache,
//! HTTP-first (reqwest blocking), SSH fallback (POSIX only).
//!
//! # Fetch algorithm (spec §2 "Usage transport + caching")
//!
//! Reproduces `fetch_usage()` in `claude-smart-helper.sh.j2` lines 655–728.
//!
//! 1. **Hub-local fast path** (`hostname == $CLAUDE_HUB_HOSTNAME` → read
//!    `paths::hub_local_cache()` directly, skip all network). Disabled when the
//!    env var is unset/empty.
//!    Shell lines 657–662: `if printf '%s' "$host" | grep -qi "^$USAGE_HUB$"; then cat "$USAGE_CACHE"; return 0`
//!
//! 2. **Positive TTL check**: if `paths::usage_cache()` exists and mtime age <
//!    `POSITIVE_TTL_SECS` (60 s, env `CLAUDE_USAGE_TTL` / alias `CSM_USAGE_TTL_SECS`)
//!    → parse + return.
//!    Shell lines 666–675: `if [ -s "$pos_cache" ]; then … if [ $(( cnow - cmt )) -lt "$USAGE_TTL" ]; then cat …`
//!
//! 2.5. **User command** (`CSM_USAGE_CMD`, if set): run it via the shell, parse
//!    stdout as `UsageData`. This is the operator-injected "check via a provided
//!    script" source; it runs *before* the negative cooldown (an explicit
//!    command is independent of a hub outage) and takes precedence over HTTP/SSH.
//!    On success the result is cached; on failure it falls through to the hub.
//!    Not in the shell original — csm-native (env-injected, never compiled in).
//!
//! 3. **Negative cooldown check**: if `paths::fetch_failed()` exists and age <
//!    `NEGATIVE_COOLDOWN_SECS` (120 s, env `CLAUDE_USAGE_FAIL_COOLDOWN`) →
//!    return `Err(FetchError::NegativeCacheActive)`.
//!    Shell lines 677–687: `if [ -f "$fail_marker" ]; then … if [ $(( now - last )) -lt "$FETCH_FAIL_COOLDOWN" ]; then return 0`
//!
//! 4. **HTTP fetch** (reqwest blocking; connect-timeout 1 s / max-time 2 s).
//!    Shell lines 694–698: `if [ -n "$USAGE_URL" ] && [ -x "$CURL" ]; then out="$(curl -fs --connect-timeout 1 --max-time …)"`
//!    `CLAUDE_USAGE_URL` env: empty string = disable HTTP path; unset = use default URL.
//!    `CLAUDE_USAGE_HTTP_TIMEOUT` env: max-time in seconds (default 2).
//!
//! 5. **SSH fallback** (`#[cfg(unix)]` only; ControlMaster reuse via `ssh`
//!    shell-out; see `ssh_fetch`). Shell lines 699–708.
//!    On Windows, HTTP is the only path (spec §5 #5).
//!
//! 6. On success: validate JSON (`serde_json::from_str`), write cache atomically
//!    (tmp + rename). Clear negative cache. Shell lines 713–720.
//!
//! 7. On failure (both HTTP + SSH fail): stamp `.usage-fetch-failed` epoch.
//!    Shell lines 723–726.

use super::model::UsageData;
use super::FetchError;
use crate::paths;

// ─── constants (overrideable via env) ─────────────────────────────────────────

/// Default positive TTL in seconds. Overridden by `CLAUDE_USAGE_TTL`.
/// Shell: `USAGE_TTL="${CLAUDE_USAGE_TTL:-60}"`.
const DEFAULT_POSITIVE_TTL_SECS: u64 = 60;

/// Default negative cooldown in seconds. Overridden by `CLAUDE_USAGE_FAIL_COOLDOWN`.
/// Shell: `FETCH_FAIL_COOLDOWN="${CLAUDE_USAGE_FAIL_COOLDOWN:-120}"`.
const DEFAULT_NEGATIVE_COOLDOWN_SECS: u64 = 120;

/// Default HTTP total timeout in seconds. Overridden by `CLAUDE_USAGE_HTTP_TIMEOUT`.
/// Shell: `HTTP_DEADLINE="${CLAUDE_USAGE_HTTP_TIMEOUT:-2}"`.
const DEFAULT_HTTP_TIMEOUT_SECS: u64 = 2;

/// Default SSH deadline in seconds. Overridden by `CLAUDE_USAGE_SSH_TIMEOUT`.
/// Shell: `SSH_DEADLINE="${CLAUDE_USAGE_SSH_TIMEOUT:-3}"`.
#[cfg(unix)]
const DEFAULT_SSH_DEADLINE_SECS: u64 = 3;

/// Default hub usage URL. Empty = HTTP disabled unless `CLAUDE_USAGE_URL` is set.
///
/// The hub endpoint is site-specific infrastructure, so the binary ships **no**
/// compiled-in URL. Deployments that run a usage hub inject the real endpoint via
/// the `CLAUDE_USAGE_URL` env var (e.g. an Ansible-templated `settings.json`).
/// Shell: `USAGE_URL="${CLAUDE_USAGE_URL-}"`.
/// Note the `-` (not `:-`): set-but-empty disables HTTP entirely; unset falls
/// back to this empty default, which `resolve_usage_url()` also treats as "off".
const DEFAULT_HUB_USAGE_URL: &str = "";

// ─── public entry-point ───────────────────────────────────────────────────────

/// Fetch usage data from the hub, obeying the positive/negative TTL caches.
///
/// Returns `Ok(UsageData)` on success or `Err(FetchError)` on any failure
/// (network down, cache-miss, parse error, etc.).
///
/// The caller should treat *any* `Err` as "hub unavailable" and open the
/// hub-down account picker (interactive contexts) or fall back silently
/// (non-interactive contexts).
pub fn fetch() -> Result<UsageData, FetchError> {
    // Step 1 — hub-local fast path.
    // Shell lines 657–662.
    if is_hub_local() {
        return read_hub_local();
    }

    let positive_ttl = positive_ttl_secs();
    let negative_cooldown = negative_cooldown_secs();

    // Step 2 — positive TTL cache (< POSITIVE_TTL_SECS).
    // Shell lines 666–675.
    if let Some(data) = try_positive_cache(positive_ttl)? {
        return Ok(data);
    }

    // Step 2.5 — user-supplied usage command (`CSM_USAGE_CMD`), if set.
    //
    // When the operator wires a metering command (a site script, a PTY scraper
    // around `claude`, or anything that emits UsageData JSON on stdout), it is
    // the explicit "check via a provided script" source and takes precedence
    // over the hub HTTP/SSH transports.
    //
    // It runs *before* the negative-cooldown gate on purpose: that cooldown
    // exists to avoid hammering a down *hub*, but an explicit command is an
    // independent source the user asked for — a hub outage must not silently
    // suppress it. Success is cached like a network fetch so the (potentially
    // slow) command is not re-run within the positive TTL.
    if let Some(cmd) = resolve_usage_command() {
        match run_usage_command(&cmd) {
            Ok(data) => {
                if let Err(e) = write_positive_cache(&data) {
                    eprintln!("csm: warning: could not write usage cache: {e}");
                }
                let _ = std::fs::remove_file(paths::fetch_failed());
                return Ok(data);
            }
            Err(e) => {
                // Command failed — fall through to the hub paths (the command is
                // an override, not a hard gate). The negative-cooldown check and
                // the final stamp below still apply to the hub transports.
                eprintln!("csm: warning: CSM_USAGE_CMD failed: {e}");
            }
        }
    }

    // Step 3 — negative cooldown (< NEGATIVE_COOLDOWN_SECS).
    // Shell lines 677–687.
    if negative_cache_active(negative_cooldown) {
        return Err(FetchError::NegativeCacheActive);
    }

    // Steps 4 + 5 — HTTP-first, then SSH fallback (POSIX only).
    // Shell lines 694–726.
    match do_network_fetch() {
        Ok(data) => {
            // Success — write positive cache, clear negative cache marker.
            // Shell lines 713–720.
            if let Err(e) = write_positive_cache(&data) {
                // Best-effort; don't fail on a caching error if the data is good.
                eprintln!("csm: warning: could not write usage cache: {e}");
            }
            let _ = std::fs::remove_file(paths::fetch_failed());
            Ok(data)
        }
        Err(e) => {
            // Failure — stamp the negative cache.
            // Shell lines 723–726.
            stamp_negative_cache();
            Err(e)
        }
    }
}

// ─── network fetch orchestration ─────────────────────────────────────────────

/// Run the HTTP-first network fetch, then SSH fallback on POSIX.
///
/// Returns the first successfully-parsed `UsageData`, or an `Err` if all
/// paths fail.
fn do_network_fetch() -> Result<UsageData, FetchError> {
    // HTTP first (all platforms).
    // Shell lines 694–698: if USAGE_URL is set-and-non-empty, try curl.
    // CLAUDE_USAGE_URL set-but-empty = disable HTTP.
    let usage_url = resolve_usage_url();

    if let Some(ref url) = usage_url {
        match http_fetch(url) {
            Ok(data) => return Ok(data),
            Err(_) => {
                // Fall through to SSH fallback (POSIX) or final failure (Windows).
            }
        }
    }

    // SSH fallback — POSIX only.
    // Shell lines 699–708: `out="$(timeout $SSH_DEADLINE ssh … 'cat "$HOME/claude-code-usage/cache/usage-limits.json"')"`.
    #[cfg(unix)]
    {
        ssh_fetch()
    }

    // Windows: HTTP is the only transport.
    #[cfg(not(unix))]
    {
        Err(FetchError::EmptyPayload)
    }
}

/// Resolve the usage URL from the environment.
///
/// Shell: `USAGE_URL="${CLAUDE_USAGE_URL-}"`.
/// The `-` (not `:-`) means: if `CLAUDE_USAGE_URL` is set but empty, use empty;
/// if unset, fall back to `DEFAULT_HUB_USAGE_URL` (also empty). Either way an
/// empty result yields `None` — HTTP is disabled unless a non-empty URL is set.
fn resolve_usage_url() -> Option<String> {
    let url = match std::env::var("CLAUDE_USAGE_URL") {
        Ok(val) => val,                             // set (possibly empty)
        Err(_) => DEFAULT_HUB_USAGE_URL.to_owned(), // unset = default (empty)
    };
    if url.is_empty() {
        None // empty = HTTP disabled
    } else {
        Some(url)
    }
}

// ─── user-supplied usage command (CSM_USAGE_CMD) ──────────────────────────────

/// Resolve the operator-supplied usage command from `CSM_USAGE_CMD`.
///
/// Empty/unset = disabled (returns `None`) — no command path is compiled in.
/// The command is run via the platform shell so a full pipeline / script path
/// works; its stdout must be a `UsageData` JSON object.
///
/// This honors the crate's separation invariant: the extraction *mechanism*
/// (which is fragile and site-specific — see the PoC findings on `claude`'s
/// `/usage`) is injected, never baked into the binary.
fn resolve_usage_command() -> Option<String> {
    std::env::var("CSM_USAGE_CMD")
        .ok()
        .map(|s| s.trim().to_owned())
        .filter(|s| !s.is_empty())
}

/// Run `cmd` through the platform shell, parse its stdout as `UsageData`.
///
/// Honors `CSM_USAGE_CMD_TIMEOUT` (seconds, default 10) as a hard deadline —
/// claude-direct extraction is slow (~2–30 s in PoC), so the command must not
/// block csm indefinitely on a prompt-path call.
fn run_usage_command(cmd: &str) -> Result<UsageData, FetchError> {
    use std::process::{Command, Stdio};
    use std::time::{Duration, Instant};

    let timeout_secs = std::env::var("CSM_USAGE_CMD_TIMEOUT")
        .ok()
        .and_then(|v| v.parse::<u64>().ok())
        .unwrap_or(10);

    #[cfg(unix)]
    let mut child = Command::new("sh")
        .args(["-c", cmd])
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .stdin(Stdio::null())
        .spawn()
        .map_err(|e| FetchError::Command(format!("spawn failed: {e}")))?;

    #[cfg(not(unix))]
    let mut child = Command::new("cmd")
        .args(["/C", cmd])
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .stdin(Stdio::null())
        .spawn()
        .map_err(|e| FetchError::Command(format!("spawn failed: {e}")))?;

    // Drain stdout on a dedicated thread so the child never blocks on a full
    // pipe buffer (~64 KB) while we poll for exit. Without this, a command that
    // emits more than the buffer deadlocks: the child blocks writing, we block in
    // try_wait, and the (valid) result is lost to the timeout. The reader thread
    // owns the pipe and reads to EOF, which it reaches when the child exits.
    let stdout_pipe = child
        .stdout
        .take()
        .ok_or_else(|| FetchError::Command("stdout pipe missing".into()))?;
    let reader = std::thread::spawn(move || {
        let mut buf = Vec::new();
        let mut pipe = stdout_pipe;
        std::io::Read::read_to_end(&mut pipe, &mut buf).map(|_| buf)
    });

    let start = Instant::now();
    let deadline = Duration::from_secs(timeout_secs);
    let status = loop {
        match child.try_wait() {
            Ok(Some(status)) => break status,
            Ok(None) => {
                if start.elapsed() >= deadline {
                    let _ = child.kill();
                    let _ = child.wait(); // reap so we don't leave a zombie
                                          // Do NOT join the reader here. Killing the direct child does
                                          // not guarantee the pipe's write-end closes: a grandchild
                                          // (e.g. `cmd | cat`) can inherit it and outlive the parent,
                                          // so read_to_end never reaches EOF and a join would block past
                                          // the deadline — defeating the whole timeout. Drop the handle
                                          // instead: the detached thread ends on its own once the last
                                          // write-end finally closes, and is reaped at process exit.
                    drop(reader);
                    return Err(FetchError::Command(format!(
                        "timed out after {timeout_secs}s"
                    )));
                }
                std::thread::sleep(Duration::from_millis(50));
            }
            Err(e) => {
                let _ = child.kill();
                let _ = child.wait();
                // Same rationale as the timeout path: a surviving grandchild can
                // keep the pipe open, so detach rather than join.
                drop(reader);
                return Err(FetchError::Command(format!("wait failed: {e}")));
            }
        }
    };

    let stdout_bytes = match reader.join() {
        Ok(Ok(bytes)) => bytes,
        Ok(Err(e)) => return Err(FetchError::Command(format!("read failed: {e}"))),
        Err(_) => return Err(FetchError::Command("stdout reader thread panicked".into())),
    };

    if !status.success() {
        return Err(FetchError::Command(format!(
            "command exited with status {status}"
        )));
    }

    // A clear diagnostic for non-UTF-8 output beats a confusing JSON parse error.
    let body = String::from_utf8(stdout_bytes)
        .map_err(|_| FetchError::Command("command output is not valid UTF-8".into()))?;
    if body.trim().is_empty() {
        return Err(FetchError::Command("command produced empty output".into()));
    }
    serde_json::from_str(&body)
        .map_err(|e| FetchError::Command(format!("output not UsageData: {e}")))
}

// ─── hub-local fast path ─────────────────────────────────────────────────────

/// The configured hub hostname (short name), or `None` when unset/empty.
///
/// The hub machine is site-specific, so the binary ships no compiled-in name.
/// Deployments that run a usage hub set `CLAUDE_HUB_HOSTNAME` (e.g. via an
/// Ansible-templated `settings.json`); when unset, both the hub-local fast path
/// and the SSH fallback are disabled — the correct behaviour for any machine
/// that is not itself the hub.
/// Shell: `USAGE_HUB="${CLAUDE_HUB_HOSTNAME-}"`.
pub fn hub_hostname() -> Option<String> {
    std::env::var("CLAUDE_HUB_HOSTNAME")
        .ok()
        .map(|h| h.trim().to_ascii_lowercase())
        .filter(|h| !h.is_empty())
}

/// True when usage metering is configured for this machine — either we ARE the
/// hub (`CLAUDE_HUB_HOSTNAME` matches this host) or a non-empty `CLAUDE_USAGE_URL`
/// is set. When this is `false`, [`fetch`] can never succeed; `csm usage` uses
/// this to print a "metering disabled" message instead of a transient error.
///
/// This is the env-opt-in gate: an external user (or a toss machine) with
/// neither variable set gets a clean "disabled" path, not a fetch failure.
///
/// A user-supplied `CSM_USAGE_CMD` also counts as configured — it is a usage
/// source in its own right, so `csm usage` must run the ladder (and hit the
/// command layer) rather than reporting "metering disabled".
pub fn is_configured() -> bool {
    is_hub_local() || resolve_usage_url().is_some() || resolve_usage_command().is_some()
}

/// Age in seconds of the positive usage cache file (`.usage-cache.json`), or
/// `None` when the cache is absent/unreadable. `csm usage` uses this to render
/// the "⚠ hub data is Nm old" stale header when serving cached data offline.
pub fn cache_age_secs() -> Option<u64> {
    let meta = std::fs::metadata(paths::usage_cache()).ok()?;
    Some(file_age_secs_from_meta(&meta))
}

/// True when this machine **is** the configured hub (read its cache directly,
/// skip all network). Always false when `CLAUDE_HUB_HOSTNAME` is unset/empty.
///
/// Shell lines 657–659: `host="$(hostname -s …)"; if printf '%s' "$host" | grep -qi "^$USAGE_HUB$"`
/// Case-insensitive match.
fn is_hub_local() -> bool {
    match hub_hostname() {
        Some(hub) => short_hostname().to_ascii_lowercase() == hub,
        None => false,
    }
}

/// Read the hub's own `usage-limits.json` (no network needed).
///
/// Shell line 660: `cat "$USAGE_CACHE"`.
fn read_hub_local() -> Result<UsageData, FetchError> {
    let path = paths::hub_local_cache();
    if !path.exists() {
        return Err(FetchError::EmptyPayload);
    }
    let raw = std::fs::read_to_string(&path)?;
    if raw.trim().is_empty() {
        return Err(FetchError::EmptyPayload);
    }
    let data: UsageData = serde_json::from_str(&raw)?;
    Ok(data)
}

/// Return the short hostname (no domain suffix), lowercase.
///
/// Shell: `hostname -s 2>/dev/null || hostname`.
/// On POSIX uses `nix::unistd::gethostname`; on Windows uses `GetComputerNameW`
/// via a subprocess (fallback to env var `COMPUTERNAME`).
fn short_hostname() -> String {
    #[cfg(unix)]
    {
        use nix::unistd::gethostname;
        gethostname()
            .ok()
            .and_then(|h| h.into_string().ok())
            // strip domain suffix — take everything up to the first '.'
            .map(|h| h.split('.').next().unwrap_or(&h).to_owned())
            .unwrap_or_default()
    }

    #[cfg(not(unix))]
    {
        // On Windows read %COMPUTERNAME% first (always set, no subprocess needed).
        std::env::var("COMPUTERNAME")
            .unwrap_or_default()
            .split('.')
            .next()
            .unwrap_or("")
            .to_ascii_lowercase()
            .to_owned()
    }
}

// ─── positive TTL cache ───────────────────────────────────────────────────────

/// Read the positive cache TTL (seconds). Default: 60.
///
/// Precedence: `CLAUDE_USAGE_TTL` (the legacy shell name) then
/// `CSM_USAGE_TTL_SECS` (the csm-native alias), then the default. Exposing the
/// alias lets users configure the cache lifetime under a csm-prefixed name
/// without knowing the legacy variable.
/// Shell: `USAGE_TTL="${CLAUDE_USAGE_TTL:-60}"`.
fn positive_ttl_secs() -> u64 {
    std::env::var("CLAUDE_USAGE_TTL")
        .ok()
        .and_then(|v| v.parse().ok())
        .or_else(|| {
            std::env::var("CSM_USAGE_TTL_SECS")
                .ok()
                .and_then(|v| v.parse().ok())
        })
        .unwrap_or(DEFAULT_POSITIVE_TTL_SECS)
}

/// Return `Ok(Some(data))` if the cache file exists, is non-empty, and its
/// mtime is less than `ttl_secs` old; `Ok(None)` if absent/stale; `Err` on
/// parse failure of a fresh file.
///
/// Shell lines 666–675:
/// ```sh
/// if [ -s "$pos_cache" ]; then
///   cmt="$(stat -f %m … || stat -c %Y …)"
///   cnow="$(date +%s)"
///   if [ $(( cnow - cmt )) -lt "$USAGE_TTL" ]; then cat "$pos_cache"; return 0; fi
/// fi
/// ```
fn try_positive_cache(ttl_secs: u64) -> Result<Option<UsageData>, FetchError> {
    let path = paths::usage_cache();
    if !path.exists() {
        return Ok(None);
    }

    // [ -s "$pos_cache" ] — non-zero size check.
    let meta = std::fs::metadata(&path)?;
    if meta.len() == 0 {
        return Ok(None);
    }

    let age = file_age_secs_from_meta(&meta);
    if age >= ttl_secs {
        return Ok(None);
    }

    // Fresh — parse and return.
    let raw = std::fs::read_to_string(&path)?;
    let data: UsageData = serde_json::from_str(&raw)?;
    Ok(Some(data))
}

// ─── negative cooldown cache ──────────────────────────────────────────────────

/// Read `CLAUDE_USAGE_FAIL_COOLDOWN` env (seconds). Default: 120.
/// Shell: `FETCH_FAIL_COOLDOWN="${CLAUDE_USAGE_FAIL_COOLDOWN:-120}"`.
fn negative_cooldown_secs() -> u64 {
    std::env::var("CLAUDE_USAGE_FAIL_COOLDOWN")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(DEFAULT_NEGATIVE_COOLDOWN_SECS)
}

/// True if the negative-cooldown file is recent (< `cooldown_secs`).
///
/// Shell lines 679–686:
/// ```sh
/// if [ -f "$fail_marker" ]; then
///   last="$(cat "$fail_marker" 2>/dev/null)"
///   now="$(date +%s)"
///   case "$last" in ''|*[!0-9]*) last=0 ;; esac
///   if [ $(( now - last )) -lt "$FETCH_FAIL_COOLDOWN" ]; then return 0; fi
/// fi
/// ```
///
/// Note: the shell reads the *content* of the file as an epoch, not the mtime.
/// However the shell also writes `date +%s` as content (line 725) in the same
/// process so content ≈ mtime. The shell reads content; we replicate that
/// exactly — read the epoch from the file content, fall back to 0 on parse
/// failure (matches the `case` guard `''|*[!0-9]*)` → `last=0`).
fn negative_cache_active(cooldown_secs: u64) -> bool {
    let path = paths::fetch_failed();
    if !path.exists() {
        return false;
    }
    // Read the epoch written into the file (shell line 681: `last="$(cat…)"`).
    let content = std::fs::read_to_string(&path).unwrap_or_default();
    let last_epoch: u64 = content.trim().parse().unwrap_or(0); // shell: case ''|*[!0-9]*) last=0
    let now_epoch = unix_now_secs();
    let age = now_epoch.saturating_sub(last_epoch);
    age < cooldown_secs
}

/// Write (or update) the negative-cooldown sentinel with the current epoch.
///
/// Shell line 725: `date +%s > "$fail_marker" 2>/dev/null`.
/// Best-effort; ignore errors.
fn stamp_negative_cache() {
    let path = paths::fetch_failed();
    // Ensure the parent directory exists.
    if let Some(parent) = path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    let epoch = unix_now_secs();
    let _ = std::fs::write(&path, epoch.to_string());
}

// ─── HTTP fetch ───────────────────────────────────────────────────────────────

/// Blocking HTTP fetch with tight timeouts.
///
/// Shell lines 695–697:
/// ```sh
/// out="$("$CURL" -fs --connect-timeout 1 --max-time "$HTTP_DEADLINE" "$USAGE_URL" 2>/dev/null)"
/// ```
/// connect-timeout = 1 s; total timeout = `HTTP_DEADLINE` (default 2 s).
///
/// `-f` = fail on HTTP 4xx/5xx; `-s` = silent.
/// Returns `Err` on any HTTP error (connection refused, timeout, non-2xx).
fn http_fetch(url: &str) -> Result<UsageData, FetchError> {
    use std::time::Duration;

    let http_timeout = std::env::var("CLAUDE_USAGE_HTTP_TIMEOUT")
        .ok()
        .and_then(|v| v.parse::<u64>().ok())
        .unwrap_or(DEFAULT_HTTP_TIMEOUT_SECS);

    let client = reqwest::blocking::Client::builder()
        .connect_timeout(Duration::from_secs(1))
        .timeout(Duration::from_secs(http_timeout))
        .build()
        .map_err(FetchError::Http)?;

    let resp = client.get(url).send().map_err(FetchError::Http)?;

    // Map HTTP errors (4xx/5xx) to failure — mirrors curl -f.
    let resp = resp.error_for_status().map_err(FetchError::Http)?;

    let body = resp.text().map_err(FetchError::Http)?;
    if body.trim().is_empty() {
        return Err(FetchError::EmptyPayload);
    }

    // Validate JSON before returning (shell line 699: `jq -e .`).
    let data: UsageData = serde_json::from_str(&body)?;
    Ok(data)
}

// ─── SSH fallback (POSIX only) ────────────────────────────────────────────────

/// SSH fallback path — POSIX only (ControlMaster socket reuse).
///
/// Reproduces shell lines 699–708:
/// ```sh
/// mkdir -p "$HOME/.ssh" 2>/dev/null
/// out="$("$TIMEOUT" "$SSH_DEADLINE" ssh "${SSH_OPTS[@]}" "$USAGE_HUB" \
///   'cat "$HOME/claude-code-usage/cache/usage-limits.json"' 2>/dev/null)"
/// ```
///
/// SSH options (shell `SSH_OPTS` array):
/// - `BatchMode=yes` (no interactive prompts)
/// - `ConnectTimeout=4`
/// - `ControlMaster=auto`
/// - `ControlPath` → `~/.ssh/cm-claude-%C.sock`
/// - `ControlPersist=300`
///
/// The outer `timeout $SSH_DEADLINE` is implemented here as a
/// `std::process::Command` with `wait_timeout`; we replicate the hard deadline
/// by spawning and checking within the deadline.
///
/// Spec §5 #5: "SSH fallback … POSIX-only behind `cfg(unix)`; Windows has HTTP-only."
#[cfg(unix)]
fn ssh_fetch() -> Result<UsageData, FetchError> {
    use std::process::{Command, Stdio};
    use std::time::{Duration, Instant};

    // No configured hub → no SSH fallback. (External machines that are not part
    // of a hub deployment never set CLAUDE_HUB_HOSTNAME, so we must not attempt
    // to ssh to an arbitrary host name.)
    let hub = hub_hostname().ok_or_else(|| FetchError::Ssh("no hub hostname configured".into()))?;

    // Ensure ~/.ssh exists (shell: `mkdir -p "$HOME/.ssh" 2>/dev/null`).
    if let Some(home) = dirs::home_dir() {
        let _ = std::fs::create_dir_all(home.join(".ssh"));
    }

    let ssh_deadline = std::env::var("CLAUDE_USAGE_SSH_TIMEOUT")
        .ok()
        .and_then(|v| v.parse::<u64>().ok())
        .unwrap_or(DEFAULT_SSH_DEADLINE_SECS);

    // Control path: `~/.ssh/cm-claude-%C.sock`.
    // `%C` is a `ssh_config` token; pass it literally — ssh expands it.
    let control_path = dirs::home_dir()
        .unwrap_or_else(|| std::path::PathBuf::from("."))
        .join(".ssh")
        .join("cm-claude-%C.sock");
    let control_path_str = control_path.to_string_lossy().to_string();

    // Remote command: single-quoted so $HOME expands on the REMOTE side.
    // Shell line 708: `'cat "$HOME/claude-code-usage/cache/usage-limits.json"'`
    let remote_cmd = r#"cat "$HOME/claude-code-usage/cache/usage-limits.json""#;

    let start = Instant::now();
    let mut child = Command::new("ssh")
        .args([
            "-o",
            "BatchMode=yes",
            "-o",
            "ConnectTimeout=4",
            "-o",
            "ControlMaster=auto",
            "-o",
            &format!("ControlPath={control_path_str}"),
            "-o",
            "ControlPersist=300",
            hub.as_str(), // short MagicDNS name (ssh_config FQDN pin handles resolution)
            remote_cmd,
        ])
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .map_err(|e| FetchError::Ssh(format!("spawn failed: {e}")))?;

    // Poll for exit within the deadline (replicates `timeout $SSH_DEADLINE ssh …`).
    let deadline = Duration::from_secs(ssh_deadline);
    let output = loop {
        match child.try_wait() {
            Ok(Some(_)) => {
                break child
                    .wait_with_output()
                    .map_err(|e| FetchError::Ssh(format!("wait_with_output failed: {e}")))?;
            }
            Ok(None) => {
                if start.elapsed() >= deadline {
                    let _ = child.kill();
                    return Err(FetchError::Ssh(format!(
                        "ssh timed out after {ssh_deadline}s"
                    )));
                }
                std::thread::sleep(std::time::Duration::from_millis(50));
            }
            Err(e) => {
                return Err(FetchError::Ssh(format!("wait failed: {e}")));
            }
        }
    };

    if !output.status.success() {
        return Err(FetchError::Ssh(format!(
            "ssh exited with status {}",
            output.status
        )));
    }

    let body = String::from_utf8_lossy(&output.stdout).to_string();
    if body.trim().is_empty() {
        return Err(FetchError::EmptyPayload);
    }

    // Shell line 699: validate JSON (`jq -e .`).
    let data: UsageData = serde_json::from_str(&body)?;
    Ok(data)
}

// ─── cache write ─────────────────────────────────────────────────────────────

/// Atomically write `data` to `.usage-cache.json` (tmp + rename).
///
/// Shell lines 716–719:
/// ```sh
/// printf '%s' "$out" > "$pos_cache.$$" 2>/dev/null \
///   && mv -f "$pos_cache.$$" "$pos_cache" 2>/dev/null \
///   || rm -f "$pos_cache.$$" 2>/dev/null
/// ```
///
/// We serialize the `UsageData` back to JSON (the same bytes we received, via
/// serde). The spec says "only validated JSON is ever cached" — we already
/// parsed it above, so serialization here is just re-encoding the same data.
fn write_positive_cache(data: &UsageData) -> Result<(), FetchError> {
    let cache_path = paths::usage_cache();
    let parent = cache_path
        .parent()
        .unwrap_or_else(|| std::path::Path::new("."));
    std::fs::create_dir_all(parent)?;

    // Write to a temp file in the same directory (same FS = atomic rename).
    let tmp_path = parent.join(format!(".usage-cache.json.{}", std::process::id()));

    let json_bytes = serde_json::to_vec(data)?;
    std::fs::write(&tmp_path, &json_bytes)?;

    // Atomic rename (mv -f).
    if let Err(e) = std::fs::rename(&tmp_path, &cache_path) {
        let _ = std::fs::remove_file(&tmp_path);
        return Err(FetchError::Io(e));
    }

    Ok(())
}

// ─── utility ─────────────────────────────────────────────────────────────────

/// Return the age of `path` in seconds (wall clock now − mtime).
/// Returns `Err(FetchError::Io)` if the metadata cannot be read.
/// Test-only: production paths call `file_age_secs_from_meta` to avoid a second `stat`.
#[cfg(test)]
fn file_age_secs(path: &std::path::Path) -> Result<u64, FetchError> {
    let meta = std::fs::metadata(path)?;
    Ok(file_age_secs_from_meta(&meta))
}

/// Compute age from an already-fetched `Metadata` (avoids a second `stat` call).
fn file_age_secs_from_meta(meta: &std::fs::Metadata) -> u64 {
    let mtime = meta.modified().unwrap_or(std::time::UNIX_EPOCH);
    let now = std::time::SystemTime::now();
    now.duration_since(mtime).map(|d| d.as_secs()).unwrap_or(0)
}

/// Current Unix epoch in seconds.
fn unix_now_secs() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

// ─── test helpers (not network-touching) ──────────────────────────────────────
//
// These functions are exposed (non-pub, but usable in `#[cfg(test)]`) so unit
// tests can drive freshness via injected file mtimes without hitting the
// network.

/// Parse raw JSON bytes as `UsageData` — the same validation gate the real
/// fetch uses.  Used in tests to verify that only valid JSON passes through.
#[cfg(test)]
pub(crate) fn parse_usage_json(raw: &str) -> Result<UsageData, FetchError> {
    if raw.trim().is_empty() {
        return Err(FetchError::EmptyPayload);
    }
    let data: UsageData = serde_json::from_str(raw)?;
    Ok(data)
}

// ─── tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::sync::Mutex;
    use tempfile::TempDir;

    /// Global mutex for tests that mutate process-wide env vars.
    /// Rust test harness runs tests in parallel by default; env var mutation
    /// without serialization causes races between tests that read+write the
    /// same env key (e.g. `resolve_usage_url_*`, `positive_ttl_*`,
    /// `negative_cooldown_*`).
    static ENV_LOCK: Mutex<()> = Mutex::new(());

    // ── shared fixture JSON ────────────────────────────────────────────────────

    const VALID_USAGE_JSON: &str = r#"{
      "captured_at": "2026-06-17T07:13:19Z",
      "profiles": {
        "home": {
          "session":  { "pct": 42, "resets": "9pm (Asia/Seoul)" },
          "week_all": { "pct": 31, "resets": "Jun 18 at 9pm (Asia/Seoul)" }
        },
        "work": {
          "session":  { "pct": 5, "resets": null },
          "week_all": { "pct": 67, "resets": "Jun 20 at 8:20pm (Asia/Seoul)" },
          "week_sonnet": null
        }
      },
      "errors": { "broken": "HTTP 401" }
    }"#;

    const INVALID_JSON: &str = r#"{ "profiles": { "p": INVALID }"#;

    // ── helper: write a file with an artificial mtime ─────────────────────────

    /// Write `content` to `path` and set its mtime to `now - age_secs` seconds
    /// ago so the TTL/freshness logic sees the desired age.
    ///
    /// Uses `touch -t [[CC]YY]MMDDhhmm[.SS]` (BSD macOS touch, also accepted
    /// by GNU touch), derived from a computed target epoch via `date -r EPOCH`
    /// (macOS) or `date -d @EPOCH` (Linux/GNU).  Both this helper and all its
    /// callers are `#[cfg(unix)]` (the mtime-aging trick is POSIX-only).
    #[cfg(unix)]
    fn write_aged_file(path: &std::path::Path, content: &str, age_secs: u64) {
        fs::write(path, content).unwrap();

        #[cfg(unix)]
        {
            let target_epoch = unix_now_secs().saturating_sub(age_secs);

            // Try `date -r EPOCH …` (macOS/BSD) then `date -d @EPOCH …` (GNU).
            let ts = std::process::Command::new("date")
                .args(["-r", &target_epoch.to_string(), "+%Y%m%d%H%M.%S"])
                .output()
                .ok()
                .filter(|o| o.status.success())
                .and_then(|o| String::from_utf8(o.stdout).ok())
                .map(|s| s.trim().to_owned())
                .or_else(|| {
                    std::process::Command::new("date")
                        .args(["-d", &format!("@{target_epoch}"), "+%Y%m%d%H%M.%S"])
                        .output()
                        .ok()
                        .filter(|o| o.status.success())
                        .and_then(|o| String::from_utf8(o.stdout).ok())
                        .map(|s| s.trim().to_owned())
                })
                .expect("could not format touch timestamp via date -r or date -d");

            let status = std::process::Command::new("touch")
                .args(["-t", &ts, path.to_string_lossy().as_ref()])
                .status()
                .expect("touch -t invocation failed");
            assert!(status.success(), "touch -t exited with failure for ts={ts}");
        }
    }

    // ── parse_usage_json ──────────────────────────────────────────────────────

    #[test]
    fn parse_valid_json_succeeds() {
        let result = parse_usage_json(VALID_USAGE_JSON);
        assert!(
            result.is_ok(),
            "expected Ok for valid JSON, got: {result:?}"
        );
        let data = result.unwrap();
        assert!(data.profiles.contains_key("home"));
    }

    #[test]
    fn parse_empty_string_returns_empty_payload() {
        let result = parse_usage_json("");
        assert!(
            matches!(result, Err(FetchError::EmptyPayload)),
            "expected EmptyPayload for empty string, got: {result:?}"
        );
    }

    #[test]
    fn parse_whitespace_only_returns_empty_payload() {
        let result = parse_usage_json("   \n  ");
        assert!(
            matches!(result, Err(FetchError::EmptyPayload)),
            "expected EmptyPayload for whitespace, got: {result:?}"
        );
    }

    #[test]
    fn parse_invalid_json_returns_json_error() {
        let result = parse_usage_json(INVALID_JSON);
        assert!(
            matches!(result, Err(FetchError::Json(_))),
            "expected Json error for invalid JSON, got: {result:?}"
        );
    }

    #[test]
    fn parse_minimal_json_succeeds() {
        let json = r#"{"profiles": {}}"#;
        let result = parse_usage_json(json);
        assert!(
            result.is_ok(),
            "expected Ok for minimal JSON, got: {result:?}"
        );
    }

    // ── negative_cache_active ─────────────────────────────────────────────────

    #[test]
    fn negative_cache_absent_is_not_active() {
        let dir = TempDir::new().unwrap();
        // Point fetch_failed path to a non-existent file.
        // We can't directly inject paths::fetch_failed() in tests, so we test
        // the logic via the content-based function with the actual path helpers
        // by using a temp dir and checking file_age_secs returns correct values.
        //
        // The negative_cache_active function reads paths::fetch_failed() which
        // is under $HOME. We test the LOGIC of the cooldown here with a helper.
        let _ = dir; // suppress unused

        // Test: a file that doesn't exist → not active.
        let non_existent = std::path::Path::new("/tmp/csm_test_never_exists_xyz123.fail");
        assert!(
            !non_existent.exists(),
            "precondition: file should not exist"
        );

        // The logic: if file doesn't exist → false.
        let active = if !non_existent.exists() {
            false
        } else {
            true // would read content
        };
        assert!(!active);
    }

    #[test]
    fn negative_cache_content_based_epoch_within_cooldown() {
        // Simulate the shell content-based logic:
        // stamp = now - 30s → still within 120s cooldown.
        let now = unix_now_secs();
        let stamp = now.saturating_sub(30);
        let content = stamp.to_string();

        // Parse as the function does.
        let last_epoch: u64 = content.trim().parse().unwrap_or(0);
        let age = now.saturating_sub(last_epoch);
        assert!(age < 120, "30s old stamp should be within 120s cooldown");
    }

    #[test]
    fn negative_cache_content_based_epoch_beyond_cooldown() {
        // Stamp = now - 200s → beyond 120s cooldown.
        let now = unix_now_secs();
        let stamp = now.saturating_sub(200);
        let last_epoch: u64 = stamp.to_string().trim().parse().unwrap_or(0);
        let age = now.saturating_sub(last_epoch);
        assert!(age >= 120, "200s old stamp should be beyond 120s cooldown");
    }

    #[test]
    fn negative_cache_empty_content_treated_as_zero() {
        // Shell: `case "$last" in ''|*[!0-9]*) last=0 ;; esac`.
        let content = "";
        let last_epoch: u64 = content.trim().parse().unwrap_or(0);
        assert_eq!(last_epoch, 0, "empty content should parse as 0");
    }

    #[test]
    fn negative_cache_non_numeric_content_treated_as_zero() {
        // Shell: `*[!0-9]*)` matches non-numeric → last=0.
        let content = "not-a-number";
        let last_epoch: u64 = content.trim().parse().unwrap_or(0);
        assert_eq!(last_epoch, 0, "non-numeric content should parse as 0");
    }

    #[test]
    fn negative_cache_roundtrip_via_tempdir() {
        // Write a stamp file with a recent epoch and verify cooldown logic
        // correctly identifies it as active.
        let dir = TempDir::new().unwrap();
        let fail_path = dir.path().join(".usage-fetch-failed");

        let now = unix_now_secs();
        // Stamp = now - 10s (within 120s cooldown).
        let stamp = now.saturating_sub(10);
        fs::write(&fail_path, stamp.to_string()).unwrap();

        // Read back and apply the same logic.
        let content = fs::read_to_string(&fail_path).unwrap();
        let last_epoch: u64 = content.trim().parse().unwrap_or(0);
        let age = now.saturating_sub(last_epoch);
        assert!(age < 120, "10s old stamp should be within 120s cooldown");
    }

    #[test]
    fn negative_cache_roundtrip_expired_stamp() {
        let dir = TempDir::new().unwrap();
        let fail_path = dir.path().join(".usage-fetch-failed");

        let now = unix_now_secs();
        // Stamp = now - 150s (beyond 120s cooldown).
        let stamp = now.saturating_sub(150);
        fs::write(&fail_path, stamp.to_string()).unwrap();

        let content = fs::read_to_string(&fail_path).unwrap();
        let last_epoch: u64 = content.trim().parse().unwrap_or(0);
        let age = now.saturating_sub(last_epoch);
        assert!(age >= 120, "150s old stamp should be beyond 120s cooldown");
    }

    // ── positive TTL cache (mtime-based) ──────────────────────────────────────

    /// Test that a file written RIGHT NOW has age ≈ 0 and is therefore "fresh"
    /// for any positive TTL > 0.
    #[test]
    fn positive_cache_fresh_file_has_small_age() {
        let dir = TempDir::new().unwrap();
        let cache = dir.path().join(".usage-cache.json");
        fs::write(&cache, VALID_USAGE_JSON).unwrap();

        let meta = fs::metadata(&cache).unwrap();
        let age = file_age_secs_from_meta(&meta);
        assert!(age < 5, "just-written file should have age < 5s, got {age}");
    }

    #[test]
    #[cfg(unix)]
    fn positive_cache_stale_file_exceeds_ttl() {
        let dir = TempDir::new().unwrap();
        let cache = dir.path().join(".usage-cache.json");
        // Write a file dated 90 seconds ago — stale for the 60s TTL.
        write_aged_file(&cache, VALID_USAGE_JSON, 90);

        let meta = fs::metadata(&cache).unwrap();
        let age = file_age_secs_from_meta(&meta);
        assert!(
            age >= 60,
            "file aged 90s should have age >= 60s (TTL), got {age}"
        );
    }

    #[test]
    #[cfg(unix)]
    fn positive_cache_fresh_file_within_ttl() {
        let dir = TempDir::new().unwrap();
        let cache = dir.path().join(".usage-cache.json");
        // Write a file dated 30 seconds ago — fresh for the 60s TTL.
        write_aged_file(&cache, VALID_USAGE_JSON, 30);

        let meta = fs::metadata(&cache).unwrap();
        let age = file_age_secs_from_meta(&meta);
        assert!(
            age < 60,
            "file aged 30s should have age < 60s (TTL), got {age}"
        );
    }

    // ── JSON validation gate ───────────────────────────────────────────────────

    /// Only valid JSON should ever be written to the positive cache.
    /// This mirrors the shell check: `if … | jq -e . >/dev/null 2>&1; then … cache`.
    #[test]
    fn json_validation_gate_blocks_invalid() {
        let result = parse_usage_json(INVALID_JSON);
        assert!(
            matches!(result, Err(FetchError::Json(_))),
            "invalid JSON must not pass the validation gate"
        );
    }

    #[test]
    fn json_validation_gate_passes_valid() {
        let result = parse_usage_json(VALID_USAGE_JSON);
        assert!(result.is_ok(), "valid JSON must pass the validation gate");
    }

    // ── write_positive_cache (atomic write) ───────────────────────────────────

    /// After a successful `write_positive_cache`, the target path exists,
    /// contains valid JSON, and no temp file remains.
    #[test]
    fn write_positive_cache_writes_valid_json_atomically() {
        let dir = TempDir::new().unwrap();
        let cache_path = dir.path().join(".usage-cache.json");

        // Override paths::usage_cache() is not possible without injection,
        // but we can test the atomic-write logic directly.
        let data: UsageData = serde_json::from_str(VALID_USAGE_JSON).unwrap();
        let json_bytes = serde_json::to_vec(&data).unwrap();

        let tmp_path = dir.path().join(".usage-cache.json.testpid");
        fs::write(&tmp_path, &json_bytes).unwrap();
        fs::rename(&tmp_path, &cache_path).unwrap();

        // Verify the final file is valid.
        assert!(cache_path.exists(), "cache file should exist after write");
        assert!(!tmp_path.exists(), "tmp file should not exist after rename");

        let on_disk = fs::read_to_string(&cache_path).unwrap();
        let parsed: UsageData =
            serde_json::from_str(&on_disk).expect("on-disk cache must be valid JSON");
        assert!(
            parsed.profiles.contains_key("home"),
            "on-disk cache should contain home profile"
        );
    }

    // ── stamp_negative_cache / unix_now_secs ──────────────────────────────────

    #[test]
    fn unix_now_secs_is_reasonable() {
        let now = unix_now_secs();
        // Must be after 2026-01-01 00:00:00 UTC = 1767225600.
        assert!(
            now > 1_767_225_600,
            "unix_now_secs should return a sane epoch, got {now}"
        );
    }

    #[test]
    fn stamp_and_read_negative_cache_via_tempdir() {
        // We can't override global paths in tests, but we can test the
        // stamp_negative_cache content-format assumption: content == epoch string.
        let now_before = unix_now_secs();
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("fail");

        // Simulate what stamp_negative_cache does.
        let epoch = unix_now_secs();
        fs::write(&path, epoch.to_string()).unwrap();
        let now_after = unix_now_secs();

        let content = fs::read_to_string(&path).unwrap();
        let stored: u64 = content.trim().parse().unwrap();
        assert!(stored >= now_before, "stored epoch should be >= before");
        assert!(stored <= now_after, "stored epoch should be <= after");
    }

    // ── resolve_usage_url ─────────────────────────────────────────────────────
    //
    // These three tests mutate the same env var; they acquire ENV_LOCK to
    // prevent parallel interference with each other.

    #[test]
    fn resolve_usage_url_disabled_when_env_unset() {
        // The binary ships no compiled-in hub URL, so an unset CLAUDE_USAGE_URL
        // means HTTP is disabled (None) — identical to set-but-empty.
        let _guard = ENV_LOCK.lock().unwrap();
        let saved = std::env::var("CLAUDE_USAGE_URL").ok();
        std::env::remove_var("CLAUDE_USAGE_URL");

        let url = resolve_usage_url();
        assert!(
            url.is_none(),
            "unset CLAUDE_USAGE_URL should disable HTTP (no compiled default)"
        );

        match saved {
            Some(v) => std::env::set_var("CLAUDE_USAGE_URL", v),
            None => std::env::remove_var("CLAUDE_USAGE_URL"),
        }
    }

    #[test]
    fn resolve_usage_url_empty_disables_http() {
        let _guard = ENV_LOCK.lock().unwrap();
        let saved = std::env::var("CLAUDE_USAGE_URL").ok();
        std::env::set_var("CLAUDE_USAGE_URL", "");

        let url = resolve_usage_url();
        assert!(url.is_none(), "empty CLAUDE_USAGE_URL should disable HTTP");

        match saved {
            Some(v) => std::env::set_var("CLAUDE_USAGE_URL", v),
            None => std::env::remove_var("CLAUDE_USAGE_URL"),
        }
    }

    #[test]
    fn resolve_usage_url_custom_value() {
        let _guard = ENV_LOCK.lock().unwrap();
        let saved = std::env::var("CLAUDE_USAGE_URL").ok();
        std::env::set_var("CLAUDE_USAGE_URL", "http://custom-hub/api");

        let url = resolve_usage_url();
        assert_eq!(url.as_deref(), Some("http://custom-hub/api"));

        match saved {
            Some(v) => std::env::set_var("CLAUDE_USAGE_URL", v),
            None => std::env::remove_var("CLAUDE_USAGE_URL"),
        }
    }

    // ── CSM_USAGE_CMD (user-supplied usage command) ───────────────────────────

    #[test]
    fn resolve_usage_command_disabled_when_unset() {
        let _guard = ENV_LOCK.lock().unwrap();
        let saved = std::env::var("CSM_USAGE_CMD").ok();
        std::env::remove_var("CSM_USAGE_CMD");
        assert!(resolve_usage_command().is_none(), "unset → None");
        // set-but-empty / whitespace → None
        std::env::set_var("CSM_USAGE_CMD", "   ");
        assert!(resolve_usage_command().is_none(), "blank → None");
        match saved {
            Some(v) => std::env::set_var("CSM_USAGE_CMD", v),
            None => std::env::remove_var("CSM_USAGE_CMD"),
        }
    }

    #[test]
    #[cfg(unix)]
    fn run_usage_command_parses_valid_json_stdout() {
        // A command that emits a valid UsageData JSON on stdout → Ok(data).
        // VALID_USAGE_JSON is tiny (~350 bytes), so inlining it as a shell
        // argument is ARG_MAX-safe. Do NOT inline a LARGE payload this way —
        // it overflows execve's ARG_MAX on Linux (see the deadlock test below,
        // which has the child generate its big payload via awk instead).
        let cmd = format!("printf '%s' '{}'", VALID_USAGE_JSON.replace('\n', " "));
        let result = run_usage_command(&cmd);
        assert!(result.is_ok(), "expected Ok, got: {result:?}");
        assert!(result.unwrap().profiles.contains_key("home"));
    }

    #[test]
    #[cfg(unix)]
    fn run_usage_command_nonzero_exit_is_command_error() {
        let result = run_usage_command("exit 3");
        assert!(
            matches!(result, Err(FetchError::Command(_))),
            "non-zero exit must be a Command error, got: {result:?}"
        );
    }

    #[test]
    #[cfg(unix)]
    fn run_usage_command_empty_stdout_is_command_error() {
        let result = run_usage_command("true"); // exits 0, no stdout
        assert!(
            matches!(result, Err(FetchError::Command(_))),
            "empty stdout must be a Command error, got: {result:?}"
        );
    }

    #[test]
    #[cfg(unix)]
    fn run_usage_command_non_json_stdout_is_command_error() {
        let result = run_usage_command("echo not-json-at-all");
        assert!(
            matches!(result, Err(FetchError::Command(_))),
            "non-JSON stdout must be a Command error, got: {result:?}"
        );
    }

    #[test]
    #[cfg(unix)]
    fn run_usage_command_respects_timeout() {
        let _guard = ENV_LOCK.lock().unwrap();
        let saved = std::env::var("CSM_USAGE_CMD_TIMEOUT").ok();
        std::env::set_var("CSM_USAGE_CMD_TIMEOUT", "1");
        let start = std::time::Instant::now();
        let result = run_usage_command("sleep 10");
        let elapsed = start.elapsed();
        assert!(
            matches!(result, Err(FetchError::Command(_))),
            "a command past the deadline must error, got: {result:?}"
        );
        assert!(
            elapsed < std::time::Duration::from_secs(5),
            "timeout must fire well before the command's own 10s, took {elapsed:?}"
        );
        match saved {
            Some(v) => std::env::set_var("CSM_USAGE_CMD_TIMEOUT", v),
            None => std::env::remove_var("CSM_USAGE_CMD_TIMEOUT"),
        }
    }

    #[test]
    #[cfg(unix)]
    fn run_usage_command_handles_large_output_without_deadlock() {
        // Regression for the pipe-deadlock finding: if the command writes more
        // than the OS pipe buffer (~64 KB) to stdout, a wait-then-read loop that
        // never drains the pipe will deadlock — the child blocks on write while
        // we block in try_wait — and only escape via the timeout, discarding the
        // (valid) result. Build a >256 KB valid UsageData JSON and assert it
        // parses well within a short deadline.
        let _guard = ENV_LOCK.lock().unwrap();
        let saved = std::env::var("CSM_USAGE_CMD_TIMEOUT").ok();
        // 3s deadline: comfortably long for a correct drain, but far shorter than
        // the wall time a deadlock would burn — so a deadlock fails the test fast.
        std::env::set_var("CSM_USAGE_CMD_TIMEOUT", "3");

        // Have the CHILD generate the large payload itself, via a tiny awk
        // program, rather than inlining a >256 KB JSON string as a shell
        // ARGUMENT. Inlining it (`printf '%s' '<huge json>'`) overflows
        // ARG_MAX on Linux (execve E2BIG) even though macOS's larger ARG_MAX
        // tolerated it — that divergence is exactly what broke CI. The awk
        // command string is ~300 bytes (ARG_MAX-safe by 400x) while its stdout
        // is ~341 KB, comfortably past the OS pipe buffer (~64 KB) that the
        // drain thread must survive. POSIX awk only (BEGIN, printf, C-style
        // for/if, %d, % modulo) — no gawk extensions, no seq, no bash-isms —
        // so it runs identically on GNU/Linux and BSD/macOS. i goes 0..=3000,
        // yielding 3001 profiles.
        let n_profiles = 3001;
        let cmd = r#"awk 'BEGIN{printf "{\"captured_at\":\"2024-01-01T00:00:00Z\",\"profiles\":{"; for(i=0;i<=3000;i++){if(i>0)printf ","; printf "\"p%d\":{\"session\":{\"pct\":%d,\"resets\":\"2024-01-01T00:00:00Z\"},\"week_all\":{\"pct\":%d,\"resets\":\"2024-01-01T00:00:00Z\"}}",i,i%100,i%100}; printf "},\"errors\":{}}"}'"#;
        let start = std::time::Instant::now();
        let result = run_usage_command(cmd);
        let elapsed = start.elapsed();

        assert!(
            result.is_ok(),
            "large output must parse (deadlock would time out): {result:?}"
        );
        assert_eq!(
            result.unwrap().profiles.len(),
            n_profiles,
            "all profiles parsed"
        );
        assert!(
            elapsed < std::time::Duration::from_secs(3),
            "must not hit the deadline — a deadlock would, took {elapsed:?}"
        );

        match saved {
            Some(v) => std::env::set_var("CSM_USAGE_CMD_TIMEOUT", v),
            None => std::env::remove_var("CSM_USAGE_CMD_TIMEOUT"),
        }
    }

    #[test]
    #[cfg(unix)]
    fn run_usage_command_timeout_is_hard_even_when_a_grandchild_holds_the_pipe() {
        // The stdout-drain thread reads to EOF, which it only reaches when the
        // pipe's last write-end closes. On timeout we kill the DIRECT child
        // (`sh`), but a grandchild can inherit the same stdout pipe and outlive
        // it — e.g. `sleep | cat`, where `cat` holds the write-end. If the
        // timeout path were to `reader.join()` unconditionally, that join would
        // block until the grandchild died on its own, silently defeating the
        // hard deadline. This test pins that the timeout returns within the
        // deadline regardless of a surviving grandchild.
        let _guard = ENV_LOCK.lock().unwrap();
        let saved = std::env::var("CSM_USAGE_CMD_TIMEOUT").ok();
        std::env::set_var("CSM_USAGE_CMD_TIMEOUT", "1");

        // `sleep 30 | cat`: cat inherits our stdout pipe and stays alive ~30s
        // after sh is killed, holding the write-end open so read_to_end can't
        // reach EOF.
        let start = std::time::Instant::now();
        let result = run_usage_command("sleep 30 | cat");
        let elapsed = start.elapsed();

        assert!(
            matches!(result, Err(FetchError::Command(_))),
            "a command past the deadline must error, got: {result:?}"
        );
        assert!(
            elapsed < std::time::Duration::from_secs(5),
            "timeout must stay hard even with a grandchild holding the pipe, took {elapsed:?}"
        );

        match saved {
            Some(v) => std::env::set_var("CSM_USAGE_CMD_TIMEOUT", v),
            None => std::env::remove_var("CSM_USAGE_CMD_TIMEOUT"),
        }
    }

    #[test]
    fn is_configured_true_when_only_command_set() {
        let _guard = ENV_LOCK.lock().unwrap();
        let saved_cmd = std::env::var("CSM_USAGE_CMD").ok();
        let saved_url = std::env::var("CLAUDE_USAGE_URL").ok();
        let saved_hub = std::env::var("CLAUDE_HUB_HOSTNAME").ok();
        // Disable hub paths, enable only the command.
        std::env::set_var("CLAUDE_USAGE_URL", "");
        std::env::remove_var("CLAUDE_HUB_HOSTNAME");
        std::env::set_var("CSM_USAGE_CMD", "echo {}");
        assert!(
            is_configured(),
            "CSM_USAGE_CMD alone must count as configured"
        );
        // restore
        match saved_cmd {
            Some(v) => std::env::set_var("CSM_USAGE_CMD", v),
            None => std::env::remove_var("CSM_USAGE_CMD"),
        }
        match saved_url {
            Some(v) => std::env::set_var("CLAUDE_USAGE_URL", v),
            None => std::env::remove_var("CLAUDE_USAGE_URL"),
        }
        match saved_hub {
            Some(v) => std::env::set_var("CLAUDE_HUB_HOSTNAME", v),
            None => std::env::remove_var("CLAUDE_HUB_HOSTNAME"),
        }
    }

    #[test]
    fn positive_ttl_alias_csm_secs() {
        let _guard = ENV_LOCK.lock().unwrap();
        let saved_legacy = std::env::var("CLAUDE_USAGE_TTL").ok();
        let saved_alias = std::env::var("CSM_USAGE_TTL_SECS").ok();
        // Legacy unset, alias set → alias wins.
        std::env::remove_var("CLAUDE_USAGE_TTL");
        std::env::set_var("CSM_USAGE_TTL_SECS", "17");
        assert_eq!(positive_ttl_secs(), 17, "alias should be honored");
        // Legacy set → legacy takes precedence over alias.
        std::env::set_var("CLAUDE_USAGE_TTL", "5");
        assert_eq!(positive_ttl_secs(), 5, "legacy var should win over alias");
        match saved_legacy {
            Some(v) => std::env::set_var("CLAUDE_USAGE_TTL", v),
            None => std::env::remove_var("CLAUDE_USAGE_TTL"),
        }
        match saved_alias {
            Some(v) => std::env::set_var("CSM_USAGE_TTL_SECS", v),
            None => std::env::remove_var("CSM_USAGE_TTL_SECS"),
        }
    }

    // ── is_hub_local ──────────────────────────────────────────────────────────

    #[test]
    fn short_hostname_is_nonempty() {
        // Can't assert what it equals in CI, but it must not be empty.
        let h = short_hostname();
        assert!(!h.is_empty(), "short_hostname() must not be empty");
    }

    #[test]
    fn hub_hostname_env_contract() {
        let _guard = ENV_LOCK.lock().unwrap();
        let saved = std::env::var("CLAUDE_HUB_HOSTNAME").ok();

        // Unset → None (no compiled-in hub name → fast path + SSH disabled).
        std::env::remove_var("CLAUDE_HUB_HOSTNAME");
        assert!(hub_hostname().is_none(), "unset → None");

        // Set-but-empty / whitespace → None.
        std::env::set_var("CLAUDE_HUB_HOSTNAME", "  ");
        assert!(hub_hostname().is_none(), "blank → None");

        // Set → trimmed + lowercased.
        std::env::set_var("CLAUDE_HUB_HOSTNAME", " Some-Hub ");
        assert_eq!(hub_hostname().as_deref(), Some("some-hub"));

        match saved {
            Some(v) => std::env::set_var("CLAUDE_HUB_HOSTNAME", v),
            None => std::env::remove_var("CLAUDE_HUB_HOSTNAME"),
        }
    }

    // ── positive_ttl_secs / negative_cooldown_secs env overrides ─────────────
    //
    // These tests also mutate env vars; acquire ENV_LOCK.

    #[test]
    fn positive_ttl_defaults_to_60() {
        let _guard = ENV_LOCK.lock().unwrap();
        let saved = std::env::var("CLAUDE_USAGE_TTL").ok();
        std::env::remove_var("CLAUDE_USAGE_TTL");
        assert_eq!(positive_ttl_secs(), 60);
        match saved {
            Some(v) => std::env::set_var("CLAUDE_USAGE_TTL", v),
            None => std::env::remove_var("CLAUDE_USAGE_TTL"),
        }
    }

    #[test]
    fn positive_ttl_respects_env_override() {
        let _guard = ENV_LOCK.lock().unwrap();
        let saved = std::env::var("CLAUDE_USAGE_TTL").ok();
        std::env::set_var("CLAUDE_USAGE_TTL", "30");
        assert_eq!(positive_ttl_secs(), 30);
        match saved {
            Some(v) => std::env::set_var("CLAUDE_USAGE_TTL", v),
            None => std::env::remove_var("CLAUDE_USAGE_TTL"),
        }
    }

    #[test]
    fn negative_cooldown_defaults_to_120() {
        let _guard = ENV_LOCK.lock().unwrap();
        let saved = std::env::var("CLAUDE_USAGE_FAIL_COOLDOWN").ok();
        std::env::remove_var("CLAUDE_USAGE_FAIL_COOLDOWN");
        assert_eq!(negative_cooldown_secs(), 120);
        match saved {
            Some(v) => std::env::set_var("CLAUDE_USAGE_FAIL_COOLDOWN", v),
            None => std::env::remove_var("CLAUDE_USAGE_FAIL_COOLDOWN"),
        }
    }

    #[test]
    fn negative_cooldown_respects_env_override() {
        let _guard = ENV_LOCK.lock().unwrap();
        let saved = std::env::var("CLAUDE_USAGE_FAIL_COOLDOWN").ok();
        std::env::set_var("CLAUDE_USAGE_FAIL_COOLDOWN", "60");
        assert_eq!(negative_cooldown_secs(), 60);
        match saved {
            Some(v) => std::env::set_var("CLAUDE_USAGE_FAIL_COOLDOWN", v),
            None => std::env::remove_var("CLAUDE_USAGE_FAIL_COOLDOWN"),
        }
    }

    // ── file_age_secs ─────────────────────────────────────────────────────────

    #[test]
    fn file_age_secs_fresh_file_is_small() {
        let dir = TempDir::new().unwrap();
        let f = dir.path().join("test.txt");
        fs::write(&f, "hello").unwrap();
        let age = file_age_secs(&f).unwrap();
        assert!(age < 5, "just-written file age should be < 5s, got {age}");
    }

    #[test]
    fn file_age_secs_missing_file_returns_io_err() {
        let result = file_age_secs(std::path::Path::new("/tmp/csm_nonexistent_xyz123.txt"));
        assert!(
            matches!(result, Err(FetchError::Io(_))),
            "missing file should return Io error"
        );
    }

    #[test]
    #[cfg(unix)]
    fn file_age_secs_aged_file_matches_expected() {
        let dir = TempDir::new().unwrap();
        let f = dir.path().join("old.txt");
        // Write the file dated 70 seconds ago.
        write_aged_file(&f, "data", 70);
        let age = file_age_secs(&f).unwrap();
        // Allow ±5s for any scheduling jitter.
        assert!(
            (65..=80).contains(&age),
            "file aged 70s should report age ≈ 70s, got {age}"
        );
    }
}