llmtrim 0.13.7

Static, deterministic LLM prompt/payload compressor — cut input tokens 30-90% with zero extra model calls
Documentation
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
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
//! `statusline` — one elegant line for Claude Code's custom status line.
//!
//! Claude Code pipes a JSON session blob on stdin and renders whatever the command
//! prints (see <https://code.claude.com/docs/en/statusline>). This module reads that
//! blob, folds in llmtrim's own live signals from the ledger + config (compression
//! saved, interceptor health, the active `sub` reroute), and prints a single
//! width-adaptive line:
//!
//! ```text
//! ◆ Opus→gpt-5.6-terra   ▓▓▓▓▓░░░ 142k   ✂ 6.8%   ◔ 3h·24% · 4d·12%   ♻ 63% cached
//! ```
//!
//! The three left segments (model→backend, context, ✂ trim) are core and never
//! truncate; the extras (5h/7d quota, then this turn's prompt-cache reuse) shed right-to-left
//! as the terminal narrows (`COLUMNS`). The context gauge fills and colours against the *real*
//! window of the model serving the turn — the rerouted backend's window under `sub`, not
//! Claude's — green below 40%, orange 40–65%, red above; and red whenever the prompt cache has
//! gone cold, where the cache segment becomes `♻ cache cold`. Segments whose data is
//! absent — no reroute, an API-key user with no rate limits — simply don't render.
//!
//! Under `sub`, the quota segment prefers the active provider's windows (cached under
//! `~/.llmtrim/sub-rate-limits.json` by the proxy when a Codex turn fires) over Claude Code's
//! Anthropic blob, but only once a matching snapshot exists and the proxy is healthy —
//! otherwise the Claude blob stays so a fresh always-mode session isn't blank for minutes.
//! Weekly is always shown when known; the short (~5h) window only appears when the provider
//! reports one. Kimi/Grok fill in later.
//!
//! Under `sub` the arrow shows the concrete model that served the last turn (e.g.
//! `→gpt-5.6-terra`) for Codex reroutes; Kimi shows the provider shortname (`→kimi`), since all
//! its tiers collapse to one internal wire id. The arrow is read from the ledger — what actually
//! answered — not from config, because in `fallback` mode config predicts nothing: Anthropic
//! serves the turn and the chain fires only if it fails. So there the arrow appears only on turns
//! a backend really served, and the gauge keeps Claude's window until one does.
//!
//! `install` wires it into `~/.claude/settings.json`; rendering itself never touches the
//! network or API tokens (the proxy polls usage on the request path; this process only reads
//! the resulting cache file).

use std::ffi::OsStr;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use serde_json::Value;

use crate::monitor::{self, DaemonView, Health};
use crate::tracking::Tracker;
use crate::ui;

/// Default context window (tokens) when neither the Claude Code blob nor the model registry
/// reports one — a conservative floor so the gauge still renders.
const CTX_WINDOW_DEFAULT: i64 = 200_000;
const CTX_BAR_WIDTH: usize = 8;
/// Fill fraction of the *real* window at which the gauge leaves green (< 40%) and enters red
/// (>= 65%); the band between is amber. Percent of the window, per the user's spec — a capacity
/// reading, not the fixed quality budget.
const CTX_GREEN_PCT: i64 = 40;
const CTX_AMBER_PCT: i64 = 65;
/// Prompt-cache TTL. Claude Code sends `cache_control: {ttl: "1h"}` on ~92% of breakpoints
/// (verified from the capture corpus: 3333×1h vs 288×5m), and the cache stays warm up to the
/// TTL since the last intercepted request. Past this idle gap the cache is cold, so a stale
/// "cached %" would lie about the next turn paying a cold write — show it cold instead.
/// Shared with [`crate::guard`], so the hook and the status line agree on when a cache is cold.
pub(crate) const CACHE_TTL_SECS: i64 = 3600;
/// How often Claude Code re-runs the status line while a session sits idle. Without it Claude
/// Code only re-renders on conversation events, so an abandoned session keeps the line drawn at
/// its last turn — green and warm — straight through the cache expiring, and `♻ cache cold`
/// only appears *after* the turn that pays for it. Rendering is local (no network, no tokens),
/// so a refresh costs one short process; 5 minutes is far finer than the 1h TTL it watches, and
/// 25× cheaper than polling every 10s would be.
const REFRESH_INTERVAL_SECS: i64 = 300;

// ── ANSI palette ────────────────────────────────────────────────────────────────
// The status line is captured by Claude Code (never a TTY), but Claude Code renders ANSI,
// so colour is emitted unconditionally — gated only by NO_COLOR, per the docs' examples.

const BRAND: &str = "38;2;153;204;255"; // llmtrim accent blue
const CYAN: &str = "36"; // codex
const VIOLET: &str = "38;2;181;137;255"; // kimi
const YELLOW: &str = "33"; // grok
const GREEN: &str = "32";
const AMBER: &str = "33";
const ORANGE: &str = "38;2;255;140;0"; // true orange, distinct from amber quota tiers
const RED: &str = "31";
const DIM: &str = "2";
const BOLD: &str = "1";

fn paint(color: bool, code: &str, s: &str) -> String {
    if color {
        format!("\x1b[{code}m{s}\x1b[0m")
    } else {
        s.to_string()
    }
}

// ── the Claude Code stdin blob (only the fields we render) ────────────────────────

struct CcInput {
    model: String,
    /// Claude Code's `effort.level`. Parsed but not currently rendered — the field doesn't track
    /// the `/model` effort override, so showing it is misleading (see [`model_segment`]). Kept so
    /// re-enabling is a one-liner once Claude Code fixes it.
    #[allow(dead_code)]
    effort: Option<String>,
    /// Claude Code's own session id (the `x-claude-code-session-id` it also tags on every
    /// intercepted request), used to scope trim to *this* session's ledger rows. `None` if
    /// absent — trim then falls back to the lifetime figure.
    session_id: Option<String>,
    /// Total input tokens currently in the context window (fresh + cache), from the last
    /// API response. `0` before the first response.
    ctx_tokens: i64,
    /// Claude Code's model id (`model.id`, e.g. `claude-opus-4-8[1m]`), used to resolve the real
    /// window under a `sub` reroute (where CC still reports its own Claude window, not the
    /// backend's).
    model_id: String,
    /// The model's context window in tokens, as Claude Code reports it (`context_window_size`).
    /// `None` when absent — the gauge then falls back to the registry or a default.
    window: Option<i64>,
    /// 5-hour and 7-day rate-limit usage %, Claude.ai subscribers only.
    five_hour_pct: Option<f64>,
    seven_day_pct: Option<f64>,
    /// Rate-limit window reset times (Unix epoch seconds, as Claude Code sends them), used to show
    /// the remaining duration beside each quota.
    five_hour_resets_at: Option<i64>,
    seven_day_resets_at: Option<i64>,
    /// Share of this turn's input served from the prompt cache, % — computed from the last
    /// API call's `current_usage`. `None` before the first response or right after `/compact`.
    cache_pct: Option<f64>,
}

fn parse_cc(input: &str) -> CcInput {
    let v: Value = serde_json::from_str(input).unwrap_or(Value::Null);
    let model = v
        .pointer("/model/display_name")
        .and_then(Value::as_str)
        .unwrap_or("?")
        .to_string();
    let model_id = v
        .pointer("/model/id")
        .and_then(Value::as_str)
        .unwrap_or("")
        .to_string();
    let effort = v
        .pointer("/effort/level")
        .and_then(Value::as_str)
        .map(str::to_string);
    let session_id = v
        .pointer("/session_id")
        .and_then(Value::as_str)
        .filter(|s| !s.is_empty())
        .map(str::to_string);
    let ctx_tokens = v
        .pointer("/context_window/total_input_tokens")
        .and_then(Value::as_i64)
        .unwrap_or(0);
    let window = v
        .pointer("/context_window/context_window_size")
        .and_then(Value::as_i64)
        .filter(|&w| w > 0);
    let five_hour_pct = v
        .pointer("/rate_limits/five_hour/used_percentage")
        .and_then(Value::as_f64);
    let seven_day_pct = v
        .pointer("/rate_limits/seven_day/used_percentage")
        .and_then(Value::as_f64);
    let five_hour_resets_at = v
        .pointer("/rate_limits/five_hour/resets_at")
        .and_then(Value::as_i64);
    let seven_day_resets_at = v
        .pointer("/rate_limits/seven_day/resets_at")
        .and_then(Value::as_i64);
    let cache_pct = {
        let cu = v.pointer("/context_window/current_usage");
        let field = |k: &str| {
            cu.and_then(|c| c.get(k))
                .and_then(Value::as_i64)
                .unwrap_or(0)
        };
        let read = field("cache_read_input_tokens");
        let total = read + field("input_tokens") + field("cache_creation_input_tokens");
        (total > 0).then(|| read as f64 / total as f64 * 100.0)
    };
    CcInput {
        model,
        effort,
        session_id,
        model_id,
        ctx_tokens,
        window,
        five_hour_pct,
        seven_day_pct,
        five_hour_resets_at,
        seven_day_resets_at,
        cache_pct,
    }
}

// ── llmtrim's own signals, read from the ledger + config ──────────────────────────

struct Led {
    health: Health,
    /// Input compression saved, % of input tokens — scoped to this Claude Code session when
    /// its id is known, else lifetime. `None` when there are no rows to measure yet (a fresh
    /// session), which renders an idle `✂ –` rather than a misleading `✂ 0.0%`.
    trim_pct: Option<f64>,
    /// Active reroute provider (`codex`/`kimi`), if `sub` is on.
    reroute: Option<String>,
    /// The real window (tokens) of the model actually serving the turn, when a `sub` reroute is
    /// active — looked up from the model registry, since Claude Code reports its own Claude
    /// window on the wire, not the backend's. `None` when not rerouted (use the blob's window).
    reroute_window: Option<i64>,
    /// The concrete upstream model id resolved for a `sub` reroute (e.g. "gpt-5.6-terra" for a
    /// Codex Opus tier), rendered after the arrow so the status line shows the *real* model
    /// serving the turn. `None` when not rerouted, or on Kimi (all tiers collapse to one wire
    /// id) — the arrow then falls back to the provider shortname.
    resolved_model: Option<String>,
    /// The prompt cache has gone cold: the session has been idle past the TTL, so the next turn
    /// pays a cold write. Renders the cache segment red with a `/compact` nudge.
    cache_cold: bool,
    /// Cache-hit rate of this session's last *completed* turn, %, as the proxy measured it on the
    /// wire. Stands in for the blob's `current_usage` while a turn is in flight — see
    /// [`cache_pct_for`].
    last_cache_pct: Option<f64>,
    /// Input tokens of that same turn — stands in for the blob's `total_input_tokens` while a
    /// turn is in flight, so the gauge doesn't empty. See [`ctx_tokens_for`].
    last_ctx_tokens: i64,
    /// Under `sub`, the active provider's rate-limit windows from
    /// `~/.llmtrim/sub-rate-limits.json` (populated by the proxy). `(label, used_percent)` for the
    /// short (~5h) window and the weekly window; either may be `None`. When the proxy is healthy
    /// and at least one is present these replace Claude Code's Anthropic blob; otherwise the
    /// blob is used (predicted always-mode before the first poll, or a degraded/stopped proxy).
    sub_five: Option<QuotaSlot>,
    sub_seven: Option<QuotaSlot>,
}

/// One rate-limit window ready for the status line: display label + used %.
type QuotaSlot = (String, f64);

/// Minimal [`DaemonView`] for the health check — mirrors `main::daemon_view` but fills only
/// the fields [`monitor::health`] reads (running/pid/port/port_accepting/env_port/ca), since
/// the status line needs the health verdict, not the full dashboard header.
fn proxy_health() -> Health {
    use crate::daemon;
    let ca_present = matches!(crate::serve::ca_cert_path(), Ok(p) if p.exists());
    let env_port = crate::setup::configured_port();
    let view = |running: bool, pid: u32, port: u16, accepting: bool| DaemonView {
        running,
        pid,
        port,
        uptime: String::new(),
        uptime_secs: 0,
        ca_present,
        port_accepting: accepting,
        env_port,
        autostart: false,
        restarts: 0,
        version: None,
        binary_version: String::new(),
        log_path: None,
        last_request: None,
    };
    let dv = match daemon::running() {
        Some(s) => view(true, s.pid, s.port, daemon::probe_port(s.port)),
        // No pidfile: trust a live probe on the wired port before declaring stopped.
        None => match env_port.filter(|&p| daemon::probe_port(p)) {
            Some(p) => view(true, 0, p, true),
            None => view(false, 0, 0, false),
        },
    };
    monitor::health(&dv)
}

