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
//! The `top` command: ranked context occupancy (V46). `du`/`top`-shaped
//! -- `-h`, `-s`, `--top N` mean what they mean there (V1). Per-path
//! attribution is `top -- <path>`, which is why there is no `blame` verb:
//! `git blame` is per-LINE authorship, and the almost-match would cost
//! more than the flag (V2).
//!
//! Report-only, exit 0 (V5). Every column is ARITHMETIC -- how much, how
//! often, how long ago. Whether that is healthy is judgment, and judgment
//! belongs to `doctor` (V59).
//!
//! `stale` is turns-since-last-load; `carried` is the compounding-cost
//! story it used to refuse. The multiplication was withheld while its
//! premise -- that every one of those turns re-sent the item -- was an
//! assumption the transcript did not record per item. It is now OBSERVED:
//! `cache_read` is the whole window on every warm turn and the window
//! only grows, so an item entering at turn N of T really does carry
//! ~`size x (T-N)` of cache-read billing (V98). Reported with the caveat
//! it rests on: UNCOMPACTED sessions, which is all that has been seen.
//!
//! Charged PER LOAD EVENT, never as the summed total times the earliest
//! entry: a re-read enters later and carries fewer remaining turns, so
//! the shortcut would overcount exactly the paths that repeat most.
//!
//! It earns a column because it is the number that makes EARLY reduction
//! visible (V94): the value of dropping something is `size x turns
//! remaining`, not its one-time load cost.
//!
//! Sizes are `bytes/4` estimates for the same reason as `trace`: no
//! content is retained (V45), so there is nothing for a real tokenizer to
//! count.

use crate::args::Format;
use crate::cli::Output;
use crate::json::escape;
use crate::render::{Style, human};
use crate::session::{LoadEvent, Session};
use crate::tracecmd::value;
use std::collections::BTreeMap;

#[derive(Default)]
struct Raw {
    session: Option<String>,
    path: Option<String>,
    top: Option<String>,
    cost: bool,
    model: Option<String>,
    style: Style,
    format: Format,
    chdir: Option<String>,
}

/// One ranked line: what was loaded, how much, how often, how stale, and
/// how much re-billing it has carried since it entered (V98).
pub(crate) struct Row {
    pub(crate) what: String,
    pub(crate) tokens: u64,
    loads: usize,
    stale: usize,
    carried: u64,
}

pub(crate) fn top(rest: &[String]) -> Output {
    match parse(rest) {
        Ok(raw) => run(&raw),
        Err(e) => Output::usage_err(format!("itok: {e}")),
    }
}

fn run(raw: &Raw) -> Output {
    // Unreadable is NOT the same as empty: printing a zero total would
    // read as a measurement of nothing, when in fact nothing was read
    // (V47's rule -- absent must stay distinguishable from zero). This
    // comment used to sit above two silent `ok("")` returns that did
    // exactly what it forbids; V104 now binds them (B14).
    let read = crate::tracecmd::session_with_compactions(
        raw.session.as_deref(),
        raw.chdir.as_deref(),
    );
    let (parsed, compactions, _) = match read {
        Ok(v) => v,
        Err(o) => return o,
    };
    render(raw, &parsed, &compactions)
}

/// The report, once the session is in hand. A bad `--model` is a usage
/// error rather than a missing line: V11's unknown-model rule reaches the
/// rate column too.
fn render(
    raw: &Raw,
    parsed: &Session,
    compactions: &[crate::session::Compaction],
) -> Output {
    let cost = match cost_line(parsed, raw) {
        Ok(line) => line,
        Err(e) => return Output::usage_err(format!("itok: {e}")),
    };
    let rows = rank(parsed, raw);
    let caveat = Caveat::of(compactions);
    Output::ok(match raw.format {
        Format::Json => json(&rows, parsed, caveat),
        Format::Human => report(&rows, parsed, &raw.style, caveat) + &cost,
    })
}

/// Group, then order by occupancy. `--top N` truncates AFTER ranking, so
/// it keeps the biggest rather than the first (V46, `du --top`'s intent).
fn rank(parsed: &Session, raw: &Raw) -> Vec<Row> {
    let events = filtered(&parsed.events, raw.path.as_deref());
    let mut rows = group(&events, &turn_times(parsed));
    rows.sort_by(|a, b| b.tokens.cmp(&a.tokens).then(a.what.cmp(&b.what)));
    if let Some(n) = raw.top.as_ref().and_then(|n| n.parse::<usize>().ok()) {
        rows.truncate(n);
    }
    rows
}

/// The same ranking `top` prints, for a caller that wants the rows rather
/// than the report (V64).
///
/// `doctor --session` needs occupancy per item to project it forward
/// (V99: every figure comes from `headroom` or `top`, never a new
/// estimator). It takes the ranking WITHOUT `--top`, because truncation
/// is a display choice and the caller has its own.
pub(crate) fn ranked(parsed: &Session) -> Vec<Row> {
    let events: Vec<&LoadEvent> = parsed.events.iter().collect();
    let mut rows = group(&events, &turn_times(parsed));
    rows.sort_by(|a, b| b.tokens.cmp(&a.tokens).then(a.what.cmp(&b.what)));
    rows
}

/// `-- <path>` restricts to one path's loads: per-path attribution
/// without a second verb (V46).
fn filtered<'a>(
    events: &'a [LoadEvent],
    want: Option<&str>,
) -> Vec<&'a LoadEvent> {
    events
        .iter()
        .filter(|e| want.is_none_or(|p| e.path.as_deref() == Some(p)))
        .collect()
}

/// Turn timestamps, ascending -- the ruler `stale` is measured against.
fn turn_times(parsed: &Session) -> Vec<String> {
    let mut ts: Vec<String> =
        parsed.turns.iter().map(|t| t.ts.clone()).collect();
    ts.sort();
    ts
}

