itok 0.3.2

context-cost estimator: token and window budgets for files and changes
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
//! The `rate` command: pre-formatted throughput string for a statusline
//! badge (V46). Report-only, exit 0 (V5). Aggregates, never verdicts
//! (V59). Per-metric ANSI color from `itok.toml` (V109).

use crate::args::Format;
use crate::cli::Output;
use crate::session::Session;
use crate::tracecmd::{Origin, value};
use std::path::{Path, PathBuf};

#[derive(Default)]
struct Raw {
    session: Option<String>,
    /// `None` = not asked for, so the DEFAULT still applies -- which is
    /// `auto` normally and `always` under `--statusline`. An explicit
    /// `--color` therefore wins regardless of flag order, instead of the
    /// two settings racing.
    color: Option<ColorMode>,
    format: Format,
    chdir: Option<String>,
    statusline: bool,
    /// The model the SESSION runs, from the statusline payload. Not a
    /// flag: `rate` is handed a payload naming the session it renders,
    /// so the capacity the gauge is drawn against is that session's and
    /// never one the caller had to remember to pass (V114).
    model: Option<String>,
}

#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
enum ColorMode {
    #[default]
    Auto,
    Always,
    Never,
}

#[derive(Default)]
struct RateConfig {
    /// A compaction point declared by hand, which WINS over the one
    /// observed in the session: a user who measured their own harness
    /// has said something itok cannot contradict from one transcript.
    ///
    /// Keyed by model where the config says so (V121), because the point
    /// is not one number: ~167k on a 200k window against ~969k-1,001k on
    /// a 1M one.
    compact: Option<Compact>,
    turn: Option<Threshold>,
    total: Option<Threshold>,
    hour: Option<Threshold>,
    day: Option<Threshold>,
}

/// A declared compaction point: one number for every model, or a table
/// keyed by the model the payload names (V121).
///
/// Two forms rather than one, because each is obvious for its case: a
/// repo pinned to a single model writes `compact = N`, and a repo that
/// sees several writes the table. Untagged, which works because TOML is
/// self-describing -- proven against `basic-toml` before this was
/// specced, rather than assumed of it (V106's lesson, applied to a
/// parser).
#[derive(serde::Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(untagged)]
enum Compact {
    /// `compact = 968887` -- every model, whatever the session runs.
    Every(u64),
    /// `[rate.compact]` -- only the models it names.
    PerModel(std::collections::BTreeMap<String, u64>),
}