fn ledger_snapshot(cc: &CcInput) -> Led {
    let cfg = llmtrim_core::config::RuntimeConfig::get();
    let global = cfg.sub.clone().filter(|s| !s.is_empty() && s != "off");
    let window_intent = crate::window_sub::lookup(cc.session_id.as_deref());
    let configured = match &window_intent {
        Some(crate::window_sub::Intent::Enabled { provider }) => Some(provider.clone()),
        Some(crate::window_sub::Intent::Disabled) => None,
        None => global,
    };
    let health = proxy_health();

    // One session-row read serves both trim and cache-cold. Match on `cc_session_id` — the real
    // Claude Code session id the proxy now records — not the ledger's `session_id`, which is a
    // hash of the system prompt and never equals Claude Code's UUID. The per-session ledger view
    // lives behind the `breakdown` feature; without it we scope nothing and fall back to lifetime.
    let row = cc.session_id.as_deref().and_then(session_row);
    // Lifetime figure, read only when we have no session to scope to.
    let lifetime = || {
        Tracker::open()
            .and_then(|t| t.summary())
            .ok()
            .filter(|s| s.input_before > 0)
            .map(|s| ui::saved_pct(s.input_before as f64, s.input_after as f64))
    };
    let session_savings = row.as_ref().map(|r| (r.input_before, r.input_after));
    let trim_pct = trim_for(cc.session_id.as_deref(), session_savings, lifetime);
    let ledger_cold = row.as_ref().is_some_and(|r| cache_cold(&r.last_ts));
    let cache_cold = effective_cache_cold(cc, ledger_cold);

    let arrow = if matches!(window_intent, Some(crate::window_sub::Intent::Disabled)) {
        ArrowSource::None
    } else {
        // A window `/sub on <provider>` always reroutes that window (see serve.rs), even when the
        // global policy is `fallback`. Treat it as always-mode for the arrow so the status line
        // shows `→grok` as soon as the user flips the override — not only after a sub turn lands.
        let window_forces = matches!(
            window_intent,
            Some(crate::window_sub::Intent::Enabled { .. })
        );
        let effective_fallback = cfg.sub_fallback && !window_forces;
        arrow_source(configured.as_deref(), effective_fallback, row.as_ref())
    };
    let (reroute, reroute_window, resolved_model) = match arrow {
        // Truth: the backend that answered the last turn, and the model recorded on it.
        ArrowSource::Served { provider, model } => {
            let window = model.as_deref().and_then(upstream_window);
            // Kimi collapses every tier to one internal wire id, which tells the user nothing
            // the provider shortname doesn't — so the arrow keeps the shortname there.
            let shown = model.filter(|_| provider != "kimi");
            (Some(provider), window, shown)
        }
        // Prediction (always mode, no turn yet / policy switch): resolve from *this* provider's
        // tier table, not the global active one (window `/sub on grok` while global is codex).
        ArrowSource::Predicted(provider) => {
            let tiers = llmtrim_core::config::sub_tiers_for(&provider);
            (
                Some(provider.clone()),
                reroute_real_window(&provider, &cc.model_id, &tiers),
                reroute_resolved_model(&provider, &cc.model_id, &tiers),
            )
        }
        ArrowSource::None => (None, None, None),
    };

    let (sub_five, sub_seven) = sub_quota_for(reroute.as_deref());

    Led {
        health,
        trim_pct,
        reroute,
        reroute_window,
        resolved_model,
        cache_cold,
        last_cache_pct: row
            .as_ref()
            .and_then(|r| r.last_cache_hit)
            .map(|f| f * 100.0),
        last_ctx_tokens: row.as_ref().map_or(0, |r| r.last_input_tokens),
        sub_five,
        sub_seven,
    }
}

/// Load the provider quota snapshot the proxy cached for the status line, if it matches the
/// active reroute. Returns `(short_window, weekly_window)` as `(label, used_percent)`.
#[cfg(feature = "intercept")]
fn sub_quota_for(reroute: Option<&str>) -> (Option<QuotaSlot>, Option<QuotaSlot>) {
    let Some(provider) = reroute else {
        return (None, None);
    };
    let Some(snap) = crate::reroute::quota::load_fresh() else {
        return (None, None);
    };
    if snap.provider != provider {
        return (None, None);
    }
    let (short, weekly) = crate::reroute::quota::split_short_weekly(&snap);
    let label = |w: &crate::reroute::quota::RateWindow, fallback: &str| {
        remaining_time_label(w.resets_at).unwrap_or_else(|| {
            let s = crate::reroute::quota::size_label(w.limit_window_seconds);
            if s == "?" { fallback.to_string() } else { s }
        })
    };
    (
        short.map(|w| (label(w, "5h"), w.used_percent)),
        weekly.map(|w| (label(w, "7d"), w.used_percent)),
    )
}

#[cfg(not(feature = "intercept"))]
fn sub_quota_for(_reroute: Option<&str>) -> (Option<QuotaSlot>, Option<QuotaSlot>) {
    (None, None)
}

/// Resolve the context occupancy the gauge fills against. Claude Code reports
/// `total_input_tokens` from the *last response*, so like `current_usage` it reads 0 on every
/// re-render while a turn is in flight — emptying the bar mid-request and refilling it after.
/// The proxy counted the same input on the wire, so the last completed turn holds the gauge
/// steady. A genuinely empty context (fresh session, no turn yet) has no ledger row either, so
/// it still renders empty rather than inventing a fill.
fn ctx_tokens_for(blob: i64, ledger_last: i64) -> i64 {
    if blob > 0 { blob } else { ledger_last }
}

/// Resolve the cache figure the segment shows. Claude Code fills `current_usage` only once a
/// response's usage has landed, so it is absent from every re-render *during* a turn — trusting
/// it alone drops the segment mid-request and pops it back afterwards. The proxy measured the
/// same quantity on the wire for the last completed turn, so it holds the number steady across
/// the gap instead of blanking it.
fn cache_pct_for(blob: Option<f64>, ledger_last: Option<f64>) -> Option<f64> {
    blob.or(ledger_last)
}

/// Where the reroute arrow's content comes from.
enum ArrowSource {
    /// The ledger recorded this backend serving the session's last turn. Ground truth.
    Served {
        provider: String,
        model: Option<String>,
    },
    /// No turn recorded yet, but `always` mode reroutes every turn — so config predicts it.
    Predicted(String),
    /// Anthropic is serving (or nothing is configured): no arrow.
    None,
}

/// Decide what the reroute arrow may claim.
///
/// - When the ledger recorded a *subscription* backend on the last turn, that is ground truth
///   (`Served`) — unless the operator has since switched the policy to a different provider
///   (window `/sub on grok` after a codex turn), in which case we predict the new target so the
///   line doesn't keep advertising a backend that will no longer answer.
/// - When the last turn was Anthropic (`last_sub_provider` absent) or there is no row yet, config
///   predicts in non-fallback mode: every future turn will reroute, so showing `→grok` after
///   `/sub on grok` mid-session is correct even if earlier turns were Anthropic.
/// - In pure `fallback` mode config predicts nothing: the chain fires only when Anthropic fails,
///   and claiming a reroute on healthy turns would be a lie (and would rescale the gauge).
fn arrow_source(
    configured: Option<&str>,
    fallback_mode: bool,
    row: Option<&SessionLedgerRow>,
) -> ArrowSource {
    let predict = |p: &str| ArrowSource::Predicted(p.to_string());
    match row {
        Some(r) => match &r.last_sub_provider {
            Some(provider) => {
                // Policy switched under us (window override / global sub change): prefer the new
                // target until a turn from that backend overwrites the ledger.
                if let Some(p) = configured
                    && !fallback_mode
                    && p != provider.as_str()
                {
                    return predict(p);
                }
                ArrowSource::Served {
                    provider: provider.clone(),
                    model: r.last_model.clone(),
                }
            }
            // Last turn was Anthropic. Still predict when policy says every turn will reroute
            // (always mode or a window `/sub on` override treated as always).
            None => match configured {
                Some(p) if !fallback_mode => predict(p),
                _ => ArrowSource::None,
            },
        },
        None => match configured {
            Some(p) if !fallback_mode => predict(p),
            _ => ArrowSource::None,
        },
    }
}

/// The ledger fields the status line needs from a session's row: its summed savings and the
/// timestamp of its last turn (for the cold-cache check).
struct SessionLedgerRow {
    input_before: i64,
    input_after: i64,
    last_ts: String,
    /// The `sub` backend that served this session's most recent turn, and that turn's model id.
    /// The ground truth behind the reroute arrow: in fallback mode a reroute happens only when
    /// Anthropic actually failed, which config cannot predict.
    last_sub_provider: Option<String>,
    last_model: Option<String>,
    /// Cache-hit fraction of this session's most recent *completed* turn. Claude Code omits
    /// `current_usage` from the blob while a turn is in flight, so this is what keeps the cache
    /// segment from blanking out mid-request.
    last_cache_hit: Option<f64>,
    /// Input tokens of that same turn — what the context gauge falls back to when the blob
    /// reports no occupancy mid-request.
    last_input_tokens: i64,
}

/// This Claude Code session's aggregated ledger row, matched on the real `cc_session_id`. Behind
/// the `breakdown` feature (the per-session query lives there); `None` without it, so trim falls
/// back to lifetime and cold-cache is never flagged.
#[cfg(feature = "breakdown")]
fn session_row(sid: &str) -> Option<SessionLedgerRow> {
    crate::breakdown::db::BreakdownDb::open()
        .ok()
        .and_then(|db| db.sessions().ok())
        .and_then(|rows| {
            rows.into_iter()
                .find(|r| r.cc_session_id.as_deref() == Some(sid))
        })
        .map(|r| SessionLedgerRow {
            input_before: r.input_before,
            input_after: r.input_after,
            last_ts: r.last_ts,
            last_sub_provider: r.last_sub_provider,
            last_model: r.last_model,
            last_cache_hit: r.last_cache_hit,
            last_input_tokens: r.last_input_tokens,
        })
}

#[cfg(not(feature = "breakdown"))]
fn session_row(_sid: &str) -> Option<SessionLedgerRow> {
    None
}

/// The concrete model a `sub` backend served this session's last turn with, if any — the only
/// thing [`crate::guard`] takes from the ledger, and only to price a rerouted turn correctly.
/// `None` (no row, no reroute, or no `breakdown` feature) never changes the guard's decision.
pub(crate) fn session_sub_model(session_id: &str) -> Option<String> {
    let row = session_row(session_id)?;
    row.last_sub_provider.as_ref()?;
    row.last_model
}

/// Whether this session's prompt cache is *known* to still be warm: a recorded turn whose
/// `last_ts` is within the TTL. Used to suppress the `/compact` model redirect, which only pays
/// off once the original model's cache has gone cold — a warm cache-read (`0.1×`) on the original
/// model beats a cold read/write on a cheaper redirect target. Fails safe: an unknown cache (no
/// session row, an unparseable timestamp, or a build without the `breakdown` feature) returns
/// `false`, so the redirect proceeds exactly as before — only a *proven* warm cache suppresses it.
/// Only the proxy (`intercept`) consults this, to gate the `/compact` redirect.
#[cfg(feature = "intercept")]
pub(crate) fn session_cache_warm(session_id: &str) -> bool {
    session_row(session_id).is_some_and(|r| ts_within_ttl(&r.last_ts))
}

/// Whether an rfc3339 timestamp is newer than the cache TTL. The strict complement of
/// [`cache_cold`]'s test, but note the *opposite* fail-safe on a bad timestamp: `cache_cold`
/// treats unparseable as not-cold (don't warn on a glitch), whereas here unparseable is not-*warm*
/// — the two gate opposite actions, and both must fail toward "act as if the cache is cold".
#[cfg(feature = "intercept")]
fn ts_within_ttl(last_ts: &str) -> bool {
    chrono::DateTime::parse_from_rfc3339(last_ts)
        .map(|t| chrono::Utc::now().signed_duration_since(t).num_seconds() < CACHE_TTL_SECS)
        .unwrap_or(false)
}

/// Decide the trim figure: this session's own savings when we have its row; idle (`None`) for a
/// known Claude Code session with no recorded turn yet — *not* the lifetime figure, which would
/// flash a misleading number for a beat before the first turn lands; and only the lifetime figure
/// (via `lifetime`) when there is no session id to scope to at all.
fn trim_for(
    session_id: Option<&str>,
    session_savings: Option<(i64, i64)>,
    lifetime: impl FnOnce() -> Option<f64>,
) -> Option<f64> {
    match (session_savings, session_id) {
        (Some((before, after)), _) => {
            (before > 0).then(|| ui::saved_pct(before as f64, after as f64))
        }
        (None, Some(_)) => None,
        (None, None) => lifetime(),
    }
}

/// The real context window of the model a `sub` reroute actually serves this turn, from the
/// model registry. Claude Code reports its own Claude window on the wire, so under reroute we
/// must resolve the backend model id and look *it* up. `None` if unknown (gauge keeps the blob
/// window). Kimi's internal id isn't a registry key, so it's mapped to its public model id.
///
/// Reroute resolution lives behind the `intercept` feature; without it a `sub` reroute can't be
/// active anyway, so the gauge just uses the blob's window.
#[cfg(feature = "intercept")]
fn reroute_real_window(
    provider: &str,
    incoming_model_id: &str,
    tiers: &std::collections::BTreeMap<String, String>,
) -> Option<i64> {
    use crate::reroute::SubProvider;
    let sp = match provider {
        "codex" => SubProvider::Codex,
        "kimi" => SubProvider::Kimi,
        "grok" => SubProvider::Grok,
        "on" | "cliproxy" | "cli-proxy-api" => {
            return upstream_window(incoming_model_id);
        }
        _ => return None,
    };
    upstream_window(&crate::reroute::resolve_model(sp, incoming_model_id, tiers))
}

/// Registry window of a concrete upstream model id. `kimi-for-coding` is an internal routing id,
/// not a models.dev key — map it to the public one.
#[cfg(feature = "intercept")]
fn upstream_window(model: &str) -> Option<i64> {
    let lookup = if model == crate::reroute::KIMI_MODEL {
        "moonshotai/kimi-k2"
    } else {
        model
    };
    llmtrim_core::context_window(lookup).map(|w| w as i64)
}

#[cfg(not(feature = "intercept"))]
fn upstream_window(_model: &str) -> Option<i64> {
    None
}

#[cfg(not(feature = "intercept"))]
fn reroute_real_window(
    _provider: &str,
    _incoming_model_id: &str,
    _tiers: &std::collections::BTreeMap<String, String>,
) -> Option<i64> {
    None
}

/// Parallel to [`reroute_real_window`]: returns the concrete upstream model id (e.g.
/// "gpt-5.6-terra" / "grok-4.6") chosen by tier mapping for the status line. `None` for Kimi,
/// whose tiers all collapse to one internal wire id: the shortname is what a reader wants there.
#[cfg(feature = "intercept")]
fn reroute_resolved_model(
    provider: &str,
    incoming_model_id: &str,
    tiers: &std::collections::BTreeMap<String, String>,
) -> Option<String> {
    use crate::reroute::SubProvider;
    let sp = match provider {
        "codex" => SubProvider::Codex,
        "grok" => SubProvider::Grok,
        _ => return None,
    };
    Some(crate::reroute::resolve_model(sp, incoming_model_id, tiers))
}

#[cfg(not(feature = "intercept"))]
fn reroute_resolved_model(
    _provider: &str,
    _incoming_model_id: &str,
    _tiers: &std::collections::BTreeMap<String, String>,
) -> Option<String> {
    None
}