/// Sum by identity: the path when a load names one, else the source in
/// parens. One column, one meaning -- a shell command genuinely has no
/// path, and inventing one would be a confident lie (V3).
fn group(events: &[&LoadEvent], turns: &[String]) -> Vec<Row> {
    let mut acc: BTreeMap<String, Sum> = BTreeMap::new();
    for e in events {
        acc.entry(identity(e)).or_default().absorb(e, turns);
    }
    acc.into_iter()
        .map(|(what, s)| Row {
            what,
            tokens: s.tokens,
            loads: s.loads,
            stale: turns_after(turns, &s.last),
            carried: s.carried,
        })
        .collect()
}

/// A load's identity: its path, or its source in parens when it has none.
fn identity(e: &LoadEvent) -> String {
    e.path
        .clone()
        .unwrap_or_else(|| format!("({})", e.source.label()))
}

/// Running totals for one identity.
#[derive(Default)]
struct Sum {
    tokens: u64,
    loads: usize,
    last: String,
    carried: u64,
}

impl Sum {
    /// Each load is charged from ITS OWN entry (V98): a re-read arrives
    /// later and has fewer turns left to be re-billed across, so summing
    /// per event is the honest product. Multiplying the accumulated total
    /// by the earliest entry instead would inflate every repeated path.
    fn absorb(&mut self, e: &LoadEvent, turns: &[String]) {
        let tokens = tokens_of(e.bytes);
        self.tokens = self.tokens.saturating_add(tokens);
        self.loads = self.loads.saturating_add(1);
        let remaining = u64::try_from(turns_after(turns, &e.ts)).unwrap_or(0);
        self.carried = self
            .carried
            .saturating_add(tokens.saturating_mul(remaining));
        if e.ts > self.last {
            self.last.clone_from(&e.ts);
        }
    }
}

/// `bytes/4` -- the only tier available without content (V45).
fn tokens_of(bytes: usize) -> u64 {
    u64::try_from(bytes / 4).unwrap_or(u64::MAX)
}

/// Turns that happened after this thing was last loaded. ISO-8601 sorts
/// lexicographically, so a string comparison is the right one.
fn turns_after(turns: &[String], last: &str) -> usize {
    turns.iter().filter(|t| t.as_str() > last).count()
}

/// The total covers the SHOWN rows, so `--top N` narrows it -- matching
/// `estimate --top N`, which does the same. Consistency beats a
/// standalone improvement here: two verbs whose `--top` meant different
/// things would be the near-collision V2 warns about.
fn report(
    rows: &[Row],
    parsed: &Session,
    style: &Style,
    caveat: Caveat<'_>,
) -> String {
    let total: u64 = rows.iter().fold(0, |a, r| a.saturating_add(r.tokens));
    let mut out = if style.summarize {
        String::new()
    } else {
        rows.iter().map(|r| line(r, style)).collect()
    };
    out.push_str(&total_line(total, style));
    if !style.summarize {
        out.push_str(&caveat.legend());
    }
    out.push_str(&ledger(parsed, style));
    out
}

/// What the session's billed tokens cost, in the unit the file declared
/// (V61).
///
/// The rates multiply the harness's OWN split -- fresh input, cache reads,
/// cache writes -- rather than this report's rows. A row's tokens are
/// `bytes/4` and its cache split is unattributable, so a per-row price
/// would be a fiction with a decimal point (V3/V44).
///
/// Integers throughout, and the unit is never named: itok bundles no price
/// list and cannot know a currency, so the number is reported in whatever
/// the file declared and the method says so beside it.
fn money(parsed: &Session, rates: crate::models::Rates) -> Option<u64> {
    let split = [
        (parsed.fresh_input(), rates.input),
        (parsed.cache_read(), rates.cache_read),
        (parsed.cache_written(), rates.cache_write),
    ];
    if split.iter().all(|(n, _)| n.is_none()) {
        return None;
    }
    Some(split.iter().fold(0u64, |acc, (n, rate)| {
        let part = n.unwrap_or(0).saturating_mul(*rate);
        acc.saturating_add(part.checked_div(1_000_000).unwrap_or(0))
    }))
}

/// The money line, or the reason there is none (V47/V61): an absence with
/// no explanation reads as a zero bill.
fn cost_line(parsed: &Session, raw: &Raw) -> Result<String, String> {
    if !raw.cost {
        return Ok(String::new());
    }
    let Some(name) = raw.model.as_deref() else {
        return Ok(
            "  cost: none -- pass --model X; rates are per model\n".to_owned()
        );
    };
    let root = std::path::PathBuf::from(raw.chdir.as_deref().unwrap_or("."));
    let rates = crate::models::tier(Some(name), &root)?.rates;
    Ok(rates.map_or_else(
        || format!("  cost: none -- {name} declares no rate column\n"),
        |r| cost_text(parsed, r),
    ))
}

fn cost_text(parsed: &Session, rates: crate::models::Rates) -> String {
    money(parsed, rates).map_or_else(
        || "  cost: none -- no usage recorded to price\n".to_owned(),
        |n| {
            format!(
                "{n:>9}       cost         (declared units; \
                 in/cr/cc per 1M tokens)\n"
            )
        },
    )
}

/// What THIS session's own record says the `carried` product is worth
/// (V98).
///
/// The caveat used to be blanket -- "assumes no compaction", printed on
/// every session, on the premise that no compaction had ever been
/// observed. That premise was false for over a month (B29). The
/// transcript answers the question per session, so the answer is read
/// here rather than assumed in either direction.
///
/// Borrowed rather than owned: the timestamp belongs to the record, and
/// copying it would be a second place for it to go stale.
#[derive(Clone, Copy)]
pub(crate) struct Caveat<'a> {
    /// When items first left this context, or `None` when they never did.
    first: Option<&'a str>,
    /// How many boundaries the transcript recorded.
    count: usize,
}

impl<'a> Caveat<'a> {
    pub(crate) fn of(compactions: &'a [crate::session::Compaction]) -> Self {
        Self {
            first: compactions.first().map(|c| c.ts.as_str()),
            count: compactions.len(),
        }
    }