impl Compact {
    /// The point for this session's model, or `None`.
    ///
    /// An UNLISTED model gets no opinion: not a nearest neighbour, not
    /// the first entry, not a mean. It falls through to the session's own
    /// record (V116), which is the honest answer and the one that cannot
    /// go stale. A threshold guessed from a different model is V2 wearing
    /// a config file.
    /// The FULL id is tried first and the base id only after it, for the
    /// reason spelled out on `models::base_id`: a `[1m]` variant compacts
    /// somewhere else entirely, so an entry naming it outright outranks
    /// the bare one. Without the fallback a suffixed id matched NOTHING
    /// here, fell past the capacity rung too, and left the badge with no
    /// red line at all -- which reads as a calm absolute band rather than
    /// as the missing measurement it is.
    fn point(&self, model: Option<&str>) -> Option<u64> {
        match self {
            Self::Every(n) => Some(*n),
            Self::PerModel(table) => {
                let name = model?;
                table
                    .get(name)
                    .or_else(|| table.get(crate::models::base_id(name)))
                    .copied()
            }
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Threshold {
    green: u64,
    amber: u64,
}

#[derive(serde::Deserialize, Default)]
struct TomlConfig {
    rate: Option<TomlRate>,
}

#[derive(serde::Deserialize, Default)]
struct TomlRate {
    compact: Option<Compact>,
    turn: Option<TomlThreshold>,
    total: Option<TomlThreshold>,
    hour: Option<TomlThreshold>,
    day: Option<TomlThreshold>,
}

#[derive(serde::Deserialize)]
struct TomlThreshold {
    green: u64,
    amber: u64,
}

/// The three quantities a reader keeps confusing, kept APART (V117/V118).
/// Each is `None` when NO turn carried the field, never 0 (V47).
#[derive(Default, Debug, Clone, Copy)]
struct Split {
    entered: Option<u64>,
    cache_read: Option<u64>,
    output: Option<u64>,
}

/// The two rate families. `growth_*` is what the badge shows and what
/// predicts a compaction; `per_*` is the gross bill's rate, kept because
/// json published it and a key's meaning does not move under a consumer
/// (V9).
#[derive(Default, Debug, Clone, Copy)]
struct Rates {
    per_hour: Option<u64>,
    per_day: Option<u64>,
    growth_hour: Option<u64>,
    growth_day: Option<u64>,
}

struct Throughput {
    /// `None` when the last turn carried no usage: absent, not zero (V47).
    last_turn: Option<u64>,
    total: u64,
    /// Sum of positive window deltas: what actually entered (V117).
    growth: u64,
    rates: Rates,
    split: Split,
    turns: usize,
    age_seconds: u64,
    active_seconds: u64,
    /// The lowest auto-compaction point this session recorded, or
    /// `None` when it has never compacted (V116).
    compact_at: Option<u64>,
    /// How many observations that point rests on. Published beside it
    /// because a threshold from one sighting and one from six are
    /// different claims (V3).
    compact_n: usize,
}

pub(crate) fn rate(rest: &[String], input: crate::cli::Input) -> Output {
    match parse(rest) {
        Ok(mut raw) => {
            if raw.statusline
                && let Err(o) = adopt_payload(&mut raw, input)
            {
                return o;
            }
            run(&raw)
        }
        Err(e) => Output::usage_err(format!("itok: {e}")),
    }
}

/// Take the session and directory from the harness's statusline payload.
///
/// Read HERE and not in `run`, so `input()` is called only when the flag
/// asked for it: a bare `itok rate` must never block waiting on a pipe
/// nobody is writing to.
///
/// An explicit positional session still wins -- the flag SUPPLIES a
/// default source, it does not seize one the caller named.
fn adopt_payload(
    raw: &mut Raw,
    input: crate::cli::Input,
) -> Result<(), Output> {
    let payload = crate::hook::statusline(&input());
    let Some(transcript) = payload.transcript else {
        return Err(Output::usage_err(
            "itok: --statusline: no `transcript_path` in the payload on stdin"
                .to_owned(),
        ));
    };
    raw.session.get_or_insert(transcript);
    if let Some(cwd) = payload.cwd {
        raw.chdir.get_or_insert(cwd);
    }
    raw.model = payload.model;
    Ok(())
}

fn run(raw: &Raw) -> Output {
    let (session, compactions, origin) = match session_of(raw) {
        Ok(v) => v,
        Err(o) => return o,
    };
    let Some(tp) = throughput(&session, &compactions) else {
        return too_few(raw, &session, &compactions);
    };
    format_output(raw, &tp, &origin)
}

/// A session too short to have a rate, answered in the SHAPE the caller
/// asked for.
///
/// The badge hides (SPEC section I: 0-1 turns = empty output) because a
/// statusline widget announcing its own silence is worse than no widget.
/// That rule is about the BADGE, and it was governing json too: `rate
/// <session> --format json` emitted zero bytes at exit 0, so a consumer
/// piping into `jq` got a parse error rather than an answer.
///
/// json therefore gets one object with the keys it always has and `null`
/// where nothing was measured -- V9's one-shape rule, and the same answer
/// `calibrate` already gives when its sample cannot support a fit ("keys
/// stay so a parser learns one shape, and `null` is json's own word for
/// not measured"). One verb answering this differently from its sibling is
/// B11's class, and this is the sibling it had not reached.
fn too_few(
    raw: &Raw,
    session: &Session,
    compactions: &[crate::session::Compaction],
) -> Output {
    match raw.format {
        Format::Json => {
            Output::ok(json(&unmeasured(session, compactions), None))
        }
        Format::Human => Output::ok(String::new()),
    }
}

/// What a session too short to have a rate DID show: its turn count and
/// the tokens it billed. Everything the sample cannot support is `None`.
fn unmeasured(
    session: &Session,
    compactions: &[crate::session::Compaction],
) -> Throughput {
    Throughput {
        last_turn: last_billed(session),
        total: session.billed_input(),
        growth: crate::session::growth(&session.turns),
        rates: Rates::default(),
        split: split_of(session),
        turns: session.turns.len(),
        age_seconds: 0,
        active_seconds: 0,
        compact_at: crate::session::compact_point(compactions),
        compact_n: crate::session::auto_compactions(compactions).count(),
    }
}

fn format_output(raw: &Raw, tp: &Throughput, origin: &Origin) -> Output {
    let note = crate::tracecmd::origin_note(origin);
    let config = load_config(raw.chdir.as_deref());
    let color = want_color(color_of(raw));
    let gauge = gauge_of(raw, tp, &config);
    Output::ok(match raw.format {
        Format::Json => json(tp, gauge.eta),
        Format::Human if raw.statusline => {
            badge(human(tp, &config, color, gauge))
        }
        Format::Human => human(tp, &config, color, gauge) + &note,
    })
}

/// What the gauge knows: where the red line is, and how much active work
/// the context has before it gets there (V119).
///
/// Read ONCE and carried, because the badge and the json object must not
/// disagree about the same session -- and they would, cheaply, if each
/// re-derived it from a config file the other had also read.
#[derive(Default, Debug, Clone, Copy)]
struct Gauge {
    limit: Option<u64>,
    eta: Option<u64>,
}

fn gauge_of(raw: &Raw, tp: &Throughput, config: &RateConfig) -> Gauge {
    let limit = red_line(raw, tp, config);
    Gauge {
        limit,
        eta: tp.last_turn.and_then(|used| {
            crate::eta::seconds(used, limit, tp.rates.growth_hour)
        }),
    }
}

/// Where the gauge turns full red: the point this level is heading for.
///
/// The ladder is V114's, most specific first. A hand-declared
/// `[rate].compact` is a user's own measurement of their own harness. The
/// session's own record is the harness's (V116). Capacity is the fallback
/// that answers "how full is the tank" when nothing has said where the
/// harness intervenes -- honest, and a different question, which is why it
/// is last rather than first.
///
/// `None` all the way down means no gauge, and V115 then means no colour
/// from it: the badge falls back to whatever `[rate].turn` was declared,
/// and to plain text when that was nothing either.
fn red_line(raw: &Raw, tp: &Throughput, config: &RateConfig) -> Option<u64> {
    let declared = config
        .compact
        .as_ref()
        .and_then(|c| c.point(raw.model.as_deref()));
    declared.or(tp.compact_at).or_else(|| {
        let root =
            std::path::PathBuf::from(raw.chdir.as_deref().unwrap_or("."));
        crate::capacity::or_none(None, raw.model.as_deref(), &root)
    })
}

/// The mode asked for, or the default for how this was invoked.
///
/// `--statusline` defaults to `always` because the harness CAPTURES the
/// string: `auto` probes for a tty, finds none, and would strip the color
/// from every badge -- a default that is right for a pipe is wrong for a
/// display surface being fed through one.
fn color_of(raw: &Raw) -> ColorMode {
    raw.color.unwrap_or(if raw.statusline {
        ColorMode::Always
    } else {
        ColorMode::Auto
    })
}

/// The badge, wrapped for a statusline. Empty stays EMPTY -- a session
/// with nothing to report hides the badge (V3), and `(itok:)` around
/// nothing is a widget announcing its own silence.
///
/// The origin note is dropped here: it explains WHICH session was picked,
/// and under `--statusline` the payload named it outright, so there is no
/// inference left to disclose.
fn badge(line: String) -> String {
    let body = line.trim_end_matches('\n');
    if body.is_empty() {
        return String::new();
    }
    format!("(itok:{body})")
}

fn want_color(mode: ColorMode) -> bool {
    match mode {
        ColorMode::Always => true,
        ColorMode::Never => false,
        ColorMode::Auto => is_tty(),
    }
}

fn session_of(raw: &Raw) -> Result<crate::tracecmd::Loaded, Output> {
    crate::tracecmd::session_with_compactions(
        raw.session.as_deref(),
        raw.chdir.as_deref(),
    )
}

fn throughput(
    session: &Session,
    compactions: &[crate::session::Compaction],
) -> Option<Throughput> {
    if session.turns.len() < 2 {
        return None;
    }
    Some(tp_from(sample_of(session, compactions)?))
}

/// Everything the badge is computed from, read off the session ONCE.
fn sample_of(
    session: &Session,
    compactions: &[crate::session::Compaction],
) -> Option<Sample> {
    let first = session.turns.first()?;
    let last = session.turns.last()?;
    Some(Sample {
        last_turn: last_billed(session),
        total: session.billed_input(),
        growth: crate::session::growth(&session.turns),
        split: split_of(session),
        span: age_seconds(&first.ts, &last.ts),
        active: active_seconds(&session.turns),
        turns: session.turns.len(),
        compact_at: crate::session::compact_point(compactions),
        compact_n: crate::session::auto_compactions(compactions).count(),
    })
}

/// The bill's composition, which is what makes `/bill` readable as a bill
/// rather than as content (V118).
/// The occupancy the badge's first cell reports: the last turn's billed
/// input, or `None` when that turn carried no usage. It used to collapse
/// to 0, which the badge then PRINTED as a confident `0` (#14, V47/V92).
fn last_billed(session: &Session) -> Option<u64> {
    session
        .turns
        .last()
        .and_then(crate::session::Turn::billed_input)
}

fn split_of(session: &Session) -> Split {
    Split {
        entered: session.entered(),
        cache_read: session.cache_read(),
        output: session.output_tokens(),
    }
}

/// What the badge is computed FROM: the two token totals and the two
/// clocks. Grouped because `tp_from` would otherwise take five
/// arguments, and because span and active are easy to swap by accident
/// when they sit side by side as bare `u64`s.
struct Sample {
    last_turn: Option<u64>,
    total: u64,
    growth: u64,
    split: Split,
    span: u64,
    active: u64,
    turns: usize,
    /// V116's red line, carried here so `tp_from` stays the ONE place a
    /// `Throughput` is built from a session.
    compact_at: Option<u64>,
    compact_n: usize,
}

fn tp_from(s: Sample) -> Throughput {
    Throughput {
        last_turn: s.last_turn,
        total: s.total,
        growth: s.growth,
        rates: rates_of(&s),
        split: s.split,
        turns: s.turns,
        age_seconds: s.span,
        active_seconds: s.active,
        compact_at: s.compact_at,
        compact_n: s.compact_n,
    }
}

/// Both rate families over the SAME active clock (V111). Growth is the
/// one the badge shows: it is what a reader can act on, and it is the
/// only one whose sign matches the warning (V117).
fn rates_of(s: &Sample) -> Rates {
    Rates {
        per_hour: rate_over(s.total, s.active, HOUR),
        per_day: rate_over(s.total, s.active, DAY),
        growth_hour: rate_over(s.growth, s.active, HOUR),
        growth_day: rate_over(s.growth, s.active, DAY),
    }
}

/// V111: the working clock -- every gap between consecutive turns, each
/// capped at `IDLE_CAP`, summed. The span between the first and last
/// stamp counts sleep; this counts work, and truncates the gap where a
/// human left rather than guessing whether they did.
///
/// N turns yield N-1 gaps, so the first turn is billed with no time
/// credited and the rate runs high by 1/N -- stated here because a short
/// session is exactly where that shows, and V110 already marks it.
fn active_seconds(turns: &[crate::session::Turn]) -> u64 {
    turns
        .iter()
        .zip(turns.iter().skip(1))
        .map(|(a, b)| gap(&a.ts, &b.ts))
        .fold(0u64, u64::saturating_add)
}

/// One inter-turn gap, credited up to the cap. An unreadable stamp
/// reads 0 here, exactly as it does for the span (V5).
fn gap(before: &str, after: &str) -> u64 {
    parse_ts(after)
        .saturating_sub(parse_ts(before))
        .min(IDLE_CAP)
}

/// The two periods the badge projects onto (V110), and the longest gap
/// credited as work rather than idle (V111 -- 300s is at or above the
/// 95th percentile of the inter-turn gap in every session measured).
const HOUR: u64 = 3_600;
const DAY: u64 = 86_400;
const IDLE_CAP: u64 = 300;

/// A rate, or NOTHING when no working time was measured.
///
/// The floor this replaces was `if active == 0 { 1 }`, and a fabricated
/// one-second denominator is not a conservative default: it multiplies the
/// session total by 3600 and by 86400, so two turns inside one wall-clock
/// second published 104 tokens as `375k/h`. B24 already recorded that exact
/// amplifier -- "the 1-second floor turned that into `132590m/h`" -- and
/// fixed only the stamp reader feeding it. B26 is the floor itself.
///
/// `None` rather than 0, because 0 is a MEASUREMENT (a session that billed
/// nothing) and this is the absence of one. V47/V92 is the rule already
/// written for the case: an absent number is a dash, never a zero. V110's
/// tilde cannot cover it either -- a mark on a fabricated value still asks
/// the reader to believe the digits.
fn rate_over(total: u64, active: u64, period: u64) -> Option<u64> {
    (active > 0).then(|| extrapolate(total, active, period))
}

fn extrapolate(total: u64, age: u64, period: u64) -> u64 {
    total
        .checked_mul(period)
        .and_then(|v| v.checked_div(age))
        .unwrap_or(0)
}

fn age_seconds(first: &str, last: &str) -> u64 {
    parse_ts(last).saturating_sub(parse_ts(first))
}

/// Epoch seconds from the RFC 3339 stamp a transcript carries
/// (`2026-08-15T06:55:39.102Z`). Fixed offsets over that fixed shape, not
/// a date parser and not a calendar crate -- the whole need is one
/// subtraction between two machine-written stamps. A stamp of any other
/// shape reads as 0, so `age_seconds` collapses to 0 and the badge still
/// prints: rate is report-only (V5), and an unreadable clock must not
/// become an error the caller has to handle. Pre-1970 stamps clamp their
/// date to the epoch day for the same reason -- no transcript carries
/// one, so the clamp costs nothing a caller can observe.
fn parse_ts(ts: &str) -> u64 {
    let days = days_from_civil(num(ts, 0..4), num(ts, 5..7), num(ts, 8..10));
    let secs = num(ts, 11..13)
        .saturating_mul(3600)
        .saturating_add(num(ts, 14..16).saturating_mul(60))
        .saturating_add(num(ts, 17..19));
    days.saturating_mul(86_400).saturating_add(secs)
}

/// One fixed-width numeric field, or 0 when it is absent or not a number.
fn num(ts: &str, at: std::ops::Range<usize>) -> u64 {
    ts.get(at).and_then(|s| s.parse().ok()).unwrap_or(0)
}

/// Days since 1970-01-01 for a civil date (Hinnant's `days_from_civil`).
/// Saturating throughout: `arithmetic_side_effects` is denied, and a
/// garbled date must yield a number, never a panic.
fn days_from_civil(y: u64, m: u64, d: u64) -> u64 {
    let shifted = if m <= 2 { y.saturating_sub(1) } else { y };
    let era = shifted.checked_div(400).unwrap_or(0);
    let yoe = shifted.saturating_sub(era.saturating_mul(400));
    era.saturating_mul(146_097)
        .saturating_add(day_of_era(yoe, day_of_year(m, d)))
        .saturating_sub(719_468)
}

/// Day of the year counted from March 1. That shift puts the leap day
/// last, which is what collapses the month lengths to one linear formula.
fn day_of_year(m: u64, d: u64) -> u64 {
    let mp = m.saturating_add(9).checked_rem(12).unwrap_or(0);
    mp.saturating_mul(153)
        .saturating_add(2)
        .checked_div(5)
        .unwrap_or(0)
        .saturating_add(d)
        .saturating_sub(1)
}

/// Day within the 400-year era: whole years, plus their leap days.
fn day_of_era(yoe: u64, doy: u64) -> u64 {
    let leaps = yoe
        .checked_div(4)
        .unwrap_or(0)
        .saturating_sub(yoe.checked_div(100).unwrap_or(0));
    yoe.saturating_mul(365)
        .saturating_add(leaps)
        .saturating_add(doy)
}

/// V108: ceiling, never floor.
pub(crate) fn shorten(n: u64) -> String {
    if n <= 99 {
        n.to_string()
    } else if n <= 999_000 {
        let k = n.saturating_add(999).checked_div(1000).unwrap_or(0);
        format!("{k}k")
    } else {
        let m = n
            .saturating_add(999_999)
            .checked_div(1_000_000)
            .unwrap_or(0);
        format!("{m}m")
    }
}

fn human(
    tp: &Throughput,
    config: &RateConfig,
    color: bool,
    gauge: Gauge,
) -> String {
    let cells = cells_of(tp, config, gauge.limit);
    let mut parts: Vec<String> =
        cells.iter().map(|c| metric(*c, color)).collect();
    parts.extend(gauge.eta.map(estimate));
    format!("{}\n", parts.join(","))
}

/// The 5th cell: time to the red line, floored and tilde'd (V119/V3).
///
/// Uncoloured on purpose. It annotates a cell that is ALREADY carrying
/// the gauge's colour, and a second accent saying the same thing twice is
/// what makes a badge stop being read (V71).
fn estimate(seconds: u64) -> String {
    format!("~{}", crate::eta::duration(seconds))
}

/// The four cells in badge order: the LEVEL, the bill, and the two GROWTH
/// rates (V117). Cells 3 and 4 divide growth rather than the bill, so the
/// number rises when the context is filling instead of when the session
/// is merely long.
fn cells_of(
    tp: &Throughput,
    config: &RateConfig,
    limit: Option<u64>,
) -> [Cell; 4] {
    let age = tp.active_seconds;
    let (hour, day) = (tp.rates.growth_hour, tp.rates.growth_day);
    let gauge = tp
        .last_turn
        .map_or(Paint::None, |used| level(used, limit, config));
    [
        (tp.last_turn, "", "", gauge),
        (Some(tp.total), "/bill", "", band(config.total)),
        (hour, "/h", mark(age, HOUR), band(config.hour)),
        (day, "/d", mark(age, DAY), band(config.day)),
    ]
}

/// How the FIRST cell is painted. It is an occupancy level (V114), so it
/// is drawn as a fraction of what holds it whenever anything can say what
/// that is, and only then falls back to the absolute band a user declared.
fn level(used: u64, limit: Option<u64>, config: &RateConfig) -> Paint {
    match limit.and_then(|l| crate::gauge::fill(used, l)) {
        Some(f) => Paint::Fill(f),
        None => band(config.turn),
    }
}

/// How every OTHER cell is painted: a flow, sorted into a band by the
/// absolute threshold that governs it, and uncoloured without one (V109).
fn band(threshold: Option<Threshold>) -> Paint {
    threshold.map_or(Paint::None, Paint::Band)
}

/// V110: the `~` on a value whose period the SAMPLE does not cover.
///
/// An hour-rate off twenty minutes is a projection, not a measurement,
/// and V3 has marked crude numbers this way since the first estimator.
/// Empty once the age covers the period -- the mark says the sample is
/// short, so it must disappear when the sample stops being short.
fn mark(age: u64, period: u64) -> &'static str {
    if age < period { "~" } else { "" }
}

/// One badge value: the number or its ABSENCE, its suffix, its projection
/// mark, and the thresholds that color it. Grouped because the limit on
/// arguments is four and the mark is the fifth thing every value carries.
type Cell = (Option<u64>, &'static str, &'static str, Paint);

/// What a value's colour MEANS, which is not the same question for every
/// cell on this badge (V114). A flow is sorted into a band; a level is a
/// fraction of a capacity; either can have nothing to say.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Paint {
    None,
    Band(Threshold),
    /// Fill in per-mille, from `gauge::fill`.
    Fill(u64),
}

/// An absent value renders as `-`, uncolored and unmarked (V47/V92).
///
/// Uncolored because a threshold sorts a MEASUREMENT into a band and there
/// is nothing here to sort. Unmarked because V110's `~` says a sample is
/// too short for the period it names, which is a claim about a number that
/// exists.
fn metric(cell: Cell, color: bool) -> String {
    let (value, suffix, mark, paint) = cell;
    let Some(value) = value else {
        return format!("-{suffix}");
    };
    let alarm = match paint {
        Paint::Fill(fill) => crate::gauge::alarm(fill),
        _ => "",
    };
    let text = format!("{alarm}{mark}{}{suffix}", shorten(value));
    colored(text, value, paint, color)
}

fn colored(text: String, value: u64, paint: Paint, color: bool) -> String {
    if !color {
        return text;
    }
    let code = match paint {
        Paint::None => return text,
        Paint::Band(th) => ansi_for(value, th).to_owned(),
        Paint::Fill(fill) => {
            crate::gauge::ansi(fill, crate::gauge::truecolor())
        }
    };
    format!("{code}{text}\x1b[0m")
}

fn ansi_for(value: u64, th: Threshold) -> &'static str {
    if value < th.green {
        "\x1b[32m"
    } else if value < th.amber {
        "\x1b[33m"
    } else {
        "\x1b[31m"
    }
}