/// Whether the prompt cache has gone cold: `last_ts` (rfc3339, the most recent intercepted
/// request) is older than the TTL. An unparseable timestamp is treated as not-cold (don't warn
/// on a data glitch).
fn cache_cold(last_ts: &str) -> bool {
    chrono::DateTime::parse_from_rfc3339(last_ts)
        .map(|t| chrono::Utc::now().signed_duration_since(t).num_seconds() >= CACHE_TTL_SECS)
        .unwrap_or(false)
}

/// Fold ledger idle time with Claude Code's live context. `/compact` and other internal turns
/// can refresh the prompt cache without updating the interceptor's `last_ts`, so a stale ledger
/// alone would keep the gauge red after the user already compacted.
fn effective_cache_cold(cc: &CcInput, ledger_cold: bool) -> bool {
    if !ledger_cold {
        return false;
    }
    // Post-compact reset: empty window, no `current_usage` yet. Do not also key off
    // `cache_creation_tokens` from the last response — that field is stale once the TTL
    // expires and would hide a legitimate cold warning on an idle session.
    cc.ctx_tokens != 0 || cc.cache_pct.is_some()
}

// ── rendering ─────────────────────────────────────────────────────────────────────

/// Colour a rate-limit % with an extra orange step before red: green < 70, amber 70–80,
/// orange 80–90, red ≥ 90 — so a filling quota escalates in visible stages, not one jump to red.
fn quota_color(pct: f64) -> &'static str {
    if pct >= 90.0 {
        RED
    } else if pct >= 80.0 {
        ORANGE
    } else if pct >= 70.0 {
        AMBER
    } else {
        GREEN
    }
}

/// The largest useful unit left before a quota window resets. `resets_at` is Unix epoch seconds,
/// the shape Claude Code actually sends (`"resets_at": 1738425600`).
fn remaining_time_label(resets_at: Option<i64>) -> Option<String> {
    let minutes = (resets_at? - chrono::Utc::now().timestamp()).max(0) / 60;
    Some(if minutes >= 24 * 60 {
        format!("{}d", minutes / (24 * 60))
    } else if minutes >= 60 {
        format!("{}h", minutes / 60)
    } else {
        format!("{minutes}m")
    })
}

/// `◆ Opus→gpt-5.6-terra` — health-brand glyph, model (Claude tier name), reroute target.
/// The target is the resolved upstream model for Codex reroutes (so you see the real model
/// serving the turn) or the provider shortname for Kimi. The arrow is suppressed when the
/// proxy isn't healthy (traffic isn't being intercepted, so it isn't actually rerouting).
///
/// Effort is intentionally not shown: Claude Code's `effort.level` field doesn't track the
/// `/model` effort override (it reports a stale/base level), so rendering it is misleading. The
/// field is still parsed — re-append `·{effort}` here once Claude Code fixes the field.
fn model_segment(cc: &CcInput, led: &Led, color: bool) -> String {
    let mut s = format!(
        "{} {}",
        paint(color, BRAND, "◆"),
        paint(color, BOLD, &cc.model)
    );
    if let (Health::Healthy, Some(p)) = (led.health, &led.reroute) {
        let code = match p.as_str() {
            "kimi" => VIOLET,
            "grok" => YELLOW,
            _ => CYAN,
        };
        let tail = led.resolved_model.clone().unwrap_or_else(|| p.clone());
        s.push_str(&paint(color, code, &format!("→{tail}")));
    }
    s
}

/// The real context window in play: the model actually serving the turn. Under a `sub` reroute
/// that's the backend model's window (from the registry); otherwise Claude Code's reported
/// `context_window_size`; falling back to a default when neither is known.
fn effective_window(cc: &CcInput, led: &Led) -> i64 {
    led.reroute_window
        .or(cc.window)
        .filter(|&w| w > 0)
        .unwrap_or(CTX_WINDOW_DEFAULT)
}

/// `▓▓▓▓▓░░░ 142k` — gauge filled and coloured against the *real* window: green below 40% of the
/// window, orange 40–65%, red at/above 65% — and red unconditionally when the prompt cache has
/// gone cold (idle past the TTL), since the next turn then pays a cold write regardless of fill.
/// Label is absolute k.
fn context_segment(ctx_tokens: i64, window: i64, cache_cold: bool, color: bool) -> String {
    let tokens = ctx_tokens.max(0);
    let window = window.max(1);
    // Clamp before multiplying so a pathological token count can't overflow (bar pins full anyway).
    let filled = (tokens.min(window) * CTX_BAR_WIDTH as i64 / window) as usize;
    let bar: String = "▓".repeat(filled) + &"░".repeat(CTX_BAR_WIDTH - filled);
    let k = (tokens as f64 / 1000.0).round() as i64;
    // Ratio in f64 so a pathologically large token count can't overflow the multiply.
    let pct = (tokens as f64 / window as f64 * 100.0) as i64;
    let code = if cache_cold {
        RED
    } else if tokens == 0 {
        DIM
    } else if pct >= CTX_AMBER_PCT {
        RED
    } else if pct >= CTX_GREEN_PCT {
        ORANGE
    } else {
        GREEN
    };
    paint(color, code, &format!("{bar} {k}k"))
}

/// The third core segment: `✂ 6.8%` when healthy and this session has saved something, a dim
/// `✂ –` when healthy but idle (nothing trimmed yet — avoids a misleading `✂ 0.0%` while still
/// signalling "llmtrim is on"), `⚠ llmtrim degraded` when broken, and nothing at all when
/// cleanly stopped (llmtrim is simply off — not an error to flag).
fn trim_or_health_segment(led: &Led, color: bool) -> Option<String> {
    match led.health {
        // Trim is a savings figure, not a tier — no "bad" value to warn on — so it stays dim;
        // colour is reserved for state signals (health, quota, context, cold cache).
        Health::Healthy => Some(match led.trim_pct {
            Some(pct) => paint(color, DIM, &format!("✂ {pct:.1}%")),
            None => paint(color, DIM, "✂ –"),
        }),
        Health::Degraded => Some(paint(color, RED, "⚠ llmtrim degraded")),
        Health::Stopped => None,
    }
}

/// Resolve which rate-limit windows to render.
///
/// Prefer the provider snapshot the proxy cached into `Led` (Codex today) only when the
/// proxy is healthy *and* we actually have a matching snapshot. Otherwise fall back to
/// Claude Code's 5h/7d blob:
/// - predicted always-mode before the first poll would otherwise blank the segment for
///   minutes on a fresh login;
/// - a degraded/stopped proxy is not actually rerouting, so Anthropic's numbers are the
///   ones that will matter on the next turn (and the arrow is already hidden).
fn quota_windows(cc: &CcInput, led: &Led) -> (Option<QuotaSlot>, Option<QuotaSlot>) {
    if led.health == Health::Healthy
        && led.reroute.is_some()
        && (led.sub_five.is_some() || led.sub_seven.is_some())
    {
        return (led.sub_five.clone(), led.sub_seven.clone());
    }
    let five = cc.five_hour_pct.map(|p| {
        (
            remaining_time_label(cc.five_hour_resets_at).unwrap_or_else(|| "5h".to_string()),
            p,
        )
    });
    let seven = cc.seven_day_pct.map(|p| {
        (
            remaining_time_label(cc.seven_day_resets_at).unwrap_or_else(|| "7d".to_string()),
            p,
        )
    });
    (five, seven)
}

/// Build the ordered extra segments (quota, then this session's cache); later ones drop first on
/// a narrow terminal.
fn extra_segments(cc: &CcInput, led: &Led, color: bool) -> Vec<String> {
    let mut out = Vec::new();
    // One quota segment carrying both rolling windows, labelled by the time remaining until
    // each reset: `◔ 3h·15% · 4d·12%`. Only the *percentage* is coloured on its own value
    // (a maxed 5h doesn't paint a comfortable 7d); the time labels stay dim.
    let quota = |label: &str, p: f64| {
        format!(
            "{}{}",
            paint(color, DIM, &format!("{label}·")),
            paint(color, quota_color(p), &format!("{}%", p.floor() as i64))
        )
    };
    let glyph = paint(color, DIM, "◔");
    let sep = paint(color, DIM, "·");
    match quota_windows(cc, led) {
        (Some((five_label, h)), Some((seven_label, d))) => {
            out.push(format!(
                "{glyph} {} {sep} {}",
                quota(&five_label, h),
                quota(&seven_label, d)
            ));
        }
        (Some((five_label, h)), None) => out.push(format!("{glyph} {}", quota(&five_label, h))),
        (None, Some((seven_label, d))) => out.push(format!("{glyph} {}", quota(&seven_label, d))),
        (None, None) => {}
    }
    if led.cache_cold {
        // Cache expired: the next turn pays a cold write. State only, no `/compact` nudge —
        // compacting re-reads the same cold context to summarise it, so it pays that charge too
        // rather than avoiding it (see `crate::guard::message`).
        out.push(paint(color, RED, "♻ cache cold"));
    } else if let Some(c) = cache_pct_for(cc.cache_pct, led.last_cache_pct) {
        // Floor, not round: only a genuine 100% cache shows `100%` (99.9 stays `99%`).
        out.push(paint(
            color,
            DIM,
            &format!("♻ {}% cached", c.floor() as i64),
        ));
    }
    out
}

const SEP: &str = "   ";

/// Assemble the line: core segments always in, extras appended left-to-right only while they
/// fit `cols` (0 = unknown width ⇒ no truncation). Once one extra overflows, stop — keeping
/// the higher-priority leftmost extras.
fn render_line(cc: &CcInput, led: &Led, cols: usize, color: bool) -> String {
    let mut core = vec![
        model_segment(cc, led, color),
        context_segment(
            ctx_tokens_for(cc.ctx_tokens, led.last_ctx_tokens),
            effective_window(cc, led),
            led.cache_cold,
            color,
        ),
    ];
    if let Some(seg) = trim_or_health_segment(led, color) {
        core.push(seg);
    }
    let mut line = core.join(SEP);

    for extra in extra_segments(cc, led, color) {
        let candidate = format!("{line}{SEP}{extra}");
        if cols == 0 || ui::visible_width(&candidate) <= cols {
            line = candidate;
        } else {
            break;
        }
    }
    line
}

/// Render the status line from a Claude Code JSON blob (stdin). Pure apart from the ledger
/// read, so tests drive `render_line` directly.
pub fn run() -> Result<()> {
    use std::io::Read;
    let mut input = String::new();
    std::io::stdin().read_to_string(&mut input).ok();

    let cc = parse_cc(&input);
    let led = ledger_snapshot(&cc);
    let cols = std::env::var("COLUMNS")
        .ok()
        .and_then(|s| s.parse::<usize>().ok())
        .unwrap_or(0);
    let color = std::env::var_os("NO_COLOR").is_none();

    println!("{}", render_line(&cc, &led, cols, color));
    Ok(())
}

// ── install / uninstall (wire ~/.claude/settings.json) ────────────────────────────

/// Whether Claude Code appears to be installed (its `~/.claude` config dir exists). Used by
/// `ensure` to decide whether to wire `/sub` (and to refresh a previously owned status line).
pub fn claude_code_present() -> bool {
    claude_settings_path()
        .ok()
        .and_then(|p| p.parent().map(std::path::Path::is_dir))
        .unwrap_or(false)
}

/// Claude Code settings.json — honors `CLAUDE_CONFIG_DIR`, else `~/.claude`.
pub(crate) fn claude_settings_path() -> Result<PathBuf> {
    if let Some(dir) = std::env::var_os("CLAUDE_CONFIG_DIR") {
        return Ok(PathBuf::from(dir).join("settings.json"));
    }
    let home = std::env::var("HOME")
        .or_else(|_| std::env::var("USERPROFILE"))
        .context("neither HOME nor USERPROFILE is set")?;
    Ok(PathBuf::from(home).join(".claude").join("settings.json"))
}

/// Shell-safe single-quoted path for hook/statusline command strings (POSIX; Windows uses doubles).
pub(crate) fn shell_quote_path(path: &str) -> String {
    #[cfg(windows)]
    {
        format!("\"{}\"", path.replace('"', "\\\""))
    }
    #[cfg(not(windows))]
    {
        // POSIX: single-quote and break/reopen for embedded quotes.
        format!("'{}'", path.replace('\'', "'\"'\"'"))
    }
}

/// Absolute or stable PATH path to this llmtrim binary (no subcommand).
pub fn stable_exe_string() -> String {
    std::env::current_exe()
        .ok()
        .filter(|p| p.exists())
        .map(|p| stable_executable_path(&p, std::env::var_os("PATH").as_deref()))
        .map(|p| p.display().to_string())
        .unwrap_or_else(|| "llmtrim".to_string())
}

/// Atomically write pretty JSON (temp in same dir + rename).
pub(crate) fn atomic_write_json(path: &Path, value: &Value) -> Result<()> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("failed to create {}", parent.display()))?;
    }
    let tmp = path.with_extension("json.tmp");
    std::fs::write(&tmp, serde_json::to_string_pretty(value)?)
        .with_context(|| format!("failed to write {}", tmp.display()))?;
    std::fs::rename(&tmp, path)
        .with_context(|| format!("failed to rename onto {}", path.display()))?;
    Ok(())
}

/// Return a stable PATH alias for `current_exe` when one resolves to the same binary.
///
/// Package managers such as Homebrew launch versioned binaries from a `Cellar` path while
/// exposing a stable symlink in `PATH`. Persisting the versioned path makes Claude Code's
/// statusline break after an upgrade. We keep the absolute-command behavior, but prefer that
/// stable alias when it is provably the same executable. If no alias is available, the caller
/// retains the existing absolute-path fallback.
fn stable_executable_path(current_exe: &Path, path: Option<&OsStr>) -> PathBuf {
    let Some(current_real) = std::fs::canonicalize(current_exe).ok() else {
        return current_exe.to_path_buf();
    };
    let Some(name) = current_exe.file_name() else {
        return current_exe.to_path_buf();
    };
    let Some(path) = path else {
        return current_exe.to_path_buf();
    };

    for dir in std::env::split_paths(path) {
        if !dir.is_absolute() {
            continue;
        }
        let candidate = dir.join(name);
        if candidate == current_exe {
            continue;
        }
        if std::fs::canonicalize(&candidate).ok().as_ref() == Some(&current_real) {
            return candidate;
        }
    }

    current_exe.to_path_buf()
}