    /// The human legend. No advice, no verdict: the arithmetic and its
    /// premise, nothing else (V59).
    pub(crate) fn legend(&self) -> String {
        let tail = self.first.map_or_else(
            || "assumes no compaction".to_owned(),
            |ts| format!("UPPER BOUND -- this session compacted at {ts}"),
        );
        format!(
            "  carried = itok x turns since entry (cache re-billing; {tail})\n"
        )
    }

    /// The same claim in the shape json carries a method (V3): every
    /// number names how it was arrived at, including this one.
    pub(crate) fn method(&self) -> &'static str {
        if self.first.is_some() {
            "bytes/4 x turns-since-entry (UPPER BOUND: this session compacted)"
        } else {
            "bytes/4 x turns-since-entry (assumes no compaction)"
        }
    }
}

/// The accounted/unaccounted split (V44). Each number names its method
/// (V3), because they do not share one: the window is EXACT, from the
/// harness's own usage record, while accounted is `bytes/4`.
///
/// The gap therefore inherits the estimate's error and keeps the tilde
/// even though one operand is exact -- subtracting an estimate from a
/// measurement yields an estimate, and rendering it as a measurement
/// would launder it.
///
/// The categories are NAMED but never apportioned: assigning bytes to
/// them would be the silent attribution V44 forbids.
fn ledger(parsed: &Session, style: &Style) -> String {
    let Some(win) = parsed.window() else {
        // No usage anywhere: report nothing rather than zero (V47).
        return String::new();
    };
    // Named arguments throughout: positional order silently transposed
    // `gap` and the load count on the first attempt, and both are
    // plausible numbers, so nothing failed -- it just printed a lie.
    format!(
        "\n{win:>9} itok  window       (actual, last turn)\n\
         {acc:>9} itok  accounted    (bytes/4, {loads} loads)\n\
         {gap:>9} itok  unaccounted  (system prompt + tool schemas + conversation)\n\
         {billed:>9} itok  billed       (actual, {turns} turns)\n",
        win = size(win, style),
        acc = tilde(parsed.accounted_tokens(), style),
        loads = parsed.events.len(),
        gap = tilde(parsed.unaccounted_tokens().unwrap_or(0), style),
        billed = size(parsed.billed_input(), style),
        turns = parsed.turns.len(),
    ) + &cache_lines(parsed, style)
}

/// How `billed` decomposes: fresh, written to cache, served from cache.
/// READ from `usage`, never inferred (V47) -- so no hit-rate percentage
/// either, which would be a judgment about whether caching is working.
/// The three numbers are arithmetic; a reader can divide.
///
/// A field absent from EVERY turn produces NO line, rather than a zero
/// that would read as "the cache was never used" (V47). Each part is
/// independent: one missing must not suppress another that is present.
fn cache_lines(parsed: &Session, style: &Style) -> String {
    [
        ("fresh", parsed.fresh_input()),
        ("cache write", parsed.cache_written()),
        ("cache read", parsed.cache_read()),
    ]
    .iter()
    .filter_map(|(label, v)| Some((label, (*v)?)))
    .map(|(label, v)| format!("{:>19} itok    {label}\n", size(v, style)))
    .collect::<String>()
        + &cold_line(parsed, style)
}

/// Turns that re-wrote the prefix instead of reading it (V95).
///
/// Reports the COST and stops. No cause: a re-auth explains the one
/// instance measured, and generalising from a sample of two would be the
/// confident guess V3 forbids. No advice either -- this is an
/// observation, and judgment belongs to `doctor` (V59). Explicitly NOT a
/// fuse input: the version of this finding that retargeted the fuse was
/// drafted, then refuted by looking at the data (V95).
fn cold_line(parsed: &Session, style: &Style) -> String {
    let Some(cold) = parsed.cold_cache() else {
        return String::new(); // cache fields absent: cannot tell (V47)
    };
    if cold.turns == 0 {
        return String::new();
    }
    format!(
        "{:>28} turn(s) re-wrote the prefix ({} written, {} read)\n",
        cold.turns,
        size(cold.written, style),
        size(cold.read, style),
    )
}

fn total_line(total: u64, style: &Style) -> String {
    format!("{:>8} itok  total (bytes/4)\n", tilde(total, style))
}

/// `carried` sits AFTER `stale`, the two counts it is built from staying
/// where they were: a reader who knows the old layout reads the new one
/// unchanged, and an appended column is the cheapest addition there is
/// (V1/V2). It carries the tilde because it is an estimate multiplied by
/// a count -- exact arithmetic over a crude operand is still crude (V3).
fn line(r: &Row, style: &Style) -> String {
    format!(
        "{:>6}  {:>8} itok  {:>6}  {:>10} itok  {}\n",
        r.loads,
        tilde(r.tokens, style),
        r.stale,
        tilde(r.carried, style),
        r.what
    )
}

/// The crude-tier marker sits AGAINST its number (`~18314`), the way
/// every other verb renders it -- a gap would be a near-collision with
/// the established look (V2/V3).
fn tilde(n: u64, style: &Style) -> String {
    format!("~{}", size(n, style))
}

fn size(n: u64, style: &Style) -> String {
    if style.human { human(n) } else { n.to_string() }
}

/// One JSON object per row (V9), same field vocabulary as every other
/// verb so a parser learns it once.
fn json(rows: &[Row], parsed: &Session, caveat: Caveat<'_>) -> String {
    let mut out: String = rows.iter().map(|r| json_object(r, caveat)).collect();
    out.push_str(&json_summary(parsed, caveat));
    out
}

/// The split as one extra object, marked `summary` so a reader can tell
/// it from a row. Additive: existing row parsers are unaffected (V9).
/// The three counts that describe coverage rather than cost. `skipped`
/// is here because a reader must be able to see that records were
/// unreadable (V43/V44).
fn json_counts(parsed: &Session) -> String {
    format!(
        "\"loads\":{},\"turns\":{},\"skipped\":{}",
        parsed.events.len(),
        parsed.turns.len(),
        parsed.skipped,
    )
}