/// An unmeasurable rate is `null`, which is what the human badge's `-`
/// says in the shape json has for it (V9/V47). The alternative was a
/// number derived from a one-second denominator nobody measured, sitting
/// beside an `active_seconds` of 0 that contradicts it -- a reader could
/// not reproduce `per_hour` from the object publishing it (B26).
fn or_null(v: Option<u64>) -> String {
    v.map_or_else(|| "null".to_owned(), |n| n.to_string())
}

/// V110 lands here as a BOOLEAN per projected metric, not as a tilde in
/// a numeric field -- json carries the same intent structurally (V9).
///
/// The booleans describe the SAMPLE, not the value, so they stay honest
/// beside a `null`: zero working time covers neither period.
fn json(tp: &Throughput, eta: Option<u64>) -> String {
    format!(
        "{{\"last_turn\":{},\"total\":{},\"per_hour\":{},\
         \"per_day\":{},\"turns\":{},{},{},\"compact_in_active_seconds\":{}}}\n",
        or_null(tp.last_turn),
        tp.total,
        or_null(tp.rates.per_hour),
        or_null(tp.rates.per_day),
        tp.turns,
        json_growth(tp),
        json_clocks(tp),
        or_null(eta),
    )
}

/// Growth, its two rates, and the bill's composition (V117/V118).
///
/// `total` and `per_hour`/`per_day` keep their old meanings above: a
/// consumer's key does not change what it counts under them (V9). The
/// quantities that were being CONFUSED with each other get names of their
/// own here, which is the whole point -- one number nobody could
/// decompose was how the badge published a rate with the wrong sign.
fn json_growth(tp: &Throughput) -> String {
    format!(
        "\"growth\":{},\"growth_per_hour\":{},\"growth_per_day\":{},\
         \"entered\":{},\"cache_read\":{},\"output\":{}",
        tp.growth,
        or_null(tp.rates.growth_hour),
        or_null(tp.rates.growth_day),
        or_null(tp.split.entered),
        or_null(tp.split.cache_read),
        or_null(tp.split.output),
    )
}

/// The two clocks, V110's projection booleans, and the compaction point
/// the gauge was drawn against with the `n` behind it (V116). Split out
/// so neither half outgrows a function anyone can hold in their head.
fn json_clocks(tp: &Throughput) -> String {
    format!(
        "\"age_seconds\":{},\"active_seconds\":{},\
         \"projected_hour\":{},\"projected_day\":{},\
         \"compact_at\":{},\"compact_n\":{}",
        tp.age_seconds,
        tp.active_seconds,
        tp.active_seconds < HOUR,
        tp.active_seconds < DAY,
        or_null(tp.compact_at),
        tp.compact_n,
    )
}

fn load_config(chdir: Option<&str>) -> RateConfig {
    let Some(text) = read_config(chdir) else {
        return RateConfig::default();
    };
    parse_config(&text)
}

fn parse_config(text: &str) -> RateConfig {
    let Ok(config) = basic_toml::from_str::<TomlConfig>(text) else {
        return RateConfig::default();
    };
    let Some(rate) = config.rate else {
        return RateConfig::default();
    };
    config_from(rate)
}