/// The command string Claude Code should run for one of our subcommands: an absolute path or a
/// stable PATH alias, so it survives a package manager replacing a versioned executable. Shared
/// with [`crate::guard`], which writes a hook command the same way.
pub(crate) fn exe_command(subcommand: &str) -> String {
    format!("{} {subcommand}", shell_quote_path(&stable_exe_string()))
}

/// The `statusLine` object we write.
fn statusline_config() -> Value {
    serde_json::json!({
        "type": "command",
        "command": exe_command("statusline"),
        "padding": 0,
        "refreshInterval": REFRESH_INTERVAL_SECS,
    })
}

/// Whether a Claude statusline command is one that `llmtrim statusline install` created.
fn is_llmtrim_statusline_command(command: &str) -> bool {
    is_llmtrim_command(command, "statusline")
}

/// Whether `command` is the llmtrim binary invoked with exactly `subcommand`. Recognize both
/// POSIX and Windows separators because settings can be moved between systems.
pub(crate) fn is_llmtrim_command(command: &str, subcommand: &str) -> bool {
    let Some(executable) = command.strip_suffix(&format!(" {subcommand}")) else {
        return false;
    };
    let executable = unquote_path_token(executable.trim());
    let name = executable.rsplit(['/', '\\']).next().unwrap_or(executable);
    name.strip_suffix(".exe").unwrap_or(name) == "llmtrim"
}

/// Strip one layer of shell quotes from a path token (double or single).
pub(crate) fn unquote_path_token(s: &str) -> &str {
    let s = s.trim();
    if s.len() >= 2 && s.starts_with('"') && s.ends_with('"') {
        return &s[1..s.len() - 1];
    }
    if s.len() >= 2 && s.starts_with('\'') && s.ends_with('\'') {
        return &s[1..s.len() - 1];
    }
    s
}

/// Set our `statusLine` key on a parsed settings object, preserving every other key. Pure
/// transform (no I/O) so [`install`]'s merge is unit-testable.
fn set_statusline(settings: &mut Value, path: &std::path::Path) -> Result<()> {
    let obj = settings
        .as_object_mut()
        .with_context(|| format!("{} is not a JSON object", path.display()))?;
    obj.insert("statusLine".to_string(), statusline_config());
    Ok(())
}

/// Remove our `statusLine` key, returning whether one was present. Pure transform.
fn clear_statusline(settings: &mut Value, path: &std::path::Path) -> Result<bool> {
    let obj = settings
        .as_object_mut()
        .with_context(|| format!("{} is not a JSON object", path.display()))?;
    Ok(obj.remove("statusLine").is_some())
}

/// Wire the status line into `~/.claude/settings.json` (merging, not clobbering). `print`
/// just emits the settings snippet instead of editing the file.
pub fn install(print: bool) -> Result<()> {
    if print {
        let snippet = serde_json::json!({ "statusLine": statusline_config() });
        println!("{}", serde_json::to_string_pretty(&snippet)?);
        return Ok(());
    }

    let path = claude_settings_path()?;
    let mut settings: Value = match std::fs::read_to_string(&path) {
        Ok(s) => serde_json::from_str(&s)
            .with_context(|| format!("{} is not valid JSON", path.display()))?,
        Err(_) => Value::Object(Default::default()),
    };
    set_statusline(&mut settings, &path)?;

    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("failed to create {}", parent.display()))?;
    }
    write_settings(&path, &settings)?;

    println!(
        "Wired the llmtrim status line into {}. Restart Claude Code to see it.",
        path.display()
    );
    Ok(())
}

/// Ownership of the Claude Code `statusLine` key relative to this binary.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OwnedStatus {
    /// No `statusLine` key (or missing settings file).
    Missing,
    /// Ours, but command path or refreshInterval differs from what we would write now.
    Stale,
    /// Ours and matches the current payload.
    Current,
    /// Present but not an llmtrim statusline — leave it alone.
    Foreign,
}

/// Whether this binary owns the current `statusLine` (Missing is not first-installed by ensure).
pub fn owned_status() -> OwnedStatus {
    let Ok(path) = claude_settings_path() else {
        return OwnedStatus::Missing;
    };
    let Ok(s) = std::fs::read_to_string(&path) else {
        return OwnedStatus::Missing;
    };
    let Ok(settings) = serde_json::from_str::<Value>(&s) else {
        return OwnedStatus::Missing;
    };
    owned_status_of(&settings)
}

fn owned_status_of(settings: &Value) -> OwnedStatus {
    let Some(status_line) = settings.get("statusLine").and_then(Value::as_object) else {
        return OwnedStatus::Missing;
    };
    let Some(command) = status_line.get("command").and_then(Value::as_str) else {
        return OwnedStatus::Foreign;
    };
    if !is_llmtrim_statusline_command(command) {
        return OwnedStatus::Foreign;
    }
    let desired = statusline_config();
    let desired_cmd = desired.get("command").and_then(Value::as_str).unwrap_or("");
    let desired_refresh = desired
        .get("refreshInterval")
        .and_then(Value::as_i64)
        .unwrap_or(REFRESH_INTERVAL_SECS);
    let refresh = status_line.get("refreshInterval").and_then(Value::as_i64);
    if command == desired_cmd && refresh == Some(desired_refresh) {
        OwnedStatus::Current
    } else {
        OwnedStatus::Stale
    }
}

/// Outcome of [`sync_owned`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SyncOutcome {
    Installed,
    Refreshed,
    AlreadyCurrent,
    SkippedForeign,
}

/// Install or refresh our status line. Never overwrites a foreign custom status line.
pub fn sync_owned() -> Result<SyncOutcome> {
    let path = claude_settings_path()?;
    let mut settings: Value = match std::fs::read_to_string(&path) {
        Ok(s) => serde_json::from_str(&s)
            .with_context(|| format!("{} is not valid JSON", path.display()))?,
        Err(_) => Value::Object(Default::default()),
    };
    match owned_status_of(&settings) {
        OwnedStatus::Foreign => Ok(SyncOutcome::SkippedForeign),
        OwnedStatus::Current => Ok(SyncOutcome::AlreadyCurrent),
        OwnedStatus::Missing => {
            set_statusline(&mut settings, &path)?;
            write_settings(&path, &settings)?;
            Ok(SyncOutcome::Installed)
        }
        OwnedStatus::Stale => {
            // Replace only our owned fields (command + refreshInterval); keep padding etc.
            refresh_statusline_config(&mut settings)?;
            write_settings(&path, &settings)?;
            Ok(SyncOutcome::Refreshed)
        }
    }
}

fn write_settings(path: &Path, settings: &Value) -> Result<()> {
    atomic_write_json(path, settings)
}

/// Re-point an existing llmtrim-owned Claude statusline at the current binary and ensure
/// `refreshInterval` is set. A custom command is left alone. Returns whether anything changed.
fn refresh_statusline_config(settings: &mut Value) -> Result<bool> {
    let Some(status_line) = settings
        .get_mut("statusLine")
        .and_then(Value::as_object_mut)
    else {
        return Ok(false);
    };
    let Some(command) = status_line.get("command").and_then(Value::as_str) else {
        return Ok(false);
    };
    if !is_llmtrim_statusline_command(command) {
        return Ok(false);
    }

    let desired = statusline_config();
    let desired_cmd = desired
        .get("command")
        .and_then(Value::as_str)
        .map(str::to_string)
        .unwrap_or_default();
    let desired_refresh = desired
        .get("refreshInterval")
        .cloned()
        .unwrap_or(Value::from(REFRESH_INTERVAL_SECS));

    let mut changed = false;
    if status_line.get("command").and_then(Value::as_str) != Some(desired_cmd.as_str()) {
        status_line.insert("command".to_string(), Value::String(desired_cmd));
        changed = true;
    }
    if status_line.get("refreshInterval") != Some(&desired_refresh) {
        status_line.insert("refreshInterval".to_string(), desired_refresh);
        changed = true;
    }
    Ok(changed)
}

/// Refresh an existing llmtrim-owned Claude statusline without touching custom commands.
/// Returns whether the settings file was rewritten. This runs during `llmtrim update` before
/// package managers can remove a versioned executable path. Does **not** install when missing.
pub fn refresh_if_installed() -> Result<bool> {
    match owned_status() {
        OwnedStatus::Missing | OwnedStatus::Foreign | OwnedStatus::Current => Ok(false),
        OwnedStatus::Stale => {
            let path = claude_settings_path()?;
            let Ok(s) = std::fs::read_to_string(&path) else {
                return Ok(false);
            };
            let mut settings: Value = serde_json::from_str(&s)
                .with_context(|| format!("{} is not valid JSON", path.display()))?;
            if !refresh_statusline_config(&mut settings)? {
                return Ok(false);
            }
            write_settings(&path, &settings)?;
            Ok(true)
        }
    }
}

/// Remove the `statusLine` key we wrote (leaves the rest of `settings.json` untouched).
pub fn uninstall() -> Result<()> {
    let path = claude_settings_path()?;
    let Ok(s) = std::fs::read_to_string(&path) else {
        println!("No {} to edit — nothing to remove.", path.display());
        return Ok(());
    };
    let mut settings: Value = serde_json::from_str(&s)
        .with_context(|| format!("{} is not valid JSON", path.display()))?;
    if clear_statusline(&mut settings, &path)? {
        std::fs::write(&path, serde_json::to_string_pretty(&settings)?)
            .with_context(|| format!("failed to write {}", path.display()))?;
        println!("Removed the llmtrim status line from {}.", path.display());
    } else {
        println!("No llmtrim status line found in {}.", path.display());
    }
    Ok(())
}

// ── sub always-on: skip Claude Code's Anthropic OAuth ─────────────────────────
//
// Claude Code gates every turn (including `/compact`) on a live Anthropic OAuth session even
// when llmtrim rewrites the request to Grok/Codex/Kimi. claude-code-proxy avoids that by
// launching Claude with `ANTHROPIC_AUTH_TOKEN=unused`. We do the same via Claude's own
// `settings.json` `env` block when global `sub` is always-on *and* `sub.anthropic_login = skip`
// (the default) — Claude never starts the OAuth flow, and the MITM still strips the dummy token
// and injects the real provider token.
//
// Trade-off: Claude Code treats any ANTHROPIC_AUTH_TOKEN / API key as taking precedence over
// claude.ai login, so **claude.ai connectors are disabled** while our dummy is set. Users who
// need connectors run `llmtrim sub anthropic-login keep` (and stay logged in to Anthropic).
//
// The dummy token alone is not enough. Shell profiles only export `HTTPS_PROXY` when the
// daemon is alive *at shell start*, and non-interactive / IDE / remote launches often never
// source those profiles. Claude then sends `Authorization: Bearer llmtrim-sub` straight to
// api.anthropic.com → `401 Invalid bearer token` / "Please run /login". So the skip-login
// package also writes the MITM proxy URL + CA trust into `settings.json` `env`, which Claude
// loads regardless of how it was launched.
//
// Unlike the shell block, settings deliberately do **not** gate on daemon liveness: Claude
// cannot re-read the profile mid-session, and a dummy token without a proxy is always worse
// than a proxy that is temporarily down (connection error vs. "Please run /login"). When
// skip-login turns off, the whole package is removed.
//
// Ownership: only touch the key when missing or already set to our sentinel value. Never
// overwrite a real API key the user put there, and never remove a foreign value on `sub off`.
// We deliberately do *not* manage CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC — that flag is a
// boolean `"1"` we cannot own without risking a user's pre-existing preference.

/// Sentinel written to `settings.json` → `env.ANTHROPIC_AUTH_TOKEN` while always-sub skips login.
/// Distinctive so we can remove it later without clobbering a user's real key.
pub const SUB_AUTH_TOKEN_VALUE: &str = "llmtrim-sub";

const SUB_AUTH_TOKEN_KEY: &str = "ANTHROPIC_AUTH_TOKEN";

/// MITM proxy + CA paths written into Claude `settings.json` env alongside the dummy token.
/// Without these, skip-login depends on the shell having exported `HTTPS_PROXY` — and that
/// fails for any launch that did not source the managed profile while the daemon was up.
///
/// `proxy_url` is always set (port falls back to [`crate::setup::DEFAULT_PORT`]). CA paths are
/// optional so a missing `ca.pem` still pins the proxy URL rather than leaving a dummy-only
/// package that 401s at Anthropic.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SubAuthProxyEnv {
    /// e.g. `http://127.0.0.1:43117`
    pub proxy_url: String,
    /// Path to the llmtrim MITM CA (`ca.pem`) for `NODE_EXTRA_CA_CERTS`, when the file exists.
    pub ca_certs: Option<String>,
    /// Combined OS-roots + MITM CA bundle, when available (`ca-bundle.pem`).
    pub ca_bundle: Option<String>,
}

/// Result of reconciling the Claude Code dummy-auth env with the current sub mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SubAuthEnvChange {
    /// Wrote our sentinel into `env.ANTHROPIC_AUTH_TOKEN`.
    Injected,
    /// Removed our sentinel (sub off / fallback / keep-login / uninstall).
    Removed,
    /// Already correct, or a foreign value we refuse to touch, or no Claude settings to edit.
    Unchanged,
}

/// What is currently in Claude settings regarding our dummy auth (for status output).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SubAuthEnvPresence {
    /// Our sentinel is set — Claude Code skips Anthropic OAuth; connectors disabled.
    Ours,
    /// A non-sentinel ANTHROPIC_AUTH_TOKEN is set — we left it alone.
    Foreign,
    /// No ANTHROPIC_AUTH_TOKEN in settings env.
    Absent,
    /// Settings file missing / unreadable / not an object.
    Unknown,
}