/// The cache decomposition, as `null` when a field was never reported.
///
/// The human view OMITS an absent line; json keeps the KEY and writes
/// `null`. Different idioms, one rule (V47): a reader must be able to
/// tell "not measured" from "measured as zero". Omitting keys
/// conditionally would make the stable contract (V9) awkward to parse,
/// while `null` is json's own word for absent.
fn json_cache(parsed: &Session) -> String {
    let field =
        |v: Option<u64>| v.map_or_else(|| "null".to_owned(), |n| n.to_string());
    format!(
        "\"fresh\":{},\"cache_write\":{},\"cache_read\":{},\
         \"cold_cache_turns\":{},\"cold_cache_written\":{}",
        field(parsed.fresh_input()),
        field(parsed.cache_written()),
        field(parsed.cache_read()),
        // null, not 0: "cannot tell" and "none found" are different
        // answers, and only one of them is a measurement (V47).
        field(parsed.cold_cache().map(|c| c.turns as u64)),
        field(parsed.cold_cache().map(|c| c.written)),
    )
}

fn json_summary(parsed: &Session, caveat: Caveat<'_>) -> String {
    let Some(win) = parsed.window() else {
        return String::new();
    };
    let counts = json_counts(parsed);
    let cache = json_cache(parsed);
    let gap = parsed.unaccounted_tokens().unwrap_or(0);
    format!(
        "{{\"summary\":true,\"window\":{win},\"accounted\":{acc},\
         \"unaccounted\":{gap},\"billed\":{billed},{cache},{counts},\
         \"compactions\":{n},\"unit\":\"input_tokens\",\
         \"window_method\":\"actual\",\"accounted_method\":\"bytes/4\"}}\n",
        acc = parsed.accounted_tokens(),
        billed = parsed.billed_input(),
        n = caveat.count,
    )
}

/// Additive: `carried` and its method join the existing vocabulary
/// without moving a field, so a parser written against the old shape
/// keeps working (V9).
///
/// The method string carries the caveat the human legend states. It lives
/// on the ROW rather than in the summary object because the summary is
/// emitted only when a turn reported usage, and a caveat that disappears
/// with the window would leave the number looking unconditional (V3).
fn json_object(r: &Row, caveat: Caveat<'_>) -> String {
    format!(
        "{{\"what\":\"{}\",\"tokens\":{},\"loads\":{},\"stale_turns\":{},\
         \"carried\":{},\"carried_method\":\"{}\",\
         \"unit\":\"input_tokens\",\"estimated\":true,\"method\":\"bytes/4\"}}\n",
        escape(&r.what),
        r.tokens,
        r.loads,
        r.stale,
        r.carried,
        caveat.method(),
    )
}

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)
}

/// One argument. `-h`/`-s`/`--top` are `du`'s, `--` is git's path
/// separator, and a bare word is the session -- nothing new to learn (V1).
fn apply<'a>(
    a: &str,
    it: &mut impl Iterator<Item = &'a String>,
    raw: &mut Raw,
) -> Result<(), String> {
    match a {
        "-h" => raw.style.human = true,
        "-s" => raw.style.summarize = true,
        "--cost" => raw.cost = true,
        "--bpe" | "--ollama" => {
            return Err(crate::tracecmd::no_real_tier(a, "top"));
        }
        _ => return with_value(a, it, raw),
    }
    Ok(())
}