fn config_from(rate: TomlRate) -> RateConfig {
    RateConfig {
        compact: rate.compact,
        turn: rate.turn.map(to_threshold),
        total: rate.total.map(to_threshold),
        hour: rate.hour.map(to_threshold),
        day: rate.day.map(to_threshold),
    }
}

fn to_threshold(t: TomlThreshold) -> Threshold {
    Threshold {
        green: t.green,
        amber: t.amber,
    }
}

fn read_config(chdir: Option<&str>) -> Option<String> {
    let start = PathBuf::from(chdir.unwrap_or("."));
    if let Some(text) =
        project_config(&start).and_then(|p| std::fs::read_to_string(p).ok())
    {
        return Some(text);
    }
    read_global_config()
}

/// V109's "project root wins": the nearest `itok.toml` from `start` up to
/// the git root, inclusive. It read only the working directory, so a
/// session opened in `repo/subdir` silently fell through to the global
/// file (#15). Bounded by the git root so it never reads a PARENT
/// project's config; outside any repository only `start` itself counts.
fn project_config(start: &Path) -> Option<PathBuf> {
    let start = std::fs::canonicalize(start).unwrap_or_else(|_| start.into());
    let top = start.ancestors().find(|d| d.join(".git").exists());
    let bound = top.unwrap_or(&start);
    for dir in start.ancestors() {
        let file = dir.join("itok.toml");
        if file.is_file() {
            return Some(file);
        }
        if dir == bound {
            break;
        }
    }
    None
}

fn read_global_config() -> Option<String> {
    let home = std::env::var("HOME").ok()?;
    let path = std::path::PathBuf::from(home).join(".config/itok/config.toml");
    std::fs::read_to_string(path).ok()
}

/// `auto` asks about the stream the BADGE lands on, which is stdout.
///
/// It probed stderr, and both directions were wrong: `itok rate > badge`
/// from a terminal wrote ANSI escapes into the file, because stderr was
/// still a tty; `itok rate 2>/dev/null` in a terminal stripped the color
/// from a tty stdout. `main.rs` prints `o.out` to stdout and `o.err` to
/// stderr, so the question "will anything render these escapes" is a
/// question about stdout and nothing else.
fn is_tty() -> bool {
    std::io::IsTerminal::is_terminal(&std::io::stdout())
}

fn parse(rest: &[String]) -> Result<Raw, String> {
    let mut raw = Raw::default();
    let mut it = rest.iter();
    while let Some(a) = it.next() {
        apply(a, &mut it, &mut raw)?;
    }
    Ok(raw)
}

fn apply<'a>(
    a: &str,
    it: &mut impl Iterator<Item = &'a String>,
    raw: &mut Raw,
) -> Result<(), String> {
    match a {
        "--bpe" | "--ollama" => {
            return Err(crate::tracecmd::no_real_tier(a, "rate"));
        }
        "--color" => raw.color = Some(parse_color(&value(it, a)?)?),
        "--format" => raw.format = crate::tracecmd::format_of(&value(it, a)?)?,
        "-C" => raw.chdir = Some(value(it, a)?),
        "--statusline" => raw.statusline = true,
        _ => return apply_positional(a, raw),
    }
    Ok(())
}

fn parse_color(s: &str) -> Result<ColorMode, String> {
    match s {
        "auto" => Ok(ColorMode::Auto),
        "always" => Ok(ColorMode::Always),
        "never" => Ok(ColorMode::Never),
        other => Err(format!("unknown color mode '{other}'")),
    }
}