/// Node 20.18+/22+ undici `fetch` ignores `HTTPS_PROXY` unless this is set. Claude Code uses
/// that stack, so without it skip-login's dummy token hits real Anthropic → `401 Invalid bearer
/// token` even when the shell has `HTTPS_PROXY` and the MITM is healthy.
const NODE_USE_ENV_PROXY_KEY: &str = "NODE_USE_ENV_PROXY";
const NODE_USE_ENV_PROXY_VALUE: &str = "1";

const HTTPS_PROXY_KEY: &str = "HTTPS_PROXY";
const HTTP_PROXY_KEY: &str = "HTTP_PROXY";
const NO_PROXY_KEY: &str = "NO_PROXY";
const NO_PROXY_LOWER_KEY: &str = "no_proxy";
const NODE_EXTRA_CA_KEY: &str = "NODE_EXTRA_CA_CERTS";
const SSL_CERT_FILE_KEY: &str = "SSL_CERT_FILE";
const CURL_CA_BUNDLE_KEY: &str = "CURL_CA_BUNDLE";

/// True when `value` is something we previously wrote for the MITM proxy URL
/// (`http://127.0.0.1:<digits>`), so an upgrade can rewrite the port without clobbering a
/// user's unrelated proxy.
fn is_llmtrim_proxy_url(value: &str) -> bool {
    let rest = value
        .strip_prefix("http://127.0.0.1:")
        .or_else(|| value.strip_prefix("http://localhost:"));
    rest.is_some_and(|r| !r.is_empty() && r.chars().all(|c| c.is_ascii_digit()))
}

/// True when `value` looks like an llmtrim CA path under `~/.llmtrim/` (any home).
fn is_llmtrim_ca_path(value: &str) -> bool {
    let norm = value.replace('\\', "/");
    norm.contains("/.llmtrim/") && (norm.ends_with("/ca.pem") || norm.ends_with("/ca-bundle.pem"))
}

/// Insert/update one env key. Overwrites when absent or `can_overwrite(current)`; never
/// clobbers a foreign value.
fn set_env_if(
    env_obj: &mut serde_json::Map<String, Value>,
    key: &str,
    want: &str,
    can_overwrite: impl Fn(&str) -> bool,
) -> bool {
    match env_obj.get(key).and_then(Value::as_str) {
        Some(cur) if cur == want => false,
        Some(cur) if !can_overwrite(cur) => false,
        _ => {
            env_obj.insert(key.to_string(), Value::String(want.to_string()));
            true
        }
    }
}

fn drop_env_if(
    env_obj: &mut serde_json::Map<String, Value>,
    key: &str,
    should_drop: impl Fn(&str) -> bool,
) {
    if env_obj
        .get(key)
        .and_then(Value::as_str)
        .is_some_and(should_drop)
    {
        env_obj.remove(key);
    }
}

/// Insert/update our skip-login package keys on `env_obj`. Returns whether anything changed.
///
/// Proxy/CA keys are only written when `proxy` is `Some`. Existing values are overwritten only
/// when absent or already ours (loopback llmtrim URL / llmtrim CA path) — never a foreign proxy.
///
/// `NODE_USE_ENV_PROXY` is forced to `"1"` whenever we own the package: a foreign `"0"` would
/// leave undici ignoring `HTTPS_PROXY` and reintroduce the 401.
fn ensure_sub_auth_package(
    env_obj: &mut serde_json::Map<String, Value>,
    proxy: Option<&SubAuthProxyEnv>,
) -> bool {
    let mut changed = false;

    // Always force undici to honor HTTPS_PROXY while skip-login owns the process.
    if set_env_if(
        env_obj,
        NODE_USE_ENV_PROXY_KEY,
        NODE_USE_ENV_PROXY_VALUE,
        |_| true,
    ) {
        changed = true;
    }

    let Some(proxy) = proxy else {
        return changed;
    };

    if set_env_if(
        env_obj,
        HTTPS_PROXY_KEY,
        &proxy.proxy_url,
        is_llmtrim_proxy_url,
    ) {
        changed = true;
    }
    if set_env_if(
        env_obj,
        HTTP_PROXY_KEY,
        &proxy.proxy_url,
        is_llmtrim_proxy_url,
    ) {
        changed = true;
    }
    // Same bypass list as the shell profile — Claude (and children) must not MITM loopback.
    if set_env_if(env_obj, NO_PROXY_KEY, crate::setup::NO_PROXY, |cur| {
        cur == crate::setup::NO_PROXY
    }) {
        changed = true;
    }
    if set_env_if(env_obj, NO_PROXY_LOWER_KEY, crate::setup::NO_PROXY, |cur| {
        cur == crate::setup::NO_PROXY
    }) {
        changed = true;
    }
    if let Some(ca) = proxy.ca_certs.as_deref()
        && set_env_if(env_obj, NODE_EXTRA_CA_KEY, ca, is_llmtrim_ca_path)
    {
        changed = true;
    }
    if let Some(bundle) = proxy.ca_bundle.as_deref() {
        if set_env_if(env_obj, SSL_CERT_FILE_KEY, bundle, is_llmtrim_ca_path) {
            changed = true;
        }
        if set_env_if(env_obj, CURL_CA_BUNDLE_KEY, bundle, is_llmtrim_ca_path) {
            changed = true;
        }
    }
    changed
}

/// Drop keys we own from `env_obj`.
///
/// Removal is shape-based (loopback MITM URL / `~/.llmtrim/` CA path), not exact-value-only:
/// if the daemon moved ports after we wrote settings, teardown must still clear the stale URL
/// rather than leave a dead `HTTPS_PROXY` after `sub off` / uninstall.
fn remove_sub_auth_package(
    env_obj: &mut serde_json::Map<String, Value>,
    proxy: Option<&SubAuthProxyEnv>,
) {
    env_obj.remove(SUB_AUTH_TOKEN_KEY);
    if env_obj.get(NODE_USE_ENV_PROXY_KEY).and_then(Value::as_str) == Some(NODE_USE_ENV_PROXY_VALUE)
    {
        env_obj.remove(NODE_USE_ENV_PROXY_KEY);
    }

    // Exact match when known, else any loopback MITM URL we would have written.
    drop_env_if(env_obj, HTTPS_PROXY_KEY, |cur| {
        proxy.is_some_and(|p| cur == p.proxy_url) || is_llmtrim_proxy_url(cur)
    });
    drop_env_if(env_obj, HTTP_PROXY_KEY, |cur| {
        proxy.is_some_and(|p| cur == p.proxy_url) || is_llmtrim_proxy_url(cur)
    });
    drop_env_if(env_obj, NO_PROXY_KEY, |cur| cur == crate::setup::NO_PROXY);
    drop_env_if(env_obj, NO_PROXY_LOWER_KEY, |cur| {
        cur == crate::setup::NO_PROXY
    });

    drop_env_if(env_obj, NODE_EXTRA_CA_KEY, |cur| {
        proxy
            .and_then(|p| p.ca_certs.as_deref())
            .is_some_and(|ca| cur == ca)
            || is_llmtrim_ca_path(cur)
    });
    drop_env_if(env_obj, SSL_CERT_FILE_KEY, |cur| {
        proxy
            .and_then(|p| p.ca_bundle.as_deref())
            .is_some_and(|b| cur == b)
            || is_llmtrim_ca_path(cur)
    });
    drop_env_if(env_obj, CURL_CA_BUNDLE_KEY, |cur| {
        proxy
            .and_then(|p| p.ca_bundle.as_deref())
            .is_some_and(|b| cur == b)
            || is_llmtrim_ca_path(cur)
    });

    // Legacy cleanup: early 0.11.8-dev also wrote CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1
    // alongside our sentinel. Drop it when tearing down our package.
    const LEGACY_NONESSENTIAL_KEY: &str = "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC";
    if env_obj.get(LEGACY_NONESSENTIAL_KEY).and_then(Value::as_str) == Some("1") {
        env_obj.remove(LEGACY_NONESSENTIAL_KEY);
    }
}

/// Pure mutation of a parsed Claude settings object (token + `NODE_USE_ENV_PROXY` only).
///
/// Prefer [`sync_sub_auth_env`], which also pins the MITM proxy URL + CA trust. This thin
/// wrapper keeps the published 2-arg signature stable for cargo-semver-checks.
pub fn apply_sub_auth_env(settings: &mut Value, want: bool) -> Result<SubAuthEnvChange> {
    apply_sub_auth_env_with_proxy(settings, want, None)
}

/// Pure mutation with an optional MITM proxy package.
///
/// - `want = true`: set `env.ANTHROPIC_AUTH_TOKEN` to [`SUB_AUTH_TOKEN_VALUE`],
///   `NODE_USE_ENV_PROXY=1`, and (when `proxy` is provided) the MITM `HTTPS_PROXY` + CA trust
///   keys — unless a foreign (non-sentinel) token is already there.
/// - `want = false`: remove those keys only when the token holds our sentinel.
pub(crate) fn apply_sub_auth_env_with_proxy(
    settings: &mut Value,
    want: bool,
    proxy: Option<&SubAuthProxyEnv>,
) -> Result<SubAuthEnvChange> {
    let root = settings
        .as_object_mut()
        .context("Claude settings root must be an object")?;

    let current = root
        .get("env")
        .and_then(Value::as_object)
        .and_then(|e| e.get(SUB_AUTH_TOKEN_KEY))
        .and_then(Value::as_str)
        .map(str::to_string);

    if want {
        match current.as_deref() {
            Some(SUB_AUTH_TOKEN_VALUE) => {
                // Ours already — still ensure the full skip-login package (upgrade path for
                // installs that got the dummy token before NODE_USE_ENV_PROXY / settings-level
                // HTTPS_PROXY were added).
                let env = root
                    .entry("env")
                    .or_insert_with(|| Value::Object(Default::default()));
                let env_obj = env
                    .as_object_mut()
                    .context("Claude settings env must be an object")?;
                if ensure_sub_auth_package(env_obj, proxy) {
                    return Ok(SubAuthEnvChange::Injected);
                }
                return Ok(SubAuthEnvChange::Unchanged);
            }
            Some(_) => return Ok(SubAuthEnvChange::Unchanged), // foreign — leave alone
            None => {
                let env = root
                    .entry("env")
                    .or_insert_with(|| Value::Object(Default::default()));
                let env_obj = env
                    .as_object_mut()
                    .context("Claude settings env must be an object")?;
                env_obj.insert(
                    SUB_AUTH_TOKEN_KEY.to_string(),
                    Value::String(SUB_AUTH_TOKEN_VALUE.to_string()),
                );
                ensure_sub_auth_package(env_obj, proxy);
                return Ok(SubAuthEnvChange::Injected);
            }
        }
    }

    // want = false: remove only our package.
    if current.as_deref() != Some(SUB_AUTH_TOKEN_VALUE) {
        return Ok(SubAuthEnvChange::Unchanged);
    }
    let Some(env) = root.get_mut("env") else {
        return Ok(SubAuthEnvChange::Unchanged);
    };
    let Some(env_obj) = env.as_object_mut() else {
        return Ok(SubAuthEnvChange::Unchanged);
    };
    remove_sub_auth_package(env_obj, proxy);
    if env_obj.is_empty() {
        root.remove("env");
    }
    Ok(SubAuthEnvChange::Removed)
}

/// Resolve the MITM proxy URL + CA paths that skip-login should pin into Claude settings.
/// Prefer the live daemon port, then the port wired into shell profiles, then the default.
///
/// Always returns `Some`: a missing CA must not block writing `HTTPS_PROXY` (dummy token
/// without a proxy is the 401 footgun this package exists to prevent).
fn resolve_sub_auth_proxy_env() -> SubAuthProxyEnv {
    let port = crate::daemon::running()
        .map(|s| s.port)
        .or_else(crate::setup::configured_port)
        .unwrap_or(crate::setup::DEFAULT_PORT);
    let (ca_certs, ca_bundle) = match crate::serve::ca_cert_path() {
        Ok(ca) if ca.is_file() => {
            let bundle_path = ca.with_file_name("ca-bundle.pem");
            let ca_bundle = bundle_path
                .is_file()
                .then(|| bundle_path.to_string_lossy().into_owned());
            (Some(ca.to_string_lossy().into_owned()), ca_bundle)
        }
        _ => (None, None),
    };
    SubAuthProxyEnv {
        proxy_url: format!("http://127.0.0.1:{port}"),
        ca_certs,
        ca_bundle,
    }
}

/// Reconcile `~/.claude/settings.json` with whether we should skip Anthropic login.
/// No-op when Claude Code isn't installed or the settings file is missing and we don't need to inject.
pub fn sync_sub_auth_env(want: bool) -> Result<SubAuthEnvChange> {
    let path = claude_settings_path()?;
    let existing = match std::fs::read_to_string(&path) {
        Ok(s) => s,
        Err(_) if !want => return Ok(SubAuthEnvChange::Unchanged),
        Err(_) => String::from("{}"),
    };
    let mut settings: Value = if existing.trim().is_empty() {
        Value::Object(Default::default())
    } else {
        serde_json::from_str(&existing)
            .with_context(|| format!("{} is not valid JSON", path.display()))?
    };
    let proxy = resolve_sub_auth_proxy_env();
    let change = apply_sub_auth_env_with_proxy(&mut settings, want, Some(&proxy))?;
    if matches!(
        change,
        SubAuthEnvChange::Injected | SubAuthEnvChange::Removed
    ) {
        write_settings(&path, &settings)?;
    }
    Ok(change)
}

/// Drop our sentinel from Claude settings (uninstall / teardown). Idempotent.
pub fn clear_sub_auth_env() -> Result<SubAuthEnvChange> {
    sync_sub_auth_env(false)
}