/// Flags that consume the next argument, plus the fallthrough cases.
fn with_value<'a>(
    a: &str,
    it: &mut impl Iterator<Item = &'a String>,
    raw: &mut Raw,
) -> Result<(), String> {
    match a {
        "--top" => raw.top = Some(value(it, a)?),
        "--model" => raw.model = Some(value(it, a)?),
        "-C" => raw.chdir = Some(value(it, a)?),
        "--" => raw.path = Some(value(it, a)?),
        "--format" => raw.format = crate::tracecmd::format_of(&value(it, a)?)?,
        other if other.starts_with('-') => {
            return Err(format!("unknown flag {other}"));
        }
        other => raw.session = Some(other.to_owned()),
    }
    Ok(())
}

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

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

    fn run_on(name: &str, extra: &[&str]) -> Output {
        let mut args = vec![fixture(name)];
        args.extend(extra.iter().map(|s| (*s).to_owned()));
        top(&args)
    }

    /// The ranked rows only: everything before the total line. The
    /// ledger footer follows it and is not a row.
    fn rows_of(out: &Output) -> Vec<&str> {
        out.out
            .lines()
            .take_while(|l| !l.contains("total (bytes/4)"))
            .collect()
    }

    /// V46: ranked by occupancy, biggest first.
    #[test]
    fn rows_are_ranked_by_occupancy() {
        let out = run_on("tool-shapes.jsonl", &[]);
        let nums: Vec<u64> = rows_of(&out)
            .iter()
            .filter_map(|l| {
                l.split('~').nth(1)?.split_whitespace().next()?.parse().ok()
            })
            .collect();
        let mut sorted = nums.clone();
        sorted.sort_by(|a, b| b.cmp(a));
        assert_eq!(nums, sorted, "rows must descend by tokens");
    }

    /// V46: `--top N` keeps the BIGGEST N, not the first N.
    #[test]
    fn top_n_truncates_the_ranking() {
        let all = run_on("tool-shapes.jsonl", &[]);
        let two = run_on("tool-shapes.jsonl", &["--top", "2"]);
        assert!(rows_of(&two).len() < rows_of(&all).len());
        assert_eq!(rows_of(&two).len(), 2);
    }

    /// `-s` collapses to the total line, like `du -s`.
    #[test]
    fn summarize_drops_the_rows_but_keeps_the_ledger() {
        let out = run_on("tool-shapes.jsonl", &["-s"]);
        assert!(rows_of(&out).is_empty(), "no per-row lines under -s");
        assert!(out.out.contains("total (bytes/4)"));
        // The split is the point of the verb, so -s keeps it (V44).
        assert!(out.out.contains("unaccounted"));
    }

    /// `-h` abbreviates, like `du -h`. Tested on the formatter directly:
    /// no fixture is large enough to abbreviate, and a test that passes
    /// only because both sides are small asserts nothing.
    #[test]
    fn human_sizes_abbreviate() {
        let plain = Style::default();
        let big = Style {
            human: true,
            summarize: false,
        };
        assert_eq!(tilde(12_345, &plain), "~12345");
        assert_eq!(tilde(12_345, &big), "~12k");
    }

    /// V46: per-path attribution is `top -- <path>`, which is why there is
    /// no `blame` verb.
    #[test]
    fn a_path_filter_narrows_to_one_paths_loads() {
        let out = run_on("tool-shapes.jsonl", &["--", "/w/one.txt"]);
        let rows = rows_of(&out);
        assert_eq!(rows.len(), 1, "one row for one path");
        assert!(rows.first().is_some_and(|r| r.contains("/w/one.txt")));
    }

    /// V59: the dup count is arithmetic -- a path loaded twice says 2.
    /// `/w/one.txt` is read and then edited in the fixture.
    #[test]
    fn repeated_loads_are_counted() {
        let out = run_on("tool-shapes.jsonl", &["--", "/w/one.txt"]);
        let row = rows_of(&out).first().copied().unwrap_or_default();
        let loads: usize = row
            .split_whitespace()
            .next()
            .and_then(|n| n.parse().ok())
            .unwrap_or(0);
        assert_eq!(loads, 2, "read + edit = two loads of the same path");
    }

    /// A load with no path is grouped under its source, in parens -- never
    /// under an invented path (V3).
    #[test]
    fn pathless_loads_group_under_their_source() {
        let out = run_on("tool-shapes.jsonl", &[]);
        assert!(out.out.contains("(shell)"));
    }

    /// V9: one JSON object per row, same field vocabulary as every verb.
    #[test]
    fn json_is_one_object_per_row() {
        let out = run_on("tool-shapes.jsonl", &["--format", "json"]);
        let human = rows_of(&run_on("tool-shapes.jsonl", &[])).len();
        let rows = json_rows(&out);
        assert_eq!(rows.len(), human, "one object per ranked row");
        for line in rows {
            assert!(line.contains("\"unit\":\"input_tokens\""));
            assert!(line.contains("\"estimated\":true"));
            assert!(line.contains("\"stale_turns\":"));
        }
        assert!(!out.out.contains('~'), "no tilde in a numeric field (V3)");
    }

    /// Row objects only -- the summary is marked and excluded.
    fn json_rows(out: &Output) -> Vec<&str> {
        out.out
            .lines()
            .filter(|l| !l.contains("\"summary\":true"))
            .collect()
    }

    /// V3/V45: a real tier is refused with its reason, never ignored.
    #[test]
    fn a_real_tier_is_refused() {
        let out = run_on("tool-shapes.jsonl", &["--bpe"]);
        assert_eq!(out.code, 2);
        assert!(out.err.contains("no content is stored"));
        assert!(out.err.contains("top"), "the message names the verb");
    }

    /// V104: a NAMED miss is a usage error, an INFERRED one is silence.
    ///
    /// This test asserted exit 0 for a named path that does not exist, and
    /// cited V5 for it -- which is the defect B14 records, encoded as law.
    /// Report-only means never gating on CONTENT; it never meant a bad
    /// argument goes unreported, and `top --bpe` two tests up has always
    /// exited 2 on the same verb.
    #[test]
    fn a_named_miss_is_a_usage_error() {
        let out = top(&["/nonexistent/s.jsonl".to_owned()]);
        assert_eq!(out.code, 2, "a name that resolves to nothing");
        assert!(out.out.is_empty(), "nothing on stdout");
        assert!(out.err.contains("no session"), "{}", out.err);
    }

    #[test]
    fn unknown_flags_and_bad_formats_are_usage_errors() {
        assert_eq!(run_on("tool-shapes.jsonl", &["--nope"]).code, 2);
        assert_eq!(run_on("tool-shapes.jsonl", &["--format", "yaml"]).code, 2);
        assert_eq!(run_on("tool-shapes.jsonl", &["--top"]).code, 2);
    }

    /// V44: the split is exact arithmetic -- accounted plus unaccounted
    /// is the window, with nothing rounded away or silently assigned.
    #[test]
    fn accounted_plus_unaccounted_is_the_window() {
        let text = std::fs::read_to_string(fixture("minimal.jsonl"))
            .unwrap_or_default();
        let s = claude_code::parse(&text);
        let win = s.window().unwrap_or(0);
        let sum = s
            .accounted_tokens()
            .saturating_add(s.unaccounted_tokens().unwrap_or(0));
        assert_eq!(sum, win);
    }

    /// The split is measured against ONE window, never the cumulative
    /// bill. This fixture bills more across its turns than any single
    /// window holds, so comparing against the cumulative would make the
    /// gap absurd -- the regression this test exists to catch (V44).
    #[test]
    fn the_split_uses_one_window_not_the_cumulative_bill() {
        let text = std::fs::read_to_string(fixture("minimal.jsonl"))
            .unwrap_or_default();
        let s = claude_code::parse(&text);
        let win = s.window().unwrap_or(0);
        assert!(
            win <= s.billed_input(),
            "a window can never exceed the cumulative bill"
        );
        assert!(
            s.unaccounted_tokens().unwrap_or(u64::MAX) <= win,
            "the gap is bounded by ONE window, not by the whole session"
        );
    }

    /// V3: the gap inherits the estimate, so it keeps the tilde even
    /// though the window it came from is exact. Laundering an estimate
    /// into a measurement is the failure this guards.
    #[test]
    fn the_gap_is_marked_estimated() {
        let out = run_on("minimal.jsonl", &["-s"]);
        let gap = out
            .out
            .lines()
            .find(|l| l.contains("unaccounted"))
            .unwrap_or_default();
        assert!(gap.contains('~'), "unaccounted must carry the tilde");
        let win = out
            .out
            .lines()
            .find(|l| l.contains("window"))
            .unwrap_or_default();
        assert!(!win.contains('~'), "the window is exact, no tilde");
    }

    /// V47: no usage anywhere means the split is ABSENT, not zero.
    #[test]
    fn no_usage_reports_no_split_rather_than_zero() {
        let out = run_on("tool-shapes.jsonl", &["-s"]);
        assert!(out.out.contains("window"), "this fixture has usage");
        let s = crate::session::Session::default();
        assert_eq!(s.window(), None);
        assert_eq!(s.unaccounted_tokens(), None);
    }

    /// `bytes/4` can over-estimate, so accounted may exceed the window.
    /// The gap clamps at zero rather than going negative, which would say
    /// something false about the data instead of about the estimator.
    ///
    /// Built in memory rather than from a fixture: no real transcript has
    /// this shape, and inventing one that did would make the fixture less
    /// representative to test an arithmetic edge.
    #[test]
    fn an_over_estimate_clamps_the_gap_at_zero() {
        let mut s = crate::session::Session::default();
        s.turns.push(crate::session::Turn {
            cache_read: Some(10),
            ..crate::session::Turn::default()
        });
        s.events.push(crate::session::LoadEvent {
            session: String::new(),
            ts: String::new(),
            source: crate::session::Source::Tool("shell".to_owned()),
            path: None,
            bytes: 4000,
            spilled: None,
        });
        assert!(s.accounted_tokens() > s.window().unwrap_or(0));
        assert_eq!(s.unaccounted_tokens(), Some(0), "clamped, never negative");
    }

    /// V9: the summary is one extra object, marked so a reader can tell
    /// it from a row, and carrying a method per figure.
    #[test]
    fn the_json_summary_is_distinguishable_and_labelled() {
        let out = run_on("minimal.jsonl", &["--format", "json"]);
        let last = out.out.lines().last().unwrap_or_default();
        assert!(last.contains("\"summary\":true"));
        assert!(last.contains("\"window_method\":\"actual\""));
        assert!(last.contains("\"accounted_method\":\"bytes/4\""));
        assert!(!out.out.contains('~'), "no tilde in json (V9)");
    }

    /// V44: the decomposition is exact -- fresh + written + read is the
    /// whole bill, with nothing rounded away.
    #[test]
    fn the_cache_parts_sum_to_billed() {
        let text = std::fs::read_to_string(fixture("minimal.jsonl"))
            .unwrap_or_default();
        let s = claude_code::parse(&text);
        let parts = s
            .fresh_input()
            .unwrap_or(0)
            .saturating_add(s.cache_written().unwrap_or(0))
            .saturating_add(s.cache_read().unwrap_or(0));
        assert_eq!(parts, s.billed_input());
    }

    /// Present fields produce lines, labelled and readable.
    #[test]
    fn cache_lines_appear_when_the_fields_are_present() {
        let out = run_on("minimal.jsonl", &["-s"]);
        for label in ["fresh", "cache write", "cache read"] {
            assert!(out.out.contains(label), "missing `{label}` line");
        }
    }

    /// V47, the one that matters: a field absent from EVERY turn produces
    /// NO line -- never a zero, which would read as "the cache was never
    /// used" when the truth is that nothing was measured.
    ///
    /// Built in memory: every fixture carries these fields, as does every
    /// real transcript characterised. This is the defensive case V47
    /// exists for, so it has to be constructed rather than found.
    #[test]
    fn absent_cache_fields_produce_no_lines_and_no_zeros() {
        let mut s = crate::session::Session::default();
        s.turns.push(crate::session::Turn {
            input: Some(100),
            ..crate::session::Turn::default()
        });
        assert_eq!(s.cache_read(), None, "never reported stays None");
        let out = ledger(&s, &Style::default());
        assert!(out.contains("fresh"), "the present field still shows");
        assert!(!out.contains("cache read"), "absent field: no line");
        assert!(!out.contains("cache write"), "absent field: no line");
    }

    /// Each part is independent: one absent field must not suppress
    /// another that IS present.
    #[test]
    fn a_missing_field_does_not_suppress_a_present_one() {
        let mut s = crate::session::Session::default();
        s.turns.push(crate::session::Turn {
            cache_read: Some(500),
            ..crate::session::Turn::default()
        });
        let out = ledger(&s, &Style::default());
        assert!(out.contains("cache read"), "present field shows");
        assert!(!out.contains("fresh"), "absent field stays absent");
    }

    /// V47/V9: json keeps the KEY and writes `null` -- a different idiom
    /// from the human view's omitted line, but the same rule. A zero here
    /// would be indistinguishable from a real measurement of zero.
    #[test]
    fn json_writes_null_for_an_absent_field_never_zero() {
        let mut s = crate::session::Session::default();
        s.turns.push(crate::session::Turn {
            input: Some(7),
            ..crate::session::Turn::default()
        });
        let out = json_cache(&s);
        assert!(out.contains("\"fresh\":7"));
        assert!(out.contains("\"cache_read\":null"), "absent -> null");
        assert!(!out.contains("\"cache_read\":0"), "never a zero");
    }

    /// The cache figures are READ from usage, so they are exact and carry
    /// no tilde -- unlike the accounted line beside them (V3/V47).
    #[test]
    fn cache_figures_are_exact_not_estimated() {
        let out = run_on("minimal.jsonl", &["-s"]);
        let line = out
            .out
            .lines()
            .find(|l| l.contains("cache read"))
            .unwrap_or_default();
        assert!(!line.contains('~'), "read from usage: no tilde");
    }

    /// The rule needs no threshold: warm turns read the whole prefix and
    /// write only the new content, so read dominates; cold, there is
    /// nothing to read. Measured, the populations sit 20x apart.
    #[test]
    fn write_over_read_classifies_a_cold_turn() {
        let mut s = crate::session::Session::default();
        s.turns.push(turn_with(1_000, 600_000)); // warm
        s.turns.push(turn_with(250_657, 20_628)); // cold
        let cold = s.cold_cache().unwrap_or_default();
        assert_eq!(cold.turns, 1, "only the write-heavy turn counts");
        assert_eq!(cold.written, 250_657);
        assert_eq!(cold.read, 20_628);
    }

    /// Equal values are NEITHER. A turn reporting zero for both is not a
    /// cold cache; it is a turn that reported nothing -- the zero-window
    /// case found in a real transcript.
    #[test]
    fn equal_values_classify_as_neither() {
        let mut s = crate::session::Session::default();
        s.turns.push(turn_with(0, 0));
        s.turns.push(turn_with(500, 500));
        assert_eq!(s.cold_cache().unwrap_or_default().turns, 0);
    }

    /// V47: absent fields mean CANNOT TELL, which is not "none found".
    /// `None` and `Some(0)` are different answers and only one of them is
    /// a measurement.
    #[test]
    fn absent_cache_fields_cannot_be_classified() {
        let mut s = crate::session::Session::default();
        s.turns.push(crate::session::Turn {
            input: Some(10),
            ..crate::session::Turn::default()
        });
        assert_eq!(s.cold_cache(), None, "cannot tell, not none-found");
        assert!(cold_line(&s, &Style::default()).is_empty());
    }

    /// No cold turns means no line -- the report stays quiet when there
    /// is nothing to report (V47).
    #[test]
    fn no_cold_turns_means_no_line() {
        let mut s = crate::session::Session::default();
        s.turns.push(turn_with(1_000, 600_000));
        assert_eq!(s.cold_cache().unwrap_or_default().turns, 0);
        assert!(cold_line(&s, &Style::default()).is_empty());
    }

    /// The figures come from `usage`, so they are exact -- no tilde. And
    /// the line states the COST only: no cause, no advice (V95/V59).
    #[test]
    fn the_cold_line_reports_cost_without_cause_or_advice() {
        let mut s = crate::session::Session::default();
        s.turns.push(turn_with(250_657, 20_628));
        let out = cold_line(&s, &Style::default());
        assert!(out.contains("re-wrote the prefix"));
        assert!(!out.contains('~'), "read from usage: exact");
        for word in ["login", "auth", "avoid", "should", "consider"] {
            assert!(
                !out.to_lowercase().contains(word),
                "no cause/advice: {word}"
            );
        }
    }

    /// V47/V9: json says `null` when the fields were never reported.
    #[test]
    fn json_cold_fields_are_null_when_unclassifiable() {
        let mut s = crate::session::Session::default();
        s.turns.push(crate::session::Turn {
            input: Some(1),
            ..crate::session::Turn::default()
        });
        let out = json_cache(&s);
        assert!(out.contains("\"cold_cache_turns\":null"));
        assert!(!out.contains("\"cold_cache_turns\":0"));
    }

    fn turn_with(write: u64, read: u64) -> crate::session::Turn {
        crate::session::Turn {
            cache_creation: Some(write),
            cache_read: Some(read),
            ..crate::session::Turn::default()
        }
    }

    /// The `carried` cell of a row, parsed back out of the rendered line.
    fn carried_cell(out: &Output) -> &str {
        rows_of(out)
            .first()
            .and_then(|r| r.split_whitespace().nth(4))
            .unwrap_or_default()
    }

    /// V98/V94: an item entering at turn N of T carries `size x (T-N)`.
    /// `/w/one.txt` is read (1 itok with 2 turns left) then edited, and an
    /// edit result carries a PATCH rather than content, so it weighs 0 and
    /// adds nothing: 1x2 + 0x1 = 2. Which is the point -- what a load
    /// carries is its BILLED size (V76), never the file it names.
    #[test]
    fn carried_is_size_times_turns_after_entry() {
        let out = run_on("tool-shapes.jsonl", &["--", "/w/one.txt"]);
        assert_eq!(carried_cell(&out), "~2");
    }

    /// V94's real point: the EARLIEST entries dominate. The last thing
    /// loaded has no turns left to be re-billed across, so its leverage is
    /// zero however big it is.
    #[test]
    fn the_last_load_has_carried_nothing() {
        let out = run_on("tool-shapes.jsonl", &["--", "/w/two.txt"]);
        assert_eq!(carried_cell(&out), "~0");
    }

    /// V98: charged PER LOAD EVENT. The shortcut -- summed tokens times
    /// the turns after the EARLIEST entry -- would say 6000 here, because
    /// it bills the re-read for turns that preceded it. Built in memory:
    /// the arithmetic is the subject, and a fixture would only obscure it.
    #[test]
    fn carried_charges_each_load_from_its_own_entry() {
        let turns: Vec<String> = ["01", "03", "05", "07"]
            .iter()
            .map(|t| (*t).into())
            .collect();
        let mut sum = Sum::default();
        sum.absorb(&load_at("02", 4000), &turns); // 1000 x 3 turns left
        sum.absorb(&load_at("04", 4000), &turns); // 1000 x 2 turns left
        assert_eq!(sum.tokens, 2000);
        assert_eq!(sum.carried, 5000);
        let shortcut = sum.tokens * 3;
        assert_ne!(sum.carried, shortcut, "the summed-total product inflates");
    }

    fn load_at(ts: &str, bytes: usize) -> LoadEvent {
        LoadEvent {
            session: String::new(),
            ts: ts.to_owned(),
            source: crate::session::Source::Tool("Read".to_owned()),
            path: Some("/w/one.txt".to_owned()),
            bytes,
            spilled: None,
        }
    }

    /// V98: the caveat is STATED, not implicit, and this fixture carries
    /// no compaction boundary, so it is the exact reading that prints.
    #[test]
    fn the_report_states_the_uncompacted_caveat() {
        let out = run_on("tool-shapes.jsonl", &[]);
        assert!(out.out.contains("carried = itok x turns since entry"));
        assert!(out.out.contains("assumes no compaction"));
    }

    /// The rates multiply the harness's OWN split, so the arithmetic is
    /// checkable by hand: 300/30/375 per million against 1,000,000 fresh,
    /// 2,000,000 read and 400,000 written is 300 + 60 + 150.
    #[test]
    fn money_prices_each_half_of_the_split_at_its_own_rate() {
        let session = priced_session();
        let rates = crate::models::Rates {
            input: 300,
            cache_read: 30,
            cache_write: 375,
        };
        assert_eq!(money(&session, rates), Some(510));
    }

    /// V47: no usage recorded is not a zero bill. A session the harness
    /// never reported cannot be priced, and saying 0 would be a claim.
    #[test]
    fn a_session_with_no_usage_has_no_price_rather_than_zero() {
        let rates = crate::models::Rates {
            input: 300,
            cache_read: 30,
            cache_write: 375,
        };
        assert_eq!(money(&Session::default(), rates), None);
    }

    /// V61: each absence says WHICH it is. "No money" and "the wrong
    /// money" are the two answers that invariant exists to keep apart, and
    /// a bare missing line reads as a zero bill.
    #[test]
    fn every_absent_price_names_its_own_reason() {
        let session = priced_session();
        let asked = Raw {
            cost: true,
            ..Raw::default()
        };
        let out = cost_line(&session, &asked).unwrap_or_default();
        assert!(out.contains("pass --model"), "{out}");
        assert!(
            cost_line(&session, &Raw::default())
                .unwrap_or_default()
                .is_empty()
        );
    }

    /// V11 reaches the new column: an unknown model FAILS. A price
    /// invented for a model nobody listed is the confident lie V61 is
    /// about.
    #[test]
    fn an_unknown_model_fails_rather_than_pricing_nothing() {
        let asked = Raw {
            cost: true,
            model: Some("nonesuch".to_owned()),
            chdir: Some("/nonexistent".to_owned()),
            ..Raw::default()
        };
        assert!(cost_line(&priced_session(), &asked).is_err());
    }

    /// A session whose usage split is round numbers, so a price is
    /// arithmetic anyone can check in their head.
    fn priced_session() -> Session {
        Session {
            turns: vec![crate::session::Turn {
                input: Some(1_000_000),
                cache_read: Some(2_000_000),
                cache_creation: Some(400_000),
                ..crate::session::Turn::default()
            }],
            ..Session::default()
        }
    }

    /// V59: the legend explains the arithmetic and its premise. It does
    /// not tell the reader what to do about the number -- in EITHER of
    /// its two readings.
    #[test]
    fn the_carried_column_gives_no_advice() {
        let compacted = Caveat {
            first: Some("2026-08-16T05:19:24.283Z"),
            count: 1,
        };
        let both = Caveat::of(&[]).legend() + &compacted.legend();
        for word in ["should", "consider", "unhealthy", "reduce", "too"] {
            assert!(!both.to_lowercase().contains(word), "no advice: {word}");
        }
    }

    /// B29: the caveat is READ off the session, not assumed. A
    /// transcript carrying a compaction says its product is an upper
    /// bound, and says when the items left.
    #[test]
    fn a_compacted_session_labels_carried_an_upper_bound() {
        let caveat = Caveat {
            first: Some("2026-08-16T05:19:24.283Z"),
            count: 2,
        };
        let legend = caveat.legend();
        assert!(legend.contains("UPPER BOUND"), "{legend}");
        assert!(legend.contains("2026-08-16T05:19:24.283Z"), "{legend}");
        assert!(!legend.contains("assumes no compaction"), "{legend}");
        assert!(
            caveat.method().contains("UPPER BOUND"),
            "{}",
            caveat.method()
        );
    }

    /// And a session with no boundary keeps the exact reading: the fix
    /// for a blanket claim is not the opposite blanket claim.
    #[test]
    fn a_session_that_never_compacted_keeps_the_exact_reading() {
        let caveat = Caveat::of(&[]);
        assert!(caveat.legend().contains("assumes no compaction"));
        assert!(!caveat.legend().contains("UPPER BOUND"));
        assert!(caveat.method().contains("assumes no compaction"));
    }

    /// Under `-s` there is no column, so there is nothing to explain --
    /// output that always appears is output nobody reads.
    #[test]
    fn the_caveat_is_absent_when_no_rows_are_shown() {
        let out = run_on("tool-shapes.jsonl", &["-s"]);
        assert!(!out.out.contains("carried ="));
    }

    /// V3: exact arithmetic over a crude operand is still crude, so the
    /// human cell keeps the tilde. V9: json carries the same intent
    /// structurally, never a tilde in a numeric field.
    #[test]
    fn carried_keeps_the_tilde_and_json_does_not() {
        assert!(carried_cell(&run_on("tool-shapes.jsonl", &[])).contains('~'));
        let out = run_on("tool-shapes.jsonl", &["--format", "json"]);
        assert!(!out.out.contains('~'));
    }

    /// V9: additive -- the field and its method join the vocabulary
    /// without moving anything a parser already reads.
    #[test]
    fn json_rows_carry_the_leverage_field_and_its_method() {
        let out = run_on("tool-shapes.jsonl", &["--format", "json"]);
        for line in json_rows(&out) {
            assert!(line.contains("\"carried\":"));
            assert!(line.contains("\"carried_method\":\"bytes/4 x turns"));
            assert!(line.contains("(assumes no compaction)"));
            // The pre-existing fields are untouched.
            assert!(line.contains("\"stale_turns\":"));
            assert!(line.contains("\"tokens\":"));
        }
    }

    /// `stale` counts turns AFTER the last load. The fixture's turns all
    /// precede or interleave its events, so the newest load has none after
    /// it.
    #[test]
    fn stale_counts_turns_after_the_last_load() {
        let out = run_on("tool-shapes.jsonl", &["--", "/w/two.txt"]);
        let row = rows_of(&out).first().copied().unwrap_or_default();
        let stale: usize = row
            .split_whitespace()
            .nth(3)
            .and_then(|n| n.parse().ok())
            .unwrap_or(999);
        assert_eq!(stale, 0, "the last-loaded path has no turns after it");
    }
}