fn apply_positional(a: &str, raw: &mut Raw) -> Result<(), String> {
    if a.starts_with('-') {
        return Err(format!("unknown flag {a}"));
    }
    raw.session = Some(a.to_owned());
    Ok(())
}

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

    const ZERO_RATES: Rates = Rates {
        per_hour: Some(0),
        per_day: Some(0),
        growth_hour: Some(0),
        growth_day: Some(0),
    };

    const ZERO_SPLIT: Split = Split {
        entered: None,
        cache_read: None,
        output: None,
    };

    const ZERO_TP: Throughput = Throughput {
        last_turn: Some(0),
        total: 0,
        growth: 0,
        rates: ZERO_RATES,
        split: ZERO_SPLIT,
        turns: 0,
        age_seconds: 0,
        active_seconds: 0,
        compact_at: None,
        compact_n: 0,
    };

    #[test]
    fn shorten_raw_digits_below_100() {
        assert_eq!(shorten(0), "0");
        assert_eq!(shorten(42), "42");
        assert_eq!(shorten(99), "99");
    }

    #[test]
    fn shorten_ceiling_k_small() {
        assert_eq!(shorten(100), "1k");
        assert_eq!(shorten(900), "1k");
        assert_eq!(shorten(1_000), "1k");
        assert_eq!(shorten(1_001), "2k");
        assert_eq!(shorten(1_500), "2k");
    }

    #[test]
    fn shorten_ceiling_k_large() {
        assert_eq!(shorten(47_000), "47k");
        assert_eq!(shorten(120_000), "120k");
        assert_eq!(shorten(900_000), "900k");
        assert_eq!(shorten(999_000), "999k");
    }

    #[test]
    fn shorten_ceiling_m_range() {
        assert_eq!(shorten(999_001), "1m");
        assert_eq!(shorten(1_000_000), "1m");
        assert_eq!(shorten(1_500_000), "2m");
        assert_eq!(shorten(22_000_000), "22m");
    }

    #[test]
    fn shorten_never_produces_1000k() {
        for n in [999_000, 999_001, 999_499, 999_500, 1_000_000] {
            let s = shorten(n);
            assert!(!s.contains("1000k"), "{n} -> {s}");
        }
    }

    fn session_with_turns(inputs: &[(u64, &str)]) -> Session {
        let mut s = Session::default();
        for (input, ts) in inputs {
            s.turns.push(Turn {
                input: Some(*input),
                ts: (*ts).to_owned(),
                ..Turn::default()
            });
        }
        s
    }

    /// The stamps below are RFC 3339 because that is what a transcript
    /// carries. B-record: the first cut of these fixtures used epoch
    /// digits, which no reader ever writes -- every rate test passed
    /// while `age_seconds` was 0 on every real session.
    const T0: &str = "2026-08-15T06:00:00.000Z";
    const T1H: &str = "2026-08-15T07:00:00.000Z";

    /// The badge hides on a short session; json still answers (V9).
    ///
    /// `--format json` used to emit ZERO BYTES here, so a consumer piping
    /// into `jq` got a parse error while the exit code said success. The
    /// keys are the ones every other `rate` object carries, `null` where
    /// nothing was measured -- the shape `calibrate` already returns when
    /// its own sample is too short.
    #[test]
    fn json_answers_a_short_session_with_an_object() {
        let one = session_with_turns(&[(1_111, "2026-08-22T10:00:00.000Z")]);
        let raw = Raw {
            format: Format::Json,
            ..Raw::default()
        };
        let out = too_few(&raw, &one, &[]).out;
        assert!(out.starts_with('{'), "one object, not silence: {out}");
        assert!(out.contains("\"turns\":1"), "{out}");
        assert!(out.contains("\"last_turn\":1111"), "{out}");
        assert!(out.contains("\"total\":1111"), "{out}");
        assert!(out.contains("\"per_hour\":null"), "{out}");
        assert!(out.contains("\"per_day\":null"), "{out}");
    }

    /// The human badge keeps its silence: a widget rendering `(itok:)`
    /// around nothing announces only itself (V3, section I).
    #[test]
    fn the_badge_stays_hidden_on_a_short_session() {
        let one = session_with_turns(&[(1_111, "2026-08-22T10:00:00.000Z")]);
        let out = too_few(&Raw::default(), &one, &[]).out;
        assert!(out.is_empty(), "badge hides: {out}");
    }

    #[test]
    fn throughput_needs_at_least_two_turns() {
        let s = session_with_turns(&[(1000, T0)]);
        assert!(throughput(&s, &[]).is_none());
        let empty = Session::default();
        assert!(throughput(&empty, &[]).is_none());
    }

    #[test]
    fn throughput_computes_totals() {
        let s = session_with_turns(&[(1_000, T0), (2_000, T1H)]);
        let tp = throughput(&s, &[]);
        assert!(tp.is_some());
        let tp = tp.unwrap_or(ZERO_TP);
        assert_eq!(tp.last_turn, Some(2_000));
        assert_eq!(tp.total, 3_000);
        assert_eq!(tp.turns, 2);
    }

    /// The span stays reported, but it is NOT what divides: one gap of
    /// an hour is credited `IDLE_CAP`, so 3000 tokens over 300 working
    /// seconds is 36k/h (V111).
    #[test]
    fn rates_divide_by_active_time_not_span() {
        let s = session_with_turns(&[(1_000, T0), (2_000, T1H)]);
        let tp = throughput(&s, &[]).unwrap_or(ZERO_TP);
        assert_eq!(tp.age_seconds, 3600, "span still reported");
        assert_eq!(tp.active_seconds, IDLE_CAP, "the gap is capped");
        assert_eq!(tp.rates.per_hour, Some(36_000));
        assert_eq!(tp.rates.per_day, Some(864_000));
    }

    /// Every gap is capped on its own, so a session is the SUM of its
    /// working gaps and one long absence cannot swamp the rest.
    #[test]
    fn each_gap_is_capped_on_its_own() {
        let turns = session_with_turns(&[
            (1, "2026-08-15T06:00:00.000Z"),
            (1, "2026-08-15T06:00:30.000Z"),
            (1, "2026-08-15T06:02:00.000Z"),
            (1, "2026-08-16T06:02:00.000Z"),
            (1, "2026-08-16T06:03:00.000Z"),
        ]);
        let active = active_seconds(&turns.turns);
        assert_eq!(active, 30 + 90 + IDLE_CAP + 60);
    }

    /// A day away counts as `IDLE_CAP`, not as a day: this is the
    /// 337.9h-span session in miniature, whose wall-clock rate
    /// understated the working rate ~20x.
    #[test]
    fn an_absence_is_truncated_not_counted() {
        let s = session_with_turns(&[
            (1_000, "2026-08-15T06:00:00.000Z"),
            (2_000, "2026-08-18T06:00:00.000Z"),
        ]);
        let tp = throughput(&s, &[]).unwrap_or(ZERO_TP);
        assert_eq!(tp.age_seconds, 3 * 86_400, "three days of span");
        assert_eq!(tp.active_seconds, IDLE_CAP, "five minutes of work");
    }

    /// Unreadable stamps leave no working time at all. The clock clamps
    /// so nothing divides by zero, and V110 marks every period the
    /// non-existent sample cannot cover.
    #[test]
    fn an_unreadable_clock_leaves_no_active_time() {
        let s = session_with_turns(&[(1_000, "nope"), (2_000, "also-nope")]);
        let tp = throughput(&s, &[]).unwrap_or(ZERO_TP);
        assert_eq!(tp.active_seconds, 0);
        assert_eq!(tp.rates.per_hour, None, "no working time, no rate");
        assert_eq!(tp.rates.per_day, None);
        let out = human(&tp, &RateConfig::default(), false, Gauge::default());
        assert!(out.contains("-/h") && out.contains("-/d"), "{out}");
        assert!(!out.contains('~'), "nothing to project from: {out}");
    }

    /// B26: a fabricated denominator is not a conservative default.
    ///
    /// The floor here was `if active == 0 { 1 }`, which multiplied the
    /// session total by 3600 and by 86400 -- so 3000 tokens over an
    /// unmeasurable clock published as `10m/h`. This test asserts the
    /// MAGNITUDE, which is what the assertions above it never did: the old
    /// test checked `active_seconds == 0` and that a tilde was present, and
    /// both were true of the garbage.
    #[test]
    fn a_clockless_rate_never_publishes_an_amplified_number() {
        let s = session_with_turns(&[(1_000, "nope"), (2_000, "also-nope")]);
        let tp = throughput(&s, &[]).unwrap_or(ZERO_TP);
        let out = human(&tp, &RateConfig::default(), false, Gauge::default());
        assert!(!out.contains('m'), "no megatoken rate anywhere: {out}");
        let js = json(&tp, None);
        assert!(js.contains("\"per_hour\":null"), "{js}");
        assert!(js.contains("\"per_day\":null"), "{js}");
        assert!(js.contains("\"active_seconds\":0"), "{js}");
    }

    /// The reachable case, with no broken clock in sight: `parse_ts`
    /// truncates to seconds, so two turns inside one wall-clock second --
    /// ordinary at session start -- leave zero active time. Under the old
    /// floor that was the amplifier, not an edge case.
    #[test]
    fn two_turns_in_one_second_publish_no_rate() {
        let s = session_with_turns(&[
            (52, "2026-08-22T10:00:00.100Z"),
            (52, "2026-08-22T10:00:00.900Z"),
        ]);
        let tp = throughput(&s, &[]).unwrap_or(ZERO_TP);
        assert_eq!(tp.active_seconds, 0, "same second, no gap credited");
        assert_eq!(tp.total, 104);
        assert_eq!(tp.rates.per_hour, None, "104 tokens are not 375k/h");
        assert_eq!(tp.rates.per_day, None);
    }

    /// The stamp shape pinned against a value computed elsewhere, so a
    /// reimplementation of `days_from_civil` cannot drift unnoticed.
    #[test]
    fn rfc3339_stamps_become_epoch_seconds() {
        assert_eq!(parse_ts("1970-01-01T00:00:00.000Z"), 0);
        assert_eq!(parse_ts("1970-01-02T00:00:01.000Z"), 86_401);
        assert_eq!(parse_ts("2000-03-01T00:00:00.000Z"), 951_868_800);
        assert_eq!(parse_ts("2026-08-15T06:55:39.102Z"), 1_786_776_939);
    }

    /// The leap day lands on the right side of the March-shift, in a
    /// leap year and in the century year that is NOT one.
    #[test]
    fn leap_days_are_counted() {
        let day = parse_ts("2024-03-01T00:00:00.000Z")
            .saturating_sub(parse_ts("2024-02-29T00:00:00.000Z"));
        assert_eq!(day, 86_400, "2024-02-29 exists");
        let century = parse_ts("2100-03-01T00:00:00.000Z")
            .saturating_sub(parse_ts("2100-02-28T00:00:00.000Z"));
        assert_eq!(century, 86_400, "2100 is not a leap year");
    }

    /// A stamp of any other shape degrades to 0 (V5): no panic, no error.
    /// The epoch-digit case is the exact fixture shape that hid this bug.
    #[test]
    fn an_unreadable_stamp_is_no_age() {
        assert_eq!(parse_ts(""), 0);
        assert_eq!(parse_ts("not-a-timestamp"), 0);
        assert_eq!(parse_ts("1000000000"), 0);
        let pre = parse_ts("1900-06-01T12:00:00.000Z");
        assert!(pre < 86_400, "pre-epoch clamps to the epoch day: {pre}");
    }

    /// The sample here is 3120 seconds: under an hour, so BOTH derived
    /// values are projections and both wear the mark (V110).
    #[test]
    fn human_output_shape() {
        let out = human(
            &sample_tp(),
            &RateConfig::default(),
            false,
            Gauge::default(),
        );
        assert_eq!(out, "3k,46k/bill,~13k/h,~280k/d\n");
    }

    /// The mark is about the DENOMINATOR reaching the period, so it
    /// flips exactly at the period and nowhere else. Both boundaries
    /// pinned from the side that still projects and the side that does
    /// not -- B24 is what a fixture cut to the code costs.
    #[test]
    fn mark_flips_at_the_period_it_names() {
        assert_eq!(mark(3599, HOUR), "~");
        assert_eq!(mark(3600, HOUR), "");
        assert_eq!(mark(86_399, DAY), "~");
        assert_eq!(mark(86_400, DAY), "");
    }

    /// An age that covers the hour but not the day marks the day ALONE:
    /// the two values are judged against their own periods, not against
    /// one verdict for the badge.
    #[test]
    fn a_covered_period_drops_its_mark() {
        let tp = Throughput {
            active_seconds: 7_200,
            ..sample_tp()
        };
        let out = human(&tp, &RateConfig::default(), false, Gauge::default());
        assert_eq!(out, "3k,46k/bill,13k/h,~280k/d\n");
    }

    /// A full day of sample marks nothing -- the badge only tildes what
    /// it had to extrapolate.
    #[test]
    fn a_day_long_sample_marks_nothing() {
        let tp = Throughput {
            active_seconds: 90_000,
            ..sample_tp()
        };
        let out = human(&tp, &RateConfig::default(), false, Gauge::default());
        assert_eq!(out, "3k,46k/bill,13k/h,280k/d\n");
    }

    /// The mark rides INSIDE the colored span: a projected value keeps
    /// its threshold color instead of trading one signal for the other.
    #[test]
    fn a_marked_value_keeps_its_color() {
        let config = RateConfig {
            hour: Some(Threshold {
                green: 1_000,
                amber: 100_000,
            }),
            ..RateConfig::default()
        };
        let out = human(&sample_tp(), &config, true, Gauge::default());
        assert!(out.contains("\x1b[33m~13k/h\x1b[0m"), "{out}");
    }

    /// V114: with a capacity to read against, cell 1 is a GAUGE, and the
    /// gauge is what colours it -- not `[rate].turn`, which is the same
    /// number the old instrument would have called green.
    #[test]
    fn a_level_with_a_limit_is_painted_by_the_gauge() {
        let config = RateConfig {
            turn: Some(Threshold {
                green: 50_000,
                amber: 100_000,
            }),
            ..RateConfig::default()
        };
        let tp = Throughput {
            last_turn: Some(963_000),
            ..sample_tp()
        };
        let out = human(&tp, &config, true, gauge_at(1_000_000));
        assert!(!out.contains("\x1b[32m963k"), "band colour won: {out}");
        assert!(out.contains("!963k"), "alarm mark missing: {out}");
    }

    /// The same level, the same declared threshold, no capacity: the
    /// declared band still applies (V114 keeps it as the fallback rung).
    #[test]
    fn a_level_without_a_limit_falls_back_to_the_declared_band() {
        let config = RateConfig {
            turn: Some(Threshold {
                green: 50_000,
                amber: 100_000,
            }),
            ..RateConfig::default()
        };
        let tp = Throughput {
            last_turn: Some(963_000),
            ..sample_tp()
        };
        let out = human(&tp, &config, true, Gauge::default());
        assert!(out.contains("\x1b[31m963k\x1b[0m"), "{out}");
    }

    /// V115: a zero level is a measurement that went missing, and the
    /// gauge must not paint it as an empty tank. This is the failure the
    /// invariant exists for -- green is the reading nobody re-checks.
    #[test]
    fn a_zero_level_is_never_painted_green_by_the_gauge() {
        let tp = Throughput {
            last_turn: Some(0),
            ..sample_tp()
        };
        let out = human(&tp, &RateConfig::default(), true, gauge_at(1_000_000));
        assert!(!out.contains("\x1b["), "absent level took a colour: {out}");
    }

    /// V115: nothing to say, nothing said.
    #[test]
    fn no_limit_and_no_threshold_leaves_the_level_plain() {
        let out =
            human(&sample_tp(), &RateConfig::default(), true, Gauge::default());
        assert!(!out.contains("\x1b["), "{out}");
    }

    /// V116's ladder, in order. A hand-declared point wins over the
    /// session's own record, which wins over a capacity.
    #[test]
    fn a_declared_compaction_point_wins_over_the_observed_one() {
        let raw = Raw::default();
        let tp = Throughput {
            compact_at: Some(900_000),
            ..sample_tp()
        };
        let config = RateConfig {
            compact: Some(Compact::Every(750_000)),
            ..RateConfig::default()
        };
        assert_eq!(red_line(&raw, &tp, &config), Some(750_000));
        assert_eq!(
            red_line(&raw, &tp, &RateConfig::default()),
            Some(900_000),
            "the session's own record is the next rung"
        );
    }

    /// V121: the table applies only to the models it NAMES.
    #[test]
    fn a_per_model_table_answers_for_the_models_it_lists() {
        let text = "[rate.compact]\n\
             \"claude-opus-5\" = 968887\n\
             \"claude-opus-4-6\" = 167028\n";
        let parsed: TomlConfig = basic_toml::from_str(text).unwrap_or_default();
        let compact = config_from(parsed.rate.unwrap_or_default()).compact;
        let compact = compact.unwrap_or(Compact::Every(0));
        assert_eq!(compact.point(Some("claude-opus-5")), Some(968_887));
        assert_eq!(compact.point(Some("claude-opus-4-6")), Some(167_028));
    }

    /// The rule that matters: an unlisted model gets NO opinion, so it
    /// falls through to the session's own record (V116). Not a nearest
    /// neighbour, not the first entry -- a threshold guessed from a
    /// different model is a wrong number wearing a config file.
    #[test]
    fn an_unlisted_model_gets_no_opinion_from_the_table() {
        let mut table = std::collections::BTreeMap::new();
        table.insert("claude-opus-5".to_owned(), 968_887);
        let compact = Compact::PerModel(table);
        assert_eq!(compact.point(Some("claude-opus-4-6")), None);
        assert_eq!(compact.point(None), None, "no model named at all");
    }

    /// The failure this fallback exists for: the harness names a
    /// context-window variant with a bracketed suffix, so the id arriving
    /// on the payload is `claude-opus-5[1m]` while every config key is
    /// bare. Matching only the full string left the badge with no red
    /// line at all.
    #[test]
    fn a_variant_suffix_falls_back_to_the_base_id() {
        let mut table = std::collections::BTreeMap::new();
        table.insert("claude-opus-5".to_owned(), 968_887);
        let compact = Compact::PerModel(table);
        assert_eq!(compact.point(Some("claude-opus-5[1m]")), Some(968_887));
    }

    /// ...but only as a FALLBACK. A table naming the variant outright is
    /// stating a point for that variant, and it has to beat the base row.
    #[test]
    fn an_entry_for_the_variant_beats_the_base_entry() {
        let mut table = std::collections::BTreeMap::new();
        table.insert("claude-opus-5".to_owned(), 168_000);
        table.insert("claude-opus-5[1m]".to_owned(), 968_887);
        let compact = Compact::PerModel(table);
        assert_eq!(compact.point(Some("claude-opus-5[1m]")), Some(968_887));
        assert_eq!(compact.point(Some("claude-opus-5")), Some(168_000));
    }

    /// The fallback must not invent a base that was never there: an
    /// unlisted model stays unlisted, suffix or no suffix (V121).
    #[test]
    fn a_variant_of_an_unlisted_model_still_gets_no_opinion() {
        let mut table = std::collections::BTreeMap::new();
        table.insert("claude-opus-5".to_owned(), 968_887);
        let compact = Compact::PerModel(table);
        assert_eq!(compact.point(Some("claude-opus-4-6[1m]")), None);
    }

    /// The scalar keeps meaning EVERY model, including a session whose
    /// model the payload never named -- that is what it is for.
    #[test]
    fn the_scalar_form_answers_for_every_model() {
        let compact = Compact::Every(968_887);
        assert_eq!(compact.point(Some("anything")), Some(968_887));
        assert_eq!(compact.point(None), Some(968_887));
    }

    /// End of the ladder, in one test: a table that does not name this
    /// session's model leaves the session's own observation in charge.
    #[test]
    fn an_unlisted_model_falls_through_to_the_sessions_own_record() {
        let mut table = std::collections::BTreeMap::new();
        table.insert("claude-opus-5".to_owned(), 968_887);
        let config = RateConfig {
            compact: Some(Compact::PerModel(table)),
            ..RateConfig::default()
        };
        let raw = Raw {
            model: Some("claude-opus-4-6".to_owned()),
            ..Raw::default()
        };
        let tp = Throughput {
            compact_at: Some(167_028),
            ..sample_tp()
        };
        assert_eq!(red_line(&raw, &tp, &config), Some(167_028));
    }

    /// A session that has never compacted, on a model no table knows,
    /// has no red line at all -- which V115 renders as no colour rather
    /// than as a guess (V92).
    #[test]
    fn no_observation_and_no_table_leaves_no_red_line() {
        let raw = Raw::default();
        assert_eq!(red_line(&raw, &sample_tp(), &RateConfig::default()), None);
    }

    /// The point and the `n` behind it travel together in json (V116):
    /// a threshold from one sighting and one from six are different
    /// claims and a consumer has to be able to tell them apart.
    #[test]
    fn json_carries_the_compaction_point_and_its_n() {
        let tp = Throughput {
            compact_at: Some(968_887),
            compact_n: 2,
            ..sample_tp()
        };
        let js = json(&tp, None);
        assert!(js.contains("\"compact_at\":968887"), "{js}");
        assert!(js.contains("\"compact_n\":2"), "{js}");
    }

    /// An unobserved point is `null`, never 0 -- a zero would draw the
    /// red line at the origin and paint every session red (V47).
    #[test]
    fn an_unobserved_compaction_point_is_null_in_json() {
        let js = json(&sample_tp(), None);
        assert!(js.contains("\"compact_at\":null"), "{js}");
        assert!(js.contains("\"compact_n\":0"), "{js}");
    }

    #[test]
    fn toml_carries_a_compaction_point() {
        let text = "[rate]\ncompact = 968887\n";
        let parsed: TomlConfig = basic_toml::from_str(text).unwrap_or_default();
        let rate = parsed.rate.unwrap_or_default();
        let got = config_from(rate).compact;
        assert_eq!(got.and_then(|c| c.point(None)), Some(968_887));
    }

    /// B30, as a test: a session that keeps taking turns without growing
    /// bills more every turn, and the badge's rate must NOT rise with it.
    /// The bill here is 3x the growth, and the two published rates say so
    /// -- under the old numerator the badge showed the larger one.
    #[test]
    fn a_flat_window_publishes_no_growth_however_long_it_runs() {
        let flat = session_with_turns(&[
            (500_000, T0),
            (500_000, "2026-08-15T06:01:00.000Z"),
            (500_000, "2026-08-15T06:02:00.000Z"),
        ]);
        let tp = throughput(&flat, &[]).unwrap_or(ZERO_TP);
        assert_eq!(tp.growth, 500_000, "only the entry window entered");
        assert_eq!(tp.total, 1_500_000, "the bill counted every re-send");
        let hour = tp.rates.growth_hour.unwrap_or(0);
        let billed = tp.rates.per_hour.unwrap_or(0);
        assert_eq!(billed, hour.saturating_mul(3), "the bill runs 3x here");
        let out = human(&tp, &RateConfig::default(), false, Gauge::default());
        assert!(out.contains(&format!("{}/h", shorten(hour))), "{out}");
        assert!(!out.contains(&format!("{}/h", shorten(billed))), "{out}");
    }

    /// The same clock, real growth: the rate follows the WINDOW, and with
    /// nothing re-billed beyond it the two families coincide.
    #[test]
    fn a_growing_window_publishes_what_it_added() {
        let rising = session_with_turns(&[
            (100_000, T0),
            (400_000, "2026-08-15T06:01:00.000Z"),
        ]);
        let tp = throughput(&rising, &[]).unwrap_or(ZERO_TP);
        assert_eq!(tp.growth, 400_000, "the window it reached");
        assert_eq!(tp.total, 500_000, "what it was billed on the way");
        let out = human(&tp, &RateConfig::default(), false, Gauge::default());
        assert!(out.contains("500k/bill"), "{out}");
    }

    /// V9: the keys a consumer already parses keep counting what they
    /// counted. `total` is still the gross bill and `per_hour` still its
    /// rate -- the new quantities arrive under new names.
    #[test]
    fn json_keeps_the_old_keys_at_their_old_meaning() {
        let js = json(&sample_tp(), None);
        assert!(js.contains("\"total\":45305"), "{js}");
        assert!(js.contains("\"per_hour\":12400"), "{js}");
        assert!(js.contains("\"per_day\":280000"), "{js}");
    }

    /// The three quantities that were being confused, each under its own
    /// name (V117/V118): what grew, what entered, what was re-read.
    #[test]
    fn json_names_growth_and_the_bills_composition() {
        let js = json(&sample_tp(), None);
        assert!(js.contains("\"growth\":6000"), "{js}");
        assert!(js.contains("\"growth_per_hour\":13000"), "{js}");
        assert!(js.contains("\"entered\":9000"), "{js}");
        assert!(js.contains("\"cache_read\":36000"), "{js}");
        assert!(js.contains("\"output\":1200"), "{js}");
    }

    /// V47 reaches the new keys too: a harness that never reported a
    /// field publishes `null`, not 0.
    #[test]
    fn an_unreported_split_field_is_null_rather_than_zero() {
        let tp = Throughput {
            split: Split::default(),
            ..sample_tp()
        };
        let js = json(&tp, None);
        assert!(js.contains("\"entered\":null"), "{js}");
        assert!(js.contains("\"output\":null"), "{js}");
    }

    const SAMPLE_RATES: Rates = Rates {
        per_hour: Some(12_400),
        per_day: Some(280_000),
        growth_hour: Some(13_000),
        growth_day: Some(280_000),
    };

    const SAMPLE_SPLIT: Split = Split {
        entered: Some(9_000),
        cache_read: Some(36_000),
        output: Some(1_200),
    };

    /// `json` with no estimate, which is what a fixture built by hand
    /// has: the red line comes from a config file and a session record,
    /// neither of which a literal `Throughput` carries.
    /// V119: the 5th cell annotates the gauge, so it appears with it.
    /// Floored, tilde'd, and uncoloured -- the cell it annotates is
    /// already carrying the gauge's colour.
    #[test]
    fn the_badge_grows_a_fifth_cell_when_the_gauge_can_date_it() {
        let g = Gauge {
            limit: Some(1_000_000),
            eta: Some(5_400),
        };
        let out = human(&sample_tp(), &RateConfig::default(), false, g);
        assert!(out.ends_with("~1h\n"), "floored to the hour: {out}");
        assert_eq!(out.matches(',').count(), 4, "five cells: {out}");
    }

    /// No red line, no cell. A permanent `-` on a statusline is a widget
    /// announcing its own silence (V71), and there is nothing to be early
    /// for when nothing can say where the line is.
    #[test]
    fn the_badge_stays_four_cells_without_a_red_line() {
        let out = human(
            &sample_tp(),
            &RateConfig::default(),
            false,
            Gauge::default(),
        );
        assert_eq!(out.matches(',').count(), 3, "four cells: {out}");
        assert!(!out.contains('~') || out.contains("/h"), "{out}");
    }

    /// The estimate is read ONCE and carried, so the badge and the json
    /// object cannot disagree about the same session.
    #[test]
    fn the_gauge_dates_the_red_line_from_the_growth_rate() {
        let config = RateConfig {
            compact: Some(Compact::Every(1_000_000)),
            ..RateConfig::default()
        };
        let tp = Throughput {
            last_turn: Some(900_000),
            ..sample_tp()
        };
        let g = gauge_of(&Raw::default(), &tp, &config);
        assert_eq!(g.limit, Some(1_000_000));
        assert_eq!(g.eta, Some(27_692), "100k left at 13k per active hour");
    }

    /// V9: the key is always present, `null` where a refusal applies --
    /// a consumer parses one shape whether or not the estimate exists.
    #[test]
    fn json_always_carries_the_estimate_key() {
        let with = json(&sample_tp(), Some(3_600));
        assert!(
            with.contains("\"compact_in_active_seconds\":3600"),
            "{with}"
        );
        let without = json(&sample_tp(), None);
        assert!(
            without.contains("\"compact_in_active_seconds\":null"),
            "{without}"
        );
    }

    /// A gauge with a red line and no estimate: the tests below are
    /// about the LEVEL colour, and an estimate would put a fifth cell in
    /// every assertion about the first four.
    fn gauge_at(limit: u64) -> Gauge {
        Gauge {
            limit: Some(limit),
            eta: None,
        }
    }

    fn json_of(tp: Throughput) -> String {
        json(&tp, None)
    }

    fn sample_tp() -> Throughput {
        Throughput {
            last_turn: Some(2_117),
            total: 45_305,
            growth: 6_000,
            rates: SAMPLE_RATES,
            split: SAMPLE_SPLIT,
            turns: 22,
            age_seconds: 3120,
            active_seconds: 3120,
            compact_at: None,
            compact_n: 0,
        }
    }

    #[test]
    fn json_is_one_line() {
        let out = json(&sample_tp(), None);
        assert_eq!(out.lines().count(), 1);
        assert!(!out.contains('~'), "no tilde in json (V9)");
    }

    #[test]
    fn json_carries_all_fields() {
        let out = json(&sample_tp(), None);
        assert!(out.contains("\"last_turn\":2117"));
        assert!(out.contains("\"total\":45305"));
        assert!(out.contains("\"per_hour\":12400"));
        assert!(out.contains("\"per_day\":280000"));
    }

    /// A last turn with no `usage` block is ABSENT, not zero (V47/V92,
    /// #14): the badge prints `-` and json `null`, while a turn that
    /// really billed nothing still reads `0` -- the two must stay apart.
    #[test]
    fn an_absent_last_turn_is_a_dash_not_a_zero() {
        let mut s = session_with_turns(&[(1_000, T0)]);
        s.turns.push(Turn {
            ts: T1H.to_owned(),
            ..Turn::default()
        });
        let tp = throughput(&s, &[]).unwrap_or(ZERO_TP);
        assert_eq!(tp.last_turn, None);
        let cfg = RateConfig::default();
        let out = human(&tp, &cfg, false, Gauge::default());
        assert!(out.starts_with("-,"), "{out}");
        assert!(json_of(tp).contains("\"last_turn\":null"));
    }

    #[test]
    fn a_last_turn_that_billed_zero_still_reads_zero() {
        let s = session_with_turns(&[(1_000, T0), (0, T1H)]);
        let tp = throughput(&s, &[]).unwrap_or(ZERO_TP);
        assert_eq!(tp.last_turn, Some(0));
        let cfg = RateConfig::default();
        let out = human(&tp, &cfg, false, Gauge::default());
        assert!(out.starts_with("0,"), "{out}");
        assert!(json_of(tp).contains("\"last_turn\":0,"));
    }

    /// V110 in json is a boolean per metric (V9), and it tracks the same
    /// boundary the tilde does.
    #[test]
    fn json_flags_each_projection() {
        let short = json(&sample_tp(), None);
        assert!(short.contains("\"projected_hour\":true"), "{short}");
        assert!(short.contains("\"projected_day\":true"), "{short}");
        let long = json_of(Throughput {
            active_seconds: 90_000,
            ..sample_tp()
        });
        assert!(long.contains("\"projected_hour\":false"), "{long}");
        assert!(long.contains("\"projected_day\":false"), "{long}");
    }

    #[test]
    fn color_applied_when_threshold_present() {
        let th = Some(Threshold {
            green: 50_000,
            amber: 100_000,
        });
        let green = colored("1k".to_owned(), 1_000, band(th), true);
        assert!(green.contains("\x1b[32m"), "green: {green}");
        let amber = colored("60k".to_owned(), 60_000, band(th), true);
        assert!(amber.contains("\x1b[33m"), "amber: {amber}");
        let red = colored("120k".to_owned(), 120_000, band(th), true);
        assert!(red.contains("\x1b[31m"), "red: {red}");
    }

    #[test]
    fn color_absent_without_threshold() {
        let out = colored("1k".to_owned(), 1_000, Paint::None, true);
        assert!(!out.contains('\x1b'), "no ANSI without threshold");
    }

    /// `auto` follows STDOUT, which is where the badge is printed.
    ///
    /// Under the test harness stdout is captured, never a terminal, so the
    /// verdict is a known false -- and that is the direction that matters:
    /// escapes must not land in a pipe or a file. The probe used to read
    /// stderr, which is a different stream with a different answer, and
    /// nothing asserted the verdict at all (only that the branch ran).
    #[test]
    fn auto_reads_the_stream_the_badge_is_written_to() {
        let piped = !std::io::IsTerminal::is_terminal(&std::io::stdout());
        assert!(piped, "the harness captures stdout");
        assert!(!want_color(ColorMode::Auto), "no escapes into a pipe");
        assert!(want_color(ColorMode::Always));
        assert!(!want_color(ColorMode::Never));
    }

    #[test]
    fn color_absent_when_disabled() {
        let th = Some(Threshold {
            green: 50_000,
            amber: 100_000,
        });
        let out = colored("1k".to_owned(), 1_000, band(th), false);
        assert!(!out.contains('\x1b'), "no ANSI when color=false");
    }

    #[test]
    fn toml_config_parses() {
        let text = r#"
[rate]
turn = { green = 50000, amber = 100000 }
total = { green = 1000000, amber = 5000000 }
"#;
        let parsed: TomlConfig = basic_toml::from_str(text).unwrap_or_default();
        let rate = parsed.rate.unwrap_or_default();
        assert_eq!(rate.turn.as_ref().map(|t| t.green), Some(50000));
        assert_eq!(rate.turn.as_ref().map(|t| t.amber), Some(100000));
        assert_eq!(rate.total.as_ref().map(|t| t.green), Some(1000000));
        assert!(rate.hour.is_none());
    }

    #[test]
    fn malformed_toml_degrades_silently() {
        let text = "this is not valid toml [[[";
        let parsed: Result<TomlConfig, _> = basic_toml::from_str(text);
        assert!(parsed.is_err());
    }

    /// The whole verb over a real one-turn transcript, so `run`'s short
    /// session branch is exercised by a PLANTED file rather than by
    /// whichever transcripts the machine running coverage happens to hold
    /// (B3, and B27's spread).
    #[test]
    fn a_one_turn_transcript_answers_in_both_formats() {
        let path = fixture("minimal.jsonl");
        let human = super::rate(std::slice::from_ref(&path), &nothing);
        assert!(human.out.is_empty(), "badge hides: {:?}", human.out);
        assert_eq!(human.code, 0);
        let js = super::rate(
            &[path, "--format".to_owned(), "json".to_owned()],
            &nothing,
        );
        assert!(js.out.starts_with('{'), "one object: {:?}", js.out);
        assert!(js.out.contains("\"per_hour\":null"), "{}", js.out);
    }

    /// The two config fallbacks that are NOT a missing file: malformed
    /// TOML, and valid TOML with no `[rate]` table. Both degrade to the
    /// default silently, because colour is cosmetic and a broken config
    /// must not break the measurement (V109).
    #[test]
    fn a_broken_or_rateless_config_degrades_to_the_default() {
        let broken = parse_config("[rate\nturn = oops");
        assert!(broken.turn.is_none() && broken.hour.is_none());
        let rateless = parse_config("[limits]\nsrc = 1000\n");
        assert!(rateless.turn.is_none() && rateless.day.is_none());
    }

    /// A planted tree under the temp dir, fresh per test (B5: no two
    /// tests share a path, so the suite stays parallel).
    fn planted(name: &str, dirs: &[&str], files: &[&str]) -> PathBuf {
        let root = std::env::temp_dir().join(format!("itok-cfg-{name}"));
        let _ = std::fs::remove_dir_all(&root);
        for d in dirs {
            let _ = std::fs::create_dir_all(root.join(d));
        }
        for f in files {
            let _ = std::fs::write(root.join(f), "[rate]\n");
        }
        // Canonical, because the search is: macOS's temp dir is a symlink.
        std::fs::canonicalize(&root).unwrap_or(root)
    }

    /// V109: the PROJECT root wins, not the working directory -- a
    /// session started in `repo/subdir` still reads `repo/itok.toml` (#15).
    #[test]
    fn config_is_found_above_a_subdirectory_up_to_the_git_root() {
        let root =
            planted("up", &["repo/.git", "repo/a/b"], &["repo/itok.toml"]);
        let found = project_config(&root.join("repo/a/b"));
        assert_eq!(found, Some(root.join("repo/itok.toml")));
    }

    #[test]
    fn the_nearest_config_wins() {
        let root = planted(
            "near",
            &["repo/.git", "repo/a/b"],
            &["repo/itok.toml", "repo/a/itok.toml"],
        );
        let found = project_config(&root.join("repo/a/b"));
        assert_eq!(found, Some(root.join("repo/a/itok.toml")));
    }

    /// The search stops at the git root, so it cannot wander into a
    /// PARENT project's config.
    #[test]
    fn the_search_never_crosses_the_git_root() {
        let root = planted(
            "bound",
            &["outer/inner/.git", "outer/inner/a"],
            &["outer/itok.toml"],
        );
        assert_eq!(project_config(&root.join("outer/inner/a")), None);
    }

    /// Outside any repository there is no root to walk to, so only the
    /// directory itself is read -- the old behaviour, now the bounded one.
    #[test]
    fn outside_a_repository_only_the_directory_itself_is_read() {
        let root = planted("norepo", &["top/a"], &["top/itok.toml"]);
        assert_eq!(project_config(&root.join("top/a")), None);
        let here = project_config(&root.join("top"));
        assert_eq!(here, Some(root.join("top/itok.toml")));
    }

    /// `rate` has no tokenizer tiers to pick from, so the flags that name
    /// one are a usage error naming the verb (V64's shared message).
    #[test]
    fn tier_flags_are_rejected_by_name() {
        for flag in ["--bpe", "--ollama"] {
            let out = super::rate(&[flag.to_owned()], &nothing);
            assert_eq!(out.code, 2, "{flag} is a usage error");
            assert!(out.err.contains("rate"), "names the verb: {}", out.err);
        }
    }

    fn fixture(name: &str) -> String {
        format!(
            "{}/tests/fixtures/session/{name}",
            env!("CARGO_MANIFEST_DIR")
        )
    }

    fn nothing() -> String {
        String::new()
    }

    /// Every test below drives the verb through an input source of its
    /// own. Shadowing the real `rate` keeps that from being something
    /// each test has to remember.
    fn rate(args: &[String]) -> Output {
        super::rate(args, &nothing)
    }

    fn payload(transcript: &str, cwd: &str) -> String {
        format!(
            "{{\"session_id\":\"s1\",\"transcript_path\":\"{transcript}\",\
             \"cwd\":\"{cwd}\",\"model\":{{\"id\":\"claude\"}}}}"
        )
    }

    /// The payload names the transcript, and the badge reports THAT one.
    #[test]
    fn statusline_reads_the_transcript_from_the_payload() {
        let text = payload(&fixture("tool-shapes.jsonl"), "/tmp");
        let src = || text.clone();
        let out = super::rate(&["--statusline".to_owned()], &src);
        assert_eq!(out.code, 0);
        assert!(out.out.starts_with("(itok:"), "wrapped: {:?}", out.out);
        assert!(out.out.ends_with(')'), "wrapped: {:?}", out.out);
    }

    /// The harness captures the string, so there is no tty to detect and
    /// `auto` would strip every badge's color. Default is `always`.
    #[test]
    fn statusline_colors_by_default() {
        let dir = std::env::temp_dir().join("itok-rate-statusline");
        let _ = std::fs::create_dir_all(&dir);
        let _ = std::fs::write(
            dir.join("itok.toml"),
            "[rate]\nturn = { green = 1, amber = 2 }\n",
        );
        let text =
            payload(&fixture("tool-shapes.jsonl"), &dir.display().to_string());
        let src = || text.clone();
        let out = super::rate(&["--statusline".to_owned()], &src);
        assert!(out.out.contains('\x1b'), "ANSI by default: {:?}", out.out);
    }

    /// An explicit `--color` still wins -- the flag supplies a DEFAULT,
    /// it does not seize the setting.
    #[test]
    fn an_explicit_color_beats_the_statusline_default() {
        let text = payload(&fixture("tool-shapes.jsonl"), "/tmp");
        let src = || text.clone();
        let args = ["--statusline", "--color", "never"];
        let out = super::rate(
            &args.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>(),
            &src,
        );
        assert!(!out.out.contains('\x1b'), "explicit never: {:?}", out.out);
    }

    /// A payload with no transcript is a usage error, not a guess: the
    /// whole point of the flag is that the session is NAMED (V104).
    #[test]
    fn a_payload_without_a_transcript_is_a_usage_error() {
        let src = || "{\"session_id\":\"s1\"}".to_owned();
        let out = super::rate(&["--statusline".to_owned()], &src);
        assert_eq!(out.code, 2);
        assert!(out.err.contains("transcript_path"), "{:?}", out.err);
        assert!(out.out.is_empty(), "statusline renders nothing");
    }

    /// The guarantee that keeps a bare `itok rate` from blocking on a
    /// terminal: without the flag, the input source is never touched.
    #[test]
    fn stdin_is_read_only_under_the_flag() {
        let seen = std::cell::Cell::new(false);
        let src = || {
            seen.set(true);
            String::new()
        };
        let _ = super::rate(&[fixture("tool-shapes.jsonl")], &src);
        assert!(!seen.get(), "bare rate must not read stdin");
        let _ = super::rate(&["--statusline".to_owned()], &src);
        assert!(seen.get(), "--statusline must read stdin");
    }

    /// Nothing to report hides the badge entirely -- `(itok:)` wrapped
    /// around nothing is a widget announcing its own silence (V3).
    #[test]
    fn an_empty_rate_produces_no_badge() {
        assert_eq!(badge(String::new()), "");
        assert_eq!(badge("\n".to_owned()), "");
        assert_eq!(badge("1k,2k/total\n".to_owned()), "(itok:1k,2k/total)");
    }

    #[test]
    fn rate_on_fixture_exits_zero() {
        let out = rate(&[fixture("tool-shapes.jsonl")]);
        assert_eq!(out.code, 0, "report-only (V5)");
    }

    #[test]
    fn rate_json_on_fixture() {
        let out = rate(&[
            fixture("tool-shapes.jsonl"),
            "--format".to_owned(),
            "json".to_owned(),
        ]);
        assert_eq!(out.code, 0);
        assert!(out.out.contains("\"last_turn\":"));
        assert!(out.out.contains("\"turns\":"));
    }

    #[test]
    fn rate_with_color_never() {
        let out = rate(&[
            fixture("tool-shapes.jsonl"),
            "--color".to_owned(),
            "never".to_owned(),
        ]);
        assert_eq!(out.code, 0);
        assert!(!out.out.contains('\x1b'), "no ANSI with --color never");
    }

    #[test]
    fn a_named_miss_is_a_usage_error() {
        let out = rate(&["/nonexistent/s.jsonl".to_owned()]);
        assert_eq!(out.code, 2);
    }

    #[test]
    fn unknown_flags_are_usage_errors() {
        assert_eq!(rate(&["--nope".to_owned()]).code, 2);
        assert_eq!(rate(&["--color".to_owned(), "rainbow".to_owned()]).code, 2);
        assert_eq!(rate(&["--format".to_owned(), "yaml".to_owned()]).code, 2);
    }

    /// Both clocks are in json: the span the session covered, and the
    /// working time that divides (V111). A reader who wants to know why
    /// a rate looks high can see the two apart.
    #[test]
    fn json_carries_both_clocks() {
        let out = json_of(Throughput {
            age_seconds: 300_000,
            active_seconds: 3_120,
            ..sample_tp()
        });
        assert!(out.contains("\"age_seconds\":300000"), "{out}");
        assert!(out.contains("\"active_seconds\":3120"), "{out}");
    }
}