/// Read-only: is our dummy token (or a foreign one) present in Claude settings?
pub fn sub_auth_env_presence() -> SubAuthEnvPresence {
    let Ok(path) = claude_settings_path() else {
        return SubAuthEnvPresence::Unknown;
    };
    let Ok(s) = std::fs::read_to_string(&path) else {
        return SubAuthEnvPresence::Absent;
    };
    let Ok(settings) = serde_json::from_str::<Value>(&s) else {
        return SubAuthEnvPresence::Unknown;
    };
    match settings
        .get("env")
        .and_then(Value::as_object)
        .and_then(|e| e.get(SUB_AUTH_TOKEN_KEY))
        .and_then(Value::as_str)
    {
        Some(SUB_AUTH_TOKEN_VALUE) => SubAuthEnvPresence::Ours,
        Some(_) => SubAuthEnvPresence::Foreign,
        None => SubAuthEnvPresence::Absent,
    }
}

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

    fn led(health: Health) -> Led {
        Led {
            health,
            trim_pct: Some(6.8),
            reroute: Some("codex".to_string()),
            reroute_window: None,
            resolved_model: Some("gpt-5.6-terra".to_string()),
            cache_cold: false,
            last_cache_pct: None,
            last_ctx_tokens: 0,
            // Tests that exercise the Claude blob path clear reroute; tests that keep the
            // codex arrow inject sub windows explicitly (or inherit these placeholders).
            sub_five: Some(("5h".into(), 24.0)),
            sub_seven: Some(("7d".into(), 12.0)),
        }
    }

    fn cc(ctx: i64) -> CcInput {
        CcInput {
            model: "Opus".to_string(),
            effort: Some("high".to_string()),
            session_id: None,
            model_id: "claude-opus-4-8".to_string(),
            ctx_tokens: ctx,
            window: Some(200_000),
            five_hour_pct: Some(24.0),
            seven_day_pct: Some(12.0),
            five_hour_resets_at: None,
            seven_day_resets_at: None,
            cache_pct: Some(63.0),
        }
    }

    #[test]
    fn full_line_has_every_segment_when_wide() {
        // 142k of a 200k window = 71% ⇒ red gauge; both rolling quota windows shown.
        let out = render_line(&cc(142_000), &led(Health::Healthy), 0, false);
        assert_eq!(
            out,
            "◆ Opus→gpt-5.6-terra   ▓▓▓▓▓░░░ 142k   ✂ 6.8%   ◔ 5h·24% · 7d·12%   ♻ 63% cached"
        );
    }

    #[test]
    fn context_gauge_colors_by_percent_of_real_window() {
        // Bands are % of the model's real window. On a 1M window, 142k is only 14% ⇒ green.
        let mut c = cc(142_000);
        c.window = Some(1_000_000);
        let out = context_segment(c.ctx_tokens, 1_000_000, false, true);
        assert!(out.contains(GREEN), "14% of 1M is green: {out}");
        // Same 142k on a 200k window is 71% ⇒ red.
        let out = context_segment(142_000, 200_000, false, true);
        assert!(out.contains(RED), "71% of 200k is red: {out}");
        // 50% lands in the orange band (40–65%).
        let out = context_segment(100_000, 200_000, false, true);
        assert!(out.contains(ORANGE), "50% is orange: {out}");
    }

    #[test]
    fn context_gauge_pins_full_over_window() {
        let out = render_line(&cc(210_000), &led(Health::Healthy), 0, false);
        assert!(
            out.contains("▓▓▓▓▓▓▓▓ 210k"),
            "over window pins full: {out}"
        );
    }

    #[test]
    fn cold_cache_forces_red_gauge_regardless_of_fill() {
        // A near-empty context still reddens the gauge when the cache is cold.
        let mut l = led(Health::Healthy);
        l.cache_cold = true;
        let out = context_segment(1_000, 1_000_000, true, true);
        assert!(out.contains(RED), "cold cache reddens even at 0.1%: {out}");
    }

    #[test]
    fn reroute_arrow_hidden_when_not_healthy() {
        let out = render_line(&cc(142_000), &led(Health::Degraded), 0, false);
        assert!(!out.contains("→codex"), "no arrow when degraded: {out}");
        assert!(
            out.contains("⚠ llmtrim degraded"),
            "warns instead of ✂: {out}"
        );
    }

    #[test]
    fn stopped_omits_trim_and_arrow_without_warning() {
        let mut l = led(Health::Stopped);
        l.reroute = None;
        l.resolved_model = None;
        let out = render_line(&cc(48_000), &l, 0, false);
        assert!(!out.contains('✂'), "no trim when off: {out}");
        assert!(!out.contains('⚠'), "clean off is not an error: {out}");
        assert!(out.starts_with("◆ Opus"), "model still shown: {out}");
    }

    #[test]
    fn narrow_terminal_sheds_extras_right_to_left() {
        // Wide enough for core + quota, but not the cache extra.
        let full = render_line(&cc(142_000), &led(Health::Healthy), 0, false);
        let width =
            ui::visible_width("◆ Opus→gpt-5.6-terra   ▓▓▓▓▓░░░ 142k   ✂ 6.8%   ◔ 5h·24% · 7d·12%");
        let out = render_line(&cc(142_000), &led(Health::Healthy), width, false);
        assert!(out.ends_with("7d·12%"), "keeps quota, sheds cache: {out}");
        assert!(!out.contains("cached"), "cache dropped first: {out}");
        assert!(full.len() > out.len());
    }

    #[test]
    fn absent_data_segments_do_not_render() {
        let mut c = cc(48_000);
        c.effort = None; // non-reasoning model
        c.five_hour_pct = None; // API-key user
        c.seven_day_pct = None;
        c.cache_pct = None; // before first API response
        let mut l = led(Health::Healthy);
        l.reroute = None; // no reroute
        l.resolved_model = None;
        let out = render_line(&c, &l, 0, false);
        assert_eq!(out, "◆ Opus   ▓░░░░░░░ 48k   ✂ 6.8%");
    }

    #[test]
    fn cold_cache_shows_compact_hint_not_stale_pct() {
        let mut l = led(Health::Healthy);
        l.cache_cold = true;
        let out = render_line(&cc(48_000), &l, 0, false);
        assert!(out.contains("♻ cache cold"), "cold hint shown: {out}");
        assert!(!out.contains("cached"), "no stale % when cold: {out}");
    }

    #[test]
    fn post_compact_reset_clears_cold_even_when_ledger_stale() {
        let mut c = cc(0);
        c.cache_pct = None;
        assert!(
            !effective_cache_cold(&c, true),
            "empty context after compact is not cold"
        );
        let mut l = led(Health::Healthy);
        l.cache_cold = effective_cache_cold(&c, true);
        let out = render_line(&c, &l, 0, false);
        assert!(!out.contains("cold"), "no cold nudge after compact: {out}");
        let gauge = context_segment(c.ctx_tokens, 200_000, l.cache_cold, true);
        assert!(
            gauge.contains(DIM),
            "gauge dim (not red) on fresh post-compact context: {gauge}"
        );
        assert!(
            !gauge.contains(RED),
            "gauge not red on fresh post-compact context: {gauge}"
        );
    }

    #[test]
    fn idle_cold_stays_when_context_still_populated() {
        let mut c = cc(142_000);
        c.cache_pct = Some(5.0);
        assert!(
            effective_cache_cold(&c, true),
            "populated context with stale ledger still shows cold"
        );
    }

    #[test]
    fn quota_labels_show_time_remaining_until_reset() {
        // Claude blob path (no sub): labels come from resets_at on the stdin payload.
        let mut c = cc(48_000);
        c.five_hour_resets_at = Some(
            (chrono::Utc::now() + chrono::Duration::hours(3) + chrono::Duration::minutes(30))
                .timestamp(),
        );
        c.seven_day_resets_at = Some(
            (chrono::Utc::now() + chrono::Duration::days(4) + chrono::Duration::hours(12))
                .timestamp(),
        );
        let mut l = led(Health::Healthy);
        l.reroute = None;
        l.resolved_model = None;
        l.sub_five = None;
        l.sub_seven = None;
        let out = render_line(&c, &l, 0, false);
        assert!(out.contains("◔ 3h·24% · 4d·12%"), "remaining labels: {out}");
    }

    #[test]
    fn quota_color_escalates_green_amber_orange_red() {
        assert_eq!(quota_color(50.0), GREEN);
        assert_eq!(quota_color(75.0), AMBER);
        assert_eq!(quota_color(85.0), ORANGE); // the added 80%+ step
        assert_eq!(quota_color(95.0), RED);
    }

    #[test]
    fn quota_windows_colour_independently() {
        // A maxed 5h next to a comfortable 7d: 5h red, 7d green — not both painted by the worse.
        let mut l = led(Health::Healthy);
        l.sub_five = Some(("5h".into(), 95.0));
        l.sub_seven = Some(("7d".into(), 12.0));
        let segs = extra_segments(&cc(48_000), &l, true);
        let quota = segs
            .iter()
            .find(|s| s.contains("5h"))
            .expect("quota segment");
        // Only the percentage is coloured; the `5h`/`7d` labels stay dim.
        assert!(
            quota.contains(&format!("\x1b[{DIM}m5h·")),
            "5h label dim: {quota}"
        );
        assert!(
            quota.contains(&format!("\x1b[{RED}m95%")),
            "5h pct red: {quota}"
        );
        assert!(
            quota.contains(&format!("\x1b[{DIM}m7d·")),
            "7d label dim: {quota}"
        );
        assert!(
            quota.contains(&format!("\x1b[{GREEN}m12%")),
            "7d pct green: {quota}"
        );
    }

    #[test]
    fn trim_is_not_coloured_by_tier() {
        // The savings figure is dim, not green — colour is for state signals only.
        let seg = trim_or_health_segment(&led(Health::Healthy), true).unwrap();
        assert!(
            seg.contains(&format!("\x1b[{DIM}m✂ 6.8%")),
            "trim dim: {seg}"
        );
        assert!(
            !seg.contains(&format!("\x1b[{GREEN}m✂")),
            "not green: {seg}"
        );
    }

    #[test]
    fn quota_shows_worse_window_and_folds_to_one_segment() {
        // Both windows in one `◔` segment; only one present ⇒ just that one.
        let out = render_line(&cc(48_000), &led(Health::Healthy), 0, false);
        assert!(out.contains("◔ 5h·24% · 7d·12%"), "both windows: {out}");
        let mut l = led(Health::Healthy);
        l.sub_seven = None;
        let out = render_line(&cc(48_000), &l, 0, false);
        assert!(
            out.contains("◔ 5h·24%") && !out.contains("7d"),
            "5h only: {out}"
        );
    }

    #[test]
    fn sub_weekly_only_omits_invented_five_hour() {
        // Plus-style Codex plan: only a weekly window. Must not paint a fake 5h.
        let mut l = led(Health::Healthy);
        l.sub_five = None;
        l.sub_seven = Some(("7d".into(), 1.0));
        let out = render_line(&cc(48_000), &l, 0, false);
        assert!(out.contains("◔ 7d·1%"), "weekly shown: {out}");
        assert!(!out.contains("5h"), "no invented 5h: {out}");
    }

    #[test]
    fn sub_without_snapshot_falls_back_to_claude_blob() {
        // Predicted always-mode / first turn before the proxy poll lands: keep Claude's
        // numbers rather than a blank segment. Once a snapshot exists it wins (see
        // `sub_weekly_only_omits_invented_five_hour`).
        let mut l = led(Health::Healthy);
        l.sub_five = None;
        l.sub_seven = None;
        let out = render_line(&cc(48_000), &l, 0, false);
        assert!(
            out.contains("◔ 5h·24% · 7d·12%"),
            "claude blob until sub cache arrives: {out}"
        );
    }

    #[test]
    fn degraded_proxy_falls_back_to_claude_blob_even_with_sub_cache() {
        // Unhealthy proxy is not intercepting, so the arrow is hidden and Anthropic will
        // serve — prefer its blob over a stale codex snapshot.
        let mut l = led(Health::Degraded);
        l.sub_five = Some(("5h".into(), 95.0));
        l.sub_seven = Some(("7d".into(), 1.0));
        let out = render_line(&cc(48_000), &l, 0, false);
        assert!(
            out.contains("◔ 5h·24% · 7d·12%"),
            "claude blob when degraded: {out}"
        );
        assert!(!out.contains("95%"), "stale sub 5h not shown: {out}");
    }

    #[test]
    fn off_sub_still_uses_claude_blob_quota() {
        let mut l = led(Health::Healthy);
        l.reroute = None;
        l.resolved_model = None;
        l.sub_five = None;
        l.sub_seven = None;
        let out = render_line(&cc(48_000), &l, 0, false);
        assert!(
            out.contains("◔ 5h·24% · 7d·12%"),
            "claude blob when not rerouted: {out}"
        );
    }

    #[test]
    fn kimi_reroute_when_healthy() {
        let tiers = std::collections::BTreeMap::new();
        let mut l = led(Health::Healthy);
        l.reroute = Some("kimi".to_string());
        l.resolved_model = reroute_resolved_model("kimi", "claude-opus-4-6", &tiers);
        assert!(
            l.resolved_model.is_none(),
            "kimi collapses to one wire id; the arrow shows the shortname"
        );
        let out = render_line(&cc(72_000), &l, 0, true);
        assert!(out.contains("→kimi"), "kimi arrow present: {out}");
        assert!(
            !out.contains("kimi-for-coding"),
            "no internal wire id on the line: {out}"
        );
    }

    #[test]
    fn grok_reroute_shows_resolved_model_when_healthy() {
        let tiers = std::collections::BTreeMap::new();
        let mut l = led(Health::Healthy);
        l.reroute = Some("grok".to_string());
        l.resolved_model = reroute_resolved_model("grok", "claude-opus-4-8", &tiers);
        assert_eq!(l.resolved_model.as_deref(), Some("grok-4.6"));
        let out = render_line(&cc(72_000), &l, 0, true);
        assert!(out.contains("→grok-4.6"), "grok arrow shows model: {out}");
    }

    fn ledger_row(sub: Option<&str>, model: Option<&str>) -> SessionLedgerRow {
        SessionLedgerRow {
            input_before: 1000,
            input_after: 940,
            last_ts: chrono::Utc::now().to_rfc3339(),
            last_sub_provider: sub.map(str::to_string),
            last_model: model.map(str::to_string),
            last_cache_hit: None,
            last_input_tokens: 0,
        }
    }

    #[test]
    fn fallback_mode_shows_no_arrow_until_a_backend_actually_serves() {
        // Anthropic served the turn: the chain is armed but never fired, so claiming a reroute
        // would be a lie — and would rescale the gauge to Codex's window.
        let row = ledger_row(None, Some("claude-opus-4-8"));
        assert!(matches!(
            arrow_source(Some("codex"), true, Some(&row)),
            ArrowSource::None
        ));
    }

    #[test]
    fn always_mode_predicts_after_anthropic_turns() {
        // Mid-session `/sub on grok` (or global always): earlier Anthropic turns leave a ledger
        // row with no sub provider. The next turn will reroute — show the prediction.
        let row = ledger_row(None, Some("claude-opus-4-8"));
        let ArrowSource::Predicted(p) = arrow_source(Some("grok"), false, Some(&row)) else {
            panic!("always mode must predict after Anthropic-only history");
        };
        assert_eq!(p, "grok");
    }

    #[test]
    fn always_mode_predicts_switched_provider_over_stale_served() {
        // Window was on codex (ledger still says codex); user ran `/sub on grok`.
        let row = ledger_row(Some("codex"), Some("gpt-5.6-terra"));
        let ArrowSource::Predicted(p) = arrow_source(Some("grok"), false, Some(&row)) else {
            panic!("switched provider must override stale Served");
        };
        assert_eq!(p, "grok");
    }

    #[test]
    fn fallback_mode_keeps_stale_served_until_ledger_moves() {
        // In fallback, a prior codex fire is still truth; config must not invent a new target.
        let row = ledger_row(Some("codex"), Some("gpt-5.6-terra"));
        let ArrowSource::Served { provider, .. } = arrow_source(Some("grok"), true, Some(&row))
        else {
            panic!("fallback keeps Served");
        };
        assert_eq!(provider, "codex");
    }

    #[test]
    fn fallback_mode_shows_the_backend_once_the_chain_fires() {
        let row = ledger_row(Some("codex"), Some("gpt-5.6-terra"));
        let ArrowSource::Served { provider, model } = arrow_source(Some("codex"), true, Some(&row))
        else {
            panic!("a fired fallback must surface the backend that served it");
        };
        assert_eq!(provider, "codex");
        assert_eq!(model.as_deref(), Some("gpt-5.6-terra"));
    }

    #[test]
    fn fallback_mode_never_predicts_from_config_on_a_fresh_session() {
        // No turn yet. `always` mode could predict; fallback mode cannot — Anthropic serves the
        // first turn and the chain only fires if it fails.
        assert!(matches!(
            arrow_source(Some("codex"), true, None),
            ArrowSource::None
        ));
        assert!(matches!(
            arrow_source(Some("codex"), false, None),
            ArrowSource::Predicted(p) if p == "codex"
        ));
    }

    #[test]
    fn ledger_truth_wins_when_it_matches_policy() {
        // Last turn was codex and policy still says codex: advertise what just served.
        let row = ledger_row(Some("codex"), Some("gpt-5.6-terra"));
        let ArrowSource::Served { provider, model } =
            arrow_source(Some("codex"), false, Some(&row))
        else {
            panic!("matching policy keeps Served");
        };
        assert_eq!(provider, "codex");
        assert_eq!(model.as_deref(), Some("gpt-5.6-terra"));
    }

    #[test]
    fn trim_for_does_not_flash_lifetime_on_a_fresh_session() {
        let lifetime = || Some(6.8);
        // A known session with no recorded turn yet ⇒ idle (None), NOT the lifetime figure —
        // the "6.8% then flips to the real number" flash we're fixing.
        assert_eq!(trim_for(Some("sess-uuid"), None, lifetime), None);
        // Its own rows ⇒ the per-session figure (300→200 = 33.3%).
        let own = trim_for(Some("sess-uuid"), Some((300, 200)), lifetime).unwrap();
        assert!((own - 33.333).abs() < 0.01, "per-session figure: {own}");
        // No session id at all (non-Claude-Code client) ⇒ lifetime is the only honest figure.
        assert_eq!(trim_for(None, None, lifetime), Some(6.8));
    }

    #[test]
    fn context_gauge_holds_its_fill_while_a_turn_is_in_flight() {
        // `total_input_tokens` comes from the last *response*, so mid-request the blob reports 0
        // and the bar empties — the flicker the cache segment had. The last completed turn's
        // input, measured on the wire, holds it.
        let mut mid_turn = cc(48_000);
        mid_turn.ctx_tokens = 0;
        let mut l = led(Health::Healthy);
        l.last_ctx_tokens = 48_000;
        assert_eq!(
            render_line(&mid_turn, &l, 0, false),
            render_line(&cc(48_000), &l, 0, false),
            "mid-turn gauge matches the completed-turn gauge"
        );
        // The blob wins whenever it has a figure; a truly fresh session (no turn, no row) still
        // renders empty rather than inventing a fill.
        assert_eq!(ctx_tokens_for(142_000, 48_000), 142_000);
        assert_eq!(ctx_tokens_for(0, 0), 0);
    }

    #[test]
    fn cache_segment_holds_its_value_while_a_turn_is_in_flight() {
        // Claude Code drops `current_usage` from the blob mid-request, so `cc.cache_pct` is None
        // on every re-render during a turn. Without a fallback the segment vanishes and pops back
        // when the turn lands — a flicker that reads like the cache collapsing.
        let mut mid_turn = cc(48_000);
        mid_turn.cache_pct = None;
        let mut l = led(Health::Healthy);
        l.last_cache_pct = Some(98.0);
        let out = render_line(&mid_turn, &l, 0, false);
        assert!(out.contains("♻ 98% cached"), "last turn stands in: {out}");

        // The blob still wins the moment it has a figure — the ledger is one turn stale.
        let out = render_line(&cc(48_000), &l, 0, false);
        assert!(
            out.contains("♻ 63% cached"),
            "blob wins when present: {out}"
        );

        // Nothing anywhere (fresh session, no turn yet) ⇒ no segment, not a fake 0%.
        assert_eq!(cache_pct_for(None, None), None);
    }

    #[test]
    fn healthy_but_idle_shows_dim_marker_not_zero() {
        // Nothing trimmed yet in this session: `✂ –`, never a misleading `✂ 0.0%`.
        let mut l = led(Health::Healthy);
        l.trim_pct = None;
        let out = render_line(&cc(48_000), &l, 0, false);
        assert!(out.contains("✂ –"), "idle marker shown: {out}");
        assert!(!out.contains("0.0%"), "no fake zero: {out}");
    }

    #[test]
    fn quota_and_cache_floor_not_round() {
        // 99.9% cache is not 100%; 89.9% quota is not 90%.
        let mut c = cc(48_000);
        c.cache_pct = Some(99.9);
        let mut l = led(Health::Healthy);
        l.sub_five = Some(("5h".into(), 89.9));
        let out = render_line(&c, &l, 0, false);
        assert!(out.contains("5h·89%"), "quota floored: {out}");
        assert!(out.contains("♻ 99% cached"), "cache floored: {out}");
    }

    #[test]
    fn parse_cc_reads_session_id() {
        let cc = parse_cc(r#"{"model":{"display_name":"Opus"},"session_id":"abc-123"}"#);
        assert_eq!(cc.session_id.as_deref(), Some("abc-123"));
        // Empty id is treated as absent (falls back to lifetime trim).
        let cc = parse_cc(r#"{"model":{"display_name":"Opus"},"session_id":""}"#);
        assert!(cc.session_id.is_none());
    }

    #[test]
    fn parse_cc_reads_nested_fields() {
        let blob = r#"{"model":{"display_name":"Sonnet","id":"claude-sonnet-5"},"effort":{"level":"medium"},
            "context_window":{"total_input_tokens":123456,"context_window_size":1000000,
              "current_usage":{"input_tokens":10,"cache_creation_input_tokens":10,"cache_read_input_tokens":80}},
            "rate_limits":{"five_hour":{"used_percentage":41.2,"resets_at":1738425600},
              "seven_day":{"used_percentage":9.0,"resets_at":1738857600}}}"#;
        let cc = parse_cc(blob);
        assert_eq!(cc.model, "Sonnet");
        assert_eq!(cc.model_id, "claude-sonnet-5");
        assert_eq!(cc.effort.as_deref(), Some("medium"));
        assert_eq!(cc.ctx_tokens, 123456);
        assert_eq!(cc.window, Some(1_000_000));
        assert_eq!(cc.five_hour_pct, Some(41.2));
        assert_eq!(cc.seven_day_pct, Some(9.0));
        // Claude Code sends `resets_at` as Unix epoch seconds (an integer), not an RFC3339 string.
        assert_eq!(cc.five_hour_resets_at, Some(1_738_425_600));
        assert_eq!(cc.seven_day_resets_at, Some(1_738_857_600));
        // 80 cache reads of 100 total input = 80%.
        assert_eq!(cc.cache_pct, Some(80.0));
    }

    #[test]
    fn install_merge_preserves_unrelated_keys() {
        let p = std::path::Path::new("settings.json");
        let mut settings = serde_json::json!({
            "theme": "dark",
            "permissions": { "allow": ["Bash"] },
        });
        set_statusline(&mut settings, p).unwrap();
        // Our key is present with a command...
        assert_eq!(settings["statusLine"]["type"], "command");
        // ...and the pre-existing keys are untouched.
        assert_eq!(settings["theme"], "dark");
        assert_eq!(settings["permissions"]["allow"][0], "Bash");
    }

    #[cfg(unix)]
    #[test]
    fn statusline_prefers_stable_path_alias_for_active_binary() {
        let root = std::env::temp_dir().join(format!(
            "llmtrim-statusline-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let versioned_dir = root.join("Cellar/llmtrim/0.9.5/bin");
        let stable_dir = root.join("bin");
        std::fs::create_dir_all(&versioned_dir).unwrap();
        std::fs::create_dir_all(&stable_dir).unwrap();

        let name = "llmtrim";
        let current = versioned_dir.join(name);
        let stable = stable_dir.join(name);
        std::fs::write(&current, b"binary").unwrap();
        std::os::unix::fs::symlink(&current, &stable).unwrap();
        let path = std::env::join_paths([&stable_dir]).unwrap();

        assert_eq!(
            stable_executable_path(&current, Some(path.as_os_str())),
            stable
        );

        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn recognizes_only_llmtrim_statusline_commands_for_refresh() {
        assert!(is_llmtrim_statusline_command(
            "/opt/homebrew/Cellar/llmtrim/0.9.4/bin/llmtrim statusline"
        ));
        assert!(is_llmtrim_statusline_command(
            r#""C:\Program Files\llmtrim\llmtrim.exe" statusline"#
        ));
        assert!(!is_llmtrim_statusline_command("my-statusline-command"));
        assert!(!is_llmtrim_statusline_command(
            "llmtrim statusline --custom"
        ));
    }

    #[test]
    fn refreshes_owned_statusline_without_touching_other_settings() {
        let mut settings = serde_json::json!({
            "theme": "dark",
            "statusLine": {
                "type": "command",
                "command": "/opt/homebrew/Cellar/llmtrim/0.9.4/bin/llmtrim statusline",
                "padding": 2
            }
        });

        assert!(refresh_statusline_config(&mut settings).unwrap());
        assert_eq!(settings["theme"], "dark");
        assert_ne!(
            settings["statusLine"]["command"],
            "/opt/homebrew/Cellar/llmtrim/0.9.4/bin/llmtrim statusline"
        );
        // Only `command` moves: a padding the user chose survives the update.
        assert_eq!(settings["statusLine"]["padding"], 2);
        assert_eq!(settings["statusLine"]["type"], "command");

        let mut custom = serde_json::json!({
            "statusLine": { "type": "command", "command": "my-statusline-command" }
        });
        assert!(!refresh_statusline_config(&mut custom).unwrap());
        assert_eq!(custom["statusLine"]["command"], "my-statusline-command");
    }

    #[test]
    fn refresh_is_a_no_op_when_the_command_already_points_at_this_binary() {
        let mut settings = serde_json::json!({ "statusLine": statusline_config() });
        assert!(!refresh_statusline_config(&mut settings).unwrap());
    }

    #[test]
    fn statusline_config_asks_claude_code_to_refresh_while_idle() {
        // Claude Code otherwise re-renders only on conversation events, so the cold-cache
        // warning would land after the expensive turn instead of before it.
        assert_eq!(
            statusline_config()["refreshInterval"],
            serde_json::json!(300)
        );
    }

    #[test]
    fn uninstall_removes_only_our_key_and_reports_presence() {
        let p = std::path::Path::new("settings.json");
        let mut settings = serde_json::json!({ "theme": "dark", "statusLine": { "x": 1 } });
        assert!(
            clear_statusline(&mut settings, p).unwrap(),
            "reports it was present"
        );
        assert!(settings.get("statusLine").is_none(), "our key gone");
        assert_eq!(settings["theme"], "dark", "other keys kept");
        // Second removal reports absence and is a no-op.
        assert!(!clear_statusline(&mut settings, p).unwrap());
    }

    #[test]
    fn merge_rejects_a_non_object_settings_file() {
        let p = std::path::Path::new("settings.json");
        let mut settings = serde_json::json!([1, 2, 3]);
        assert!(set_statusline(&mut settings, p).is_err());
        assert!(clear_statusline(&mut settings, p).is_err());
    }

    fn sample_proxy() -> SubAuthProxyEnv {
        SubAuthProxyEnv {
            proxy_url: "http://127.0.0.1:43117".into(),
            ca_certs: Some("/home/u/.llmtrim/ca.pem".into()),
            ca_bundle: Some("/home/u/.llmtrim/ca-bundle.pem".into()),
        }
    }

    #[test]
    fn sub_auth_env_injects_sentinel_and_removes_only_ours() {
        let mut settings = serde_json::json!({ "theme": "dark" });
        let proxy = sample_proxy();
        assert_eq!(
            apply_sub_auth_env_with_proxy(&mut settings, true, Some(&proxy)).unwrap(),
            SubAuthEnvChange::Injected
        );
        assert_eq!(
            settings["env"]["ANTHROPIC_AUTH_TOKEN"],
            SUB_AUTH_TOKEN_VALUE
        );
        assert_eq!(settings["env"]["NODE_USE_ENV_PROXY"], "1");
        assert_eq!(settings["env"]["HTTPS_PROXY"], "http://127.0.0.1:43117");
        assert_eq!(settings["env"]["HTTP_PROXY"], "http://127.0.0.1:43117");
        assert_eq!(settings["env"]["NO_PROXY"], crate::setup::NO_PROXY);
        assert_eq!(settings["env"]["no_proxy"], crate::setup::NO_PROXY);
        assert_eq!(
            settings["env"]["NODE_EXTRA_CA_CERTS"],
            "/home/u/.llmtrim/ca.pem"
        );
        assert_eq!(
            settings["env"]["SSL_CERT_FILE"],
            "/home/u/.llmtrim/ca-bundle.pem"
        );
        // Idempotent when already ours (full package).
        assert_eq!(
            apply_sub_auth_env_with_proxy(&mut settings, true, Some(&proxy)).unwrap(),
            SubAuthEnvChange::Unchanged
        );
        // Remove on want=false.
        assert_eq!(
            apply_sub_auth_env_with_proxy(&mut settings, false, Some(&proxy)).unwrap(),
            SubAuthEnvChange::Removed
        );
        assert!(settings.get("env").is_none(), "empty env object dropped");
        assert_eq!(settings["theme"], "dark");
    }

    #[test]
    fn sub_auth_env_never_overwrites_or_removes_a_foreign_token() {
        let mut settings = serde_json::json!({
            "env": { "ANTHROPIC_AUTH_TOKEN": "sk-ant-real", "OTHER": "keep" }
        });
        let proxy = sample_proxy();
        assert_eq!(
            apply_sub_auth_env_with_proxy(&mut settings, true, Some(&proxy)).unwrap(),
            SubAuthEnvChange::Unchanged
        );
        assert_eq!(settings["env"]["ANTHROPIC_AUTH_TOKEN"], "sk-ant-real");
        assert!(
            settings["env"].get("HTTPS_PROXY").is_none(),
            "foreign token blocks the whole package"
        );
        assert_eq!(
            apply_sub_auth_env_with_proxy(&mut settings, false, Some(&proxy)).unwrap(),
            SubAuthEnvChange::Unchanged
        );
        assert_eq!(settings["env"]["ANTHROPIC_AUTH_TOKEN"], "sk-ant-real");
        assert_eq!(settings["env"]["OTHER"], "keep");
    }

    #[test]
    fn sub_auth_env_preserves_sibling_env_keys_when_removing_ours() {
        let mut settings = serde_json::json!({
            "env": {
                "ANTHROPIC_AUTH_TOKEN": SUB_AUTH_TOKEN_VALUE,
                "CLAUDE_CODE_EFFORT_LEVEL": "low"
            }
        });
        assert_eq!(
            apply_sub_auth_env_with_proxy(&mut settings, false, None).unwrap(),
            SubAuthEnvChange::Removed
        );
        assert!(settings["env"].get("ANTHROPIC_AUTH_TOKEN").is_none());
        assert_eq!(settings["env"]["CLAUDE_CODE_EFFORT_LEVEL"], "low");
    }

    #[test]
    fn sub_auth_env_cleans_legacy_nonessential_flag_with_our_token() {
        let mut settings = serde_json::json!({
            "env": {
                "ANTHROPIC_AUTH_TOKEN": SUB_AUTH_TOKEN_VALUE,
                "NODE_USE_ENV_PROXY": "1",
                "HTTPS_PROXY": "http://127.0.0.1:43117",
                "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1",
                "CLAUDE_CODE_EFFORT_LEVEL": "low"
            }
        });
        assert_eq!(
            apply_sub_auth_env_with_proxy(&mut settings, false, None).unwrap(),
            SubAuthEnvChange::Removed
        );
        assert!(settings["env"].get("ANTHROPIC_AUTH_TOKEN").is_none());
        assert!(settings["env"].get("NODE_USE_ENV_PROXY").is_none());
        assert!(
            settings["env"].get("HTTPS_PROXY").is_none(),
            "loopback MITM proxy cleaned without resolved package"
        );
        assert!(
            settings["env"]
                .get("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC")
                .is_none(),
            "legacy package flag cleaned with our token"
        );
        assert_eq!(settings["env"]["CLAUDE_CODE_EFFORT_LEVEL"], "low");
    }

    #[test]
    fn sub_auth_env_upgrades_existing_token_with_proxy_package() {
        // Pre-fix installs only wrote the dummy token (+ maybe NODE_USE_ENV_PROXY). A
        // reconcile must add HTTPS_PROXY + CA so Claude does not need shell profile env.
        let mut settings = serde_json::json!({
            "env": { "ANTHROPIC_AUTH_TOKEN": SUB_AUTH_TOKEN_VALUE }
        });
        let proxy = sample_proxy();
        assert_eq!(
            apply_sub_auth_env_with_proxy(&mut settings, true, Some(&proxy)).unwrap(),
            SubAuthEnvChange::Injected
        );
        assert_eq!(settings["env"]["NODE_USE_ENV_PROXY"], "1");
        assert_eq!(settings["env"]["HTTPS_PROXY"], "http://127.0.0.1:43117");
        assert_eq!(settings["env"]["NO_PROXY"], crate::setup::NO_PROXY);
        assert_eq!(
            settings["env"]["NODE_EXTRA_CA_CERTS"],
            "/home/u/.llmtrim/ca.pem"
        );
    }

    #[test]
    fn sub_auth_env_rewrites_stale_loopback_proxy_port() {
        let mut settings = serde_json::json!({
            "env": {
                "ANTHROPIC_AUTH_TOKEN": SUB_AUTH_TOKEN_VALUE,
                "NODE_USE_ENV_PROXY": "1",
                "HTTPS_PROXY": "http://127.0.0.1:9999",
                "HTTP_PROXY": "http://127.0.0.1:9999"
            }
        });
        let proxy = sample_proxy();
        assert_eq!(
            apply_sub_auth_env_with_proxy(&mut settings, true, Some(&proxy)).unwrap(),
            SubAuthEnvChange::Injected
        );
        assert_eq!(settings["env"]["HTTPS_PROXY"], "http://127.0.0.1:43117");
        assert_eq!(settings["env"]["HTTP_PROXY"], "http://127.0.0.1:43117");
    }

    #[test]
    fn sub_auth_env_remove_clears_stale_port_when_resolved_port_differs() {
        // Wrote :43117 earlier; daemon now lives on :8787. Teardown must still drop the
        // stale loopback URL (exact-match-only remove left it behind).
        let mut settings = serde_json::json!({
            "env": {
                "ANTHROPIC_AUTH_TOKEN": SUB_AUTH_TOKEN_VALUE,
                "NODE_USE_ENV_PROXY": "1",
                "HTTPS_PROXY": "http://127.0.0.1:43117",
                "HTTP_PROXY": "http://127.0.0.1:43117",
                "NODE_EXTRA_CA_CERTS": "/home/u/.llmtrim/ca.pem",
                "CLAUDE_CODE_EFFORT_LEVEL": "low"
            }
        });
        let current = SubAuthProxyEnv {
            proxy_url: "http://127.0.0.1:8787".into(),
            ca_certs: Some("/home/u/.llmtrim/ca.pem".into()),
            ca_bundle: None,
        };
        assert_eq!(
            apply_sub_auth_env_with_proxy(&mut settings, false, Some(&current)).unwrap(),
            SubAuthEnvChange::Removed
        );
        assert!(settings["env"].get("HTTPS_PROXY").is_none());
        assert!(settings["env"].get("HTTP_PROXY").is_none());
        assert!(settings["env"].get("NODE_EXTRA_CA_CERTS").is_none());
        assert_eq!(settings["env"]["CLAUDE_CODE_EFFORT_LEVEL"], "low");
    }

    #[test]
    fn sub_auth_env_forces_node_use_env_proxy_over_zero() {
        let mut settings = serde_json::json!({
            "env": {
                "ANTHROPIC_AUTH_TOKEN": SUB_AUTH_TOKEN_VALUE,
                "NODE_USE_ENV_PROXY": "0"
            }
        });
        let proxy = sample_proxy();
        assert_eq!(
            apply_sub_auth_env_with_proxy(&mut settings, true, Some(&proxy)).unwrap(),
            SubAuthEnvChange::Injected
        );
        assert_eq!(settings["env"]["NODE_USE_ENV_PROXY"], "1");
    }

    #[test]
    fn sub_auth_env_proxy_url_without_ca_still_writes_https_proxy() {
        let mut settings = serde_json::json!({ "theme": "dark" });
        let proxy = SubAuthProxyEnv {
            proxy_url: "http://127.0.0.1:43117".into(),
            ca_certs: None,
            ca_bundle: None,
        };
        assert_eq!(
            apply_sub_auth_env_with_proxy(&mut settings, true, Some(&proxy)).unwrap(),
            SubAuthEnvChange::Injected
        );
        assert_eq!(settings["env"]["HTTPS_PROXY"], "http://127.0.0.1:43117");
        assert!(settings["env"].get("NODE_EXTRA_CA_CERTS").is_none());
    }

    #[test]
    fn sub_auth_env_does_not_clobber_foreign_https_proxy() {
        let mut settings = serde_json::json!({
            "env": {
                "ANTHROPIC_AUTH_TOKEN": SUB_AUTH_TOKEN_VALUE,
                "HTTPS_PROXY": "http://corp-proxy.example:8080"
            }
        });
        let proxy = sample_proxy();
        assert_eq!(
            apply_sub_auth_env_with_proxy(&mut settings, true, Some(&proxy)).unwrap(),
            SubAuthEnvChange::Injected
        );
        assert_eq!(
            settings["env"]["HTTPS_PROXY"], "http://corp-proxy.example:8080",
            "user corporate proxy left alone"
        );
        // Still adds the CA + NODE_USE_ENV_PROXY bits.
        assert_eq!(settings["env"]["NODE_USE_ENV_PROXY"], "1");
        assert_eq!(
            settings["env"]["NODE_EXTRA_CA_CERTS"],
            "/home/u/.llmtrim/ca.pem"
        );
    }

    #[test]
    fn sub_auth_env_does_not_touch_nonessential_without_our_token() {
        let mut settings = serde_json::json!({
            "env": {
                "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1"
            }
        });
        assert_eq!(
            apply_sub_auth_env_with_proxy(&mut settings, false, None).unwrap(),
            SubAuthEnvChange::Unchanged
        );
        assert_eq!(
            settings["env"]["CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"], "1",
            "user-only flag left alone when our token is absent"
        );
    }

    #[test]
    fn cache_pct_absent_without_current_usage() {
        let cc = parse_cc(
            r#"{"model":{"display_name":"Opus"},"context_window":{"total_input_tokens":100}}"#,
        );
        assert!(
            cc.cache_pct.is_none(),
            "no current_usage ⇒ no cache segment"
        );
    }

    #[test]
    fn parse_cc_tolerates_garbage_and_missing_fields() {
        let cc = parse_cc("not json");
        assert_eq!(cc.model, "?");
        assert_eq!(cc.ctx_tokens, 0);
        assert!(cc.effort.is_none());
    }

    #[test]
    fn context_gauge_handles_extreme_token_counts() {
        // Negative clamps to empty/0k; a pathologically huge count pins full without
        // overflowing i64 (regression: `tokens * width` used to overflow before clamping).
        assert!(context_segment(-5000, 200_000, false, false).starts_with("░░░░░░░░ 0k"));
        assert!(context_segment(i64::MAX / 4, 200_000, false, false).starts_with("▓▓▓▓▓▓▓▓"));
    }

    #[test]
    fn cache_cold_parses_timestamps() {
        assert!(!cache_cold("garbage"), "unparseable ⇒ not cold");
        let fresh = chrono::Utc::now().to_rfc3339();
        assert!(!cache_cold(&fresh), "just now ⇒ warm");
        let stale =
            (chrono::Utc::now() - chrono::Duration::seconds(CACHE_TTL_SECS + 60)).to_rfc3339();
        assert!(cache_cold(&stale), "past the TTL ⇒ cold");
    }

    #[cfg(feature = "intercept")]
    #[test]
    fn ts_within_ttl_gates_the_compact_redirect() {
        // The predicate behind `session_cache_warm` (its DB lookup isn't unit-testable). It must be
        // the strict complement of `cache_cold` inside the TTL, but fail the *opposite* way on a bad
        // timestamp: unknown ⇒ not warm ⇒ redirect still fires.
        assert!(
            !ts_within_ttl("garbage"),
            "unparseable ⇒ not warm (redirect)"
        );
        assert!(
            ts_within_ttl(&chrono::Utc::now().to_rfc3339()),
            "just now ⇒ warm"
        );
        let stale =
            (chrono::Utc::now() - chrono::Duration::seconds(CACHE_TTL_SECS + 60)).to_rfc3339();
        assert!(!ts_within_ttl(&stale), "past the TTL ⇒ not warm (redirect)");
        // Every point inside the TTL is warm here and not cold there — no boundary gap/overlap.
        let fresh =
            (chrono::Utc::now() - chrono::Duration::seconds(CACHE_TTL_SECS - 60)).to_rfc3339();
        assert!(
            ts_within_ttl(&fresh) && !cache_cold(&fresh),
            "within TTL: warm, not cold"
        );
        assert!(
            !ts_within_ttl(&stale) && cache_cold(&stale),
            "past TTL: not warm, cold"
        );
    }

    #[test]
    fn effective_window_prefers_reroute_then_blob() {
        let mut l = led(Health::Healthy);
        // Reroute window (backend's real window) wins over the blob's Claude window.
        l.reroute_window = Some(262_144);
        assert_eq!(effective_window(&cc(0), &l), 262_144);
        // No reroute ⇒ the blob's context_window_size.
        l.reroute_window = None;
        assert_eq!(effective_window(&cc(0), &l), 200_000);
        // Neither ⇒ the default floor.
        let mut c = cc(0);
        c.window = None;
        assert_eq!(effective_window(&c, &l), CTX_WINDOW_DEFAULT);
    }
}