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
//! The `trace` command: one line per runtime load event, chronological
//! (V46). `git log`/strace-shaped -- `-n`, `--since`, `--reverse` mean
//! what they mean there, so there is nothing new to learn (V1).
//!
//! Report-only, exit 0 always (V5). It reports ARITHMETIC -- what was
//! loaded, when, and how big -- never a verdict about whether that is
//! healthy (V59).
//!
//! Per-event sizes are ESTIMATES and say so. The reader keeps no content
//! (V45), only byte lengths, so `bytes/4` is the only tier available
//! here: there is nothing left to tokenize, which is why `--bpe` is not
//! accepted rather than accepted-and-ignored (V3). The session TOTAL is
//! exact, because it comes from the harness's own usage records -- the
//! attribution is partial, the total is not (V44).

use crate::args::Format;
use crate::cli::Output;
use crate::json::escape;
use crate::session::{LoadEvent, Session, Source, claude_code};
use std::path::{Path, PathBuf};

#[derive(Default)]
struct Raw {
    session: Option<String>,
    limit: Option<String>,
    since: Option<String>,
    reverse: bool,
    format: Format,
    chdir: Option<String>,
}

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

fn run(raw: &Raw) -> Output {
    // An INFERRED absence is not an error: this project may simply have no
    // recorded session, and report-only means exit 0 (V5). A NAMED one is,
    // because silence would read as "that session is empty" (V104).
    let parsed = match session_at(raw.session.as_deref(), raw.chdir.as_deref())
    {
        Ok((p, _)) => p,
        Err(o) => return o,
    };
    let rows = select(parsed.events, raw);
    Output::ok(match raw.format {
        Format::Json => json(&rows),
        Format::Human => report(&rows),
    })
}

/// Where a session came from -- the claim itself, not just the path.
///
/// "The newest transcript" and "your session" are DIFFERENT claims (V96),
/// and a report labelled with the wrong one is a report about someone
/// else's context. So the origin travels with the path and the caller can
/// say which it was.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Origin {
    /// A path the caller named.
    Argument,
    /// An id the HARNESS offered -- authoritative for "your session".
    Harness,
    /// Newest-by-mtime. A GUESS: with two sessions in one project it can
    /// silently pick the wrong one.
    Newest,
}

/// The env vars a harness may use to name the live session.
///
/// Checked in order and treated as equivalent, because the point is the
/// SOURCE (the harness said so) rather than which spelling it used. An
/// unset or empty value is no offer at all -- an empty string is not an id.
const SESSION_VARS: [&str; 3] = [
    "CLAUDE_SESSION_ID",
    "ITOK_SESSION_ID",
    "CLAUDE_CODE_SESSION_ID",
];

/// A session id the harness offered, if any.
fn harness_session() -> Option<String> {
    first_id(SESSION_VARS.iter().filter_map(|k| std::env::var(k).ok()))
}

/// The first value that is actually an id.
///
/// Pure, so the rule is testable without depending on which variables the
/// ambient environment happens to set -- this machine really does export
/// `CLAUDE_CODE_SESSION_ID`, and a test that assumed otherwise passed or
/// failed on where it ran (B3's ambient-state lesson).
fn first_id(values: impl Iterator<Item = String>) -> Option<String> {
    values.map(|v| v.trim().to_owned()).find(|v| !v.is_empty())
}

/// Why no transcript was read. The two cases mean OPPOSITE things (V104).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Missing {
    /// Nothing was named and nothing was found. Silence is the honest
    /// answer -- the caller asked for no session in particular.
    Inferred,
    /// A session WAS named and did not resolve. Silence here would read as
    /// "that session is empty", which is a different claim and a false one,
    /// so this carries the diagnostic instead.
    Named(String),
}

/// A named session, then a harness-offered id, then newest-by-mtime.
///
/// The ORDER is V96's rule: prefer identity the harness knows over a guess
/// from the filesystem, and fall back only when nothing was offered.
///
/// A NAMED session is an id OR a path (V104, and the shared `<session>`
/// clause in section I). It used to be a path and only a path -- so a harness id,
/// which is what V96 says identity actually looks like, resolved to a
/// relative path that never existed. The id branch was already written
/// three lines below, for the INFERRED case, and was never carried to the
/// named one: B11's shape, and the reason M12 exists.
///
/// Path first, then id, because "a file that exists" is unambiguous and a
/// session id is never also a real relative path. When neither resolves,
/// the error NAMES both attempts rather than reporting a bare not-found.
pub(crate) fn resolve_session(
    session: Option<&str>,
    chdir: Option<&str>,
) -> Result<(PathBuf, Origin), Missing> {
    resolve_with(session, chdir, env_home(), harness_session())
}

/// The resolution rule with its two AMBIENT inputs -- the home directory
/// and the id a harness offered -- passed IN rather than read here.
///
/// The seam exists so the rule can be tested against a planted tree
/// without writing to the process environment. Those tests used to set
/// `HOME` and put it back, which edition 2024 correctly calls `unsafe`
/// (a mutation every other thread can observe mid-read) and this crate
/// forbids unsafe outright. Passing the value is not a workaround for the
/// lint: it is the thing the lint was asking for, and it also makes the
/// tests hermetic under a parallel runner (B3).
fn resolve_with(
    session: Option<&str>,
    chdir: Option<&str>,
    home: Option<PathBuf>,
    offered: Option<String>,
) -> Result<(PathBuf, Origin), Missing> {
    if let Some(s) = session {
        return named_session(s, chdir, home.as_deref());
    }
    let dir = project_dir(chdir, home.as_deref()).ok_or(Missing::Inferred)?;
    if let Some(id) = offered {
        let named = dir.join(format!("{id}.jsonl"));
        if named.is_file() {
            return Ok((named, Origin::Harness));
        }
    }
    newest_in(&dir)
        .map(|p| (p, Origin::Newest))
        .ok_or(Missing::Inferred)
}

/// Resolve what the caller NAMED, or say what was tried.
fn named_session(
    s: &str,
    chdir: Option<&str>,
    home: Option<&Path>,
) -> Result<(PathBuf, Origin), Missing> {
    let dir = project_dir(chdir, home);
    match found(s, dir.as_deref()) {
        Some(p) => Ok((p, Origin::Argument)),
        None => Err(Missing::Named(no_session(s, dir.as_deref()))),
    }
}

/// A path that exists, else the id form under the project dir.
fn found(s: &str, dir: Option<&Path>) -> Option<PathBuf> {
    let as_path = PathBuf::from(s);
    if as_path.is_file() {
        return Some(as_path);
    }
    let as_id = dir?.join(format!("{s}.jsonl"));
    as_id.is_file().then_some(as_id)
}

/// The diagnostic names BOTH forms and the directory searched, because
/// "not found" without them cannot be acted on: the caller cannot tell a
/// typo in an id from a session that is really gone (V71).
fn no_session(s: &str, dir: Option<&Path>) -> String {
    let where_ = dir.map_or_else(
        || "no project directory for this working directory".to_owned(),
        |d| d.display().to_string(),
    );
    format!(
        "itok: no session '{s}' -- not a readable path, \
         and no '{s}.jsonl' in {where_}"
    )
}

/// The one place a `Missing` becomes an `Output`, so all four runtime verbs
/// answer it identically (V64) -- a named miss is a usage error (exit 2,
/// per section I), an inferred one is honest silence.
pub(crate) fn missing_output(m: &Missing) -> Output {
    match m {
        Missing::Inferred => Output::ok(String::new()),
        Missing::Named(msg) => Output::usage(format!("{msg}\n")),
    }
}

/// A resolved source that cannot be READ is also a named failure: it
/// existed a moment ago, so silence would hide a real I/O fault.
fn read_source(path: &Path) -> Result<String, Output> {
    std::fs::read_to_string(path).map_err(|e| {
        Output::usage(format!("itok: cannot read {}: {e}\n", path.display()))
    })
}

/// Resolve, read, parse -- the whole front half of every runtime verb, in
/// ONE place (V64).
///
/// It was four copies, and they had drifted into four different silences.
/// A verb that owns its own copy of "what does a missing session mean" is
/// how B14 reached all four at once, so the answer lives here and each
/// caller just propagates the `Output`.
///
/// Truncates at the last complete line so a session still being written
/// gives the same answer twice (V77/V43).
pub(crate) fn session_at(
    session: Option<&str>,
    chdir: Option<&str>,
) -> Result<(Session, Origin), Output> {
    let (session, _, origin) = session_with_compactions(session, chdir)?;
    Ok((session, origin))
}

/// The same load, keeping the harness's compaction records (V116).
///
/// A SECOND entry point rather than a wider return for all five verbs:
/// only `rate` draws a red line today, and `Session` cannot carry the
/// records without breaking its public shape. Both go through the ONE
/// resolve-read-parse above, so B14's four silences cannot come back as
/// two.
/// A loaded session, the harness's compaction records, and where the
/// session came from -- named because the triple appears on both sides of
/// the call and a bare tuple of three is where an argument gets swapped.
pub(crate) type Loaded = (Session, Vec<crate::session::Compaction>, Origin);

pub(crate) fn session_with_compactions(
    session: Option<&str>,
    chdir: Option<&str>,
) -> Result<Loaded, Output> {
    let (path, origin) =
        resolve_session(session, chdir).map_err(|m| missing_output(&m))?;
    let text = read_source(&path)?;
    let (session, compactions) =
        claude_code::parse_with(crate::session::complete_prefix(&text));
    Ok((session, compactions, origin))
}

/// The harness's transcript directory for this project.
fn project_dir(chdir: Option<&str>, home: Option<&Path>) -> Option<PathBuf> {
    let cwd = chdir.map_or_else(
        || std::env::current_dir().ok(),
        |d| Some(PathBuf::from(d)),
    )?;
    let home = home?;
    let project = std::fs::canonicalize(&cwd).unwrap_or(cwd);
    Some(claude_code::project_dir(home, &project))
}

/// `HOME`, read in ONE place so the seam above has a single ambient
/// source to stand in for.
fn env_home() -> Option<PathBuf> {
    std::env::var("HOME").ok().map(PathBuf::from)
}

fn newest_in(dir: &Path) -> Option<PathBuf> {
    claude_code::newest_in(dir)
}

/// A one-line note naming WHICH session was read, when that is a guess.
///
/// Silent for an explicit path or a harness id: the caller already knows
/// what it asked for. Loud for newest-by-mtime, because with two sessions in
/// one project that is a guess, and "the newest transcript" is a weaker
/// claim than "your session" (V96/V3). Only the guess needs saying, or the
/// note becomes output that always appears and nobody reads (V71).
pub(crate) fn origin_note(origin: &Origin) -> String {
    match origin {
        Origin::Newest => "  session: newest by mtime -- not necessarily \
             yours; pass a path or set CLAUDE_SESSION_ID\n"
            .to_owned(),
        Origin::Argument | Origin::Harness => String::new(),
    }
}

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

    /// V96/V3: only the GUESS is announced. An explicit path or a harness id
    /// is what the caller asked for, so a note there would be output that
    /// always appears and nobody reads (V71).
    #[test]
    fn only_the_guess_announces_itself() {
        assert!(origin_note(&Origin::Argument).is_empty());
        assert!(origin_note(&Origin::Harness).is_empty());
        let note = origin_note(&Origin::Newest);
        assert!(note.contains("newest by mtime"), "{note}");
        assert!(note.contains("not necessarily"), "the claim is weakened");
        assert!(note.contains("CLAUDE_SESSION_ID"), "and says what to do");
    }

    /// An explicit path is the strongest claim and needs no environment --
    /// but it must EXIST. This test used to pass a path that was never
    /// there and assert it resolved, which is the behaviour B14 was: a name
    /// accepted without being checked, then read into silence.
    #[test]
    fn an_explicit_path_is_its_own_origin() {
        let dir = std::env::temp_dir().join("itok-v104-path");
        let _ = std::fs::create_dir_all(&dir);
        let file = dir.join("x.jsonl");
        let _ = std::fs::write(&file, "");
        let got = resolve_session(Some(&file.to_string_lossy()), None);
        assert_eq!(got, Ok((file.clone(), Origin::Argument)));
        let _ = std::fs::remove_file(&file);
    }

    /// V104: a NAMED source that cannot be read is an ERROR, and the
    /// diagnostic names both forms that were tried plus where it looked.
    ///
    /// PLANTED: the guard is proven by a name that resolves to nothing,
    /// because a check that has never rejected anything cannot be told from
    /// one that cannot (V79).
    #[test]
    fn v104_a_named_session_that_misses_is_an_error() {
        let got = resolve_session(Some("no-such-session-xyz"), None);
        let msg = match got {
            Err(Missing::Named(m)) => m,
            Err(Missing::Inferred) => {
                unreachable!("a NAMED miss reported as an inferred one")
            }
            Ok(_) => unreachable!("a name resolving to nothing succeeded"),
        };
        assert!(msg.contains("no-such-session-xyz"), "{msg}");
        assert!(msg.contains(".jsonl"), "names the id form tried: {msg}");
    }

    /// V104's other half: the two absences render differently. An inferred
    /// miss is silence at exit 0; a named one is a diagnostic at exit 2.
    #[test]
    fn v104_only_a_named_miss_is_a_usage_error() {
        let inferred = missing_output(&Missing::Inferred);
        assert_eq!(inferred.code, 0, "nothing was asked for");
        assert!(inferred.out.is_empty() && inferred.err.is_empty());
        let named = missing_output(&Missing::Named("itok: gone".to_owned()));
        assert_eq!(named.code, 2, "a named miss is a usage error");
        assert!(named.err.contains("itok: gone"), "{}", named.err);
        assert!(named.out.is_empty(), "nothing on stdout");
    }

    /// A transcript under a throwaway HOME, and the id that should find it.
    ///
    /// The directories are SUFFIXED with the id so two tests never share a
    /// project dir. They run in separate processes under nextest, so a
    /// shared dir is not a data race -- it is worse: `newest_in` picks by
    /// mtime, so one test's planted file can win another test's fallback
    /// and the failure looks like a bug in the tool.
    fn planted_transcript(id: &str) -> (PathBuf, PathBuf, PathBuf) {
        let home = std::env::temp_dir().join(format!("itok-v104-home-{id}"));
        let cwd = std::env::temp_dir().join(format!("itok-v104-proj-{id}"));
        let _ = std::fs::create_dir_all(&cwd);
        let canon = std::fs::canonicalize(&cwd).unwrap_or_else(|_| cwd.clone());
        let dir = crate::session::claude_code::project_dir(&home, &canon);
        let _ = std::fs::create_dir_all(&dir);
        let file = dir.join(format!("{id}.jsonl"));
        let _ = std::fs::write(&file, "");
        (home, cwd, file)
    }

    /// Resolve with the planted tree HANDED IN as the home directory.
    ///
    /// It used to set `HOME`, call, and put it back. That is a process-wide
    /// mutation made to answer a question about one call -- unsound under a
    /// parallel runner (B3's lesson), and `unsafe` from edition 2024 on,
    /// which this crate forbids outright. `resolve_with` takes the value
    /// instead, so the test reads exactly what it planted and touches
    /// nothing ambient.
    fn resolve_under_home(
        home: &Path,
        cwd: &Path,
        arg: Option<&str>,
    ) -> Result<(PathBuf, Origin), Missing> {
        let dir = cwd.to_string_lossy();
        resolve_with(arg, Some(&dir), Some(home.to_path_buf()), None)
    }

    /// A session ID resolves against the project directory, which is what
    /// V96 says identity actually looks like. The id branch existed for the
    /// INFERRED case and was never carried to the named one (B14/B11).
    #[test]
    fn v104_a_bare_id_resolves_against_the_project_dir() {
        let (home, cwd, file) = planted_transcript("abc-123");
        let got = resolve_under_home(&home, &cwd, Some("abc-123"));
        assert_eq!(got, Ok((file.clone(), Origin::Argument)), "id resolved");
        let _ = std::fs::remove_file(&file);
    }

    /// The harness-offered id RESOLVING, which is V96's whole point: an id
    /// the harness knows beats a guess from the filesystem.
    ///
    /// Planted, and hermetic. This branch used to be reached only through
    /// the dogfood tests, which read whatever transcripts the machine
    /// holds -- so it was covered on a laptop with sessions and uncovered
    /// on a CI runner without them, and the coverage number differed by
    /// machine (B27).
    #[test]
    fn a_harness_id_that_resolves_wins_over_newest() {
        let (home, cwd, file) = planted_transcript("harness-wins");
        let got = resolve_with(
            None,
            Some(&cwd.to_string_lossy()),
            Some(home.clone()),
            Some("harness-wins".to_owned()),
        );
        assert_eq!(
            got,
            Ok((file.clone(), Origin::Harness)),
            "the id the harness offered, not a guess by mtime"
        );
        let _ = std::fs::remove_file(&file);
    }

    /// The diagnostic when there is no project directory to have searched.
    /// The other half (a directory that WAS searched) is pinned above; this
    /// is the branch where `chdir` resolves to nothing.
    #[test]
    fn a_miss_with_no_project_dir_says_so() {
        let msg = no_session("ghost", None);
        assert!(msg.contains("ghost"), "{msg}");
        assert!(msg.contains("no project directory"), "{msg}");
    }

    /// A source that resolved and then could not be READ is a named
    /// failure, not silence: it existed a moment ago, so an I/O fault must
    /// not read as an empty session. A directory is the portable way to
    /// hold a path that exists and is not readable as text.
    #[test]
    fn a_source_that_cannot_be_read_names_the_path() {
        let dir = std::env::temp_dir();
        let out = read_source(&dir)
            .err()
            .unwrap_or_else(|| Output::ok(String::new()));
        assert_eq!(out.code, 2, "a read fault is a usage error");
        assert!(out.err.contains("cannot read"), "{}", out.err);
        assert!(
            out.err.contains(&dir.display().to_string()),
            "names the path: {}",
            out.err
        );
    }

    /// An id the harness offers wins over newest-by-mtime -- but only if the
    /// transcript EXISTS. A stale variable pointing at a deleted session must
    /// fall back rather than resolve to nothing.
    ///
    /// HERMETIC, and it was not. This used to call `resolve_session(None,
    /// None)` against the AMBIENT home and cwd, then assert inside an
    /// `if let Ok(..)` -- so on a machine with no transcript directory for
    /// the current working directory it took the `Err` path and checked
    /// NOTHING while still reporting green. B3's rule, in the file that
    /// records B3's lesson: a test whose input is the machine it runs on
    /// asserts different things on two laptops.
    ///
    /// It was found by coverage, not by reading: the `if let` body is
    /// covered on linux and not on macOS, one line, which is exactly the
    /// margin between 98.01% and 97.99% against a 98% floor (B22). A
    /// vacuous test and a platform-dependent gate turned out to be the
    /// same defect.
    #[test]
    fn a_stale_harness_id_falls_back_instead_of_failing() {
        let (home, cwd, file) = planted_transcript("stale-fallback");
        let dir = cwd.to_string_lossy();
        let got = resolve_with(
            None,
            Some(&dir),
            Some(home.clone()),
            Some("no-such-session-id-xyz".to_owned()),
        );
        // Unconditional now: the planted transcript is the only candidate,
        // so the stale id MUST lose to newest-by-mtime and the answer is
        // known rather than whatever the machine happened to hold.
        assert_eq!(
            got,
            Ok((file.clone(), Origin::Newest)),
            "a stale harness id must fall back to newest, not resolve to \
             nothing and not win"
        );
        let _ = std::fs::remove_file(&file);
    }

    /// An empty or whitespace value is no offer at all: an empty string is
    /// not an id. The first REAL value wins, in variable order.
    #[test]
    fn an_empty_variable_is_not_an_offer() {
        let vals = |v: &[&str]| first_id(v.iter().map(|s| (*s).to_owned()));
        assert_eq!(vals(&["", "   ", "\t"]), None, "nothing offered");
        assert_eq!(
            vals(&["", "abc"]),
            Some("abc".to_owned()),
            "first real one"
        );
        assert_eq!(vals(&["  id  "]), Some("id".to_owned()), "trimmed");
        assert_eq!(vals(&[]), None);
    }
}

/// Apply the git-log selectors, in git's own order: filter, then reverse,
/// then limit. `-n` therefore keeps the NEWEST events, like `git log -n`
/// keeps the most recent commits (V1).
fn select(events: Vec<LoadEvent>, raw: &Raw) -> Vec<LoadEvent> {
    let mut rows = since(events, raw.since.as_deref());
    keep_newest(&mut rows, raw.limit.as_deref());
    if raw.reverse {
        rows.reverse();
    }
    rows
}

/// ISO-8601 sorts lexicographically, which is why a plain string
/// comparison is correct here and no date library is needed.
fn since(events: Vec<LoadEvent>, cutoff: Option<&str>) -> Vec<LoadEvent> {
    events
        .into_iter()
        .filter(|e| cutoff.is_none_or(|s| e.ts.as_str() >= s))
        .collect()
}

/// `-n` keeps the NEWEST events, like `git log -n` keeps the most recent
/// commits (V1). An unparsable count keeps everything, rather than
/// silently keeping none.
fn keep_newest(rows: &mut Vec<LoadEvent>, limit: Option<&str>) {
    let Some(n) = limit.and_then(|n| n.parse::<usize>().ok()) else {
        return;
    };
    let drop = rows.len().saturating_sub(n);
    rows.drain(..drop);
}

/// `bytes/4`, the only tier available without content (V45). The tilde in
/// the human view marks it crude, exactly as everywhere else (V3).
fn tokens(bytes: usize) -> usize {
    bytes / 4
}

fn kind(source: &Source) -> &'static str {
    match source {
        Source::Tool(_) => "tool",
        Source::Attachment(_) => "attachment",
    }
}

/// One line per event: time, what it came from, its estimated cost, and
/// the path when there is one.
fn report(rows: &[LoadEvent]) -> String {
    let mut out = String::new();
    for e in rows {
        out.push_str(&format!(
            "{}  {:<22} ~{:>7} itok  {}\n",
            time_of(&e.ts),
            e.source.label(),
            tokens(e.bytes),
            e.path.as_deref().unwrap_or(""),
        ));
    }
    out
}

/// The clock part of an ISO timestamp, which is what a chronological
/// listing needs; the date is the same for every line in a session.
fn time_of(ts: &str) -> &str {
    ts.split('T')
        .nth(1)
        .and_then(|t| t.get(..8))
        .unwrap_or("--:--:--")
}

/// One JSON object per event (V9). Carries the same `unit`/`estimated`/
/// `method` fields every other verb emits, so a parser learns them once.
fn json(rows: &[LoadEvent]) -> String {
    rows.iter().map(json_object).collect()
}

fn json_object(e: &LoadEvent) -> String {
    format!(
        "{{\"ts\":\"{}\",\"kind\":\"{}\",\"source\":\"{}\",\"path\":{},\
         \"bytes\":{},\"tokens\":{},\"unit\":\"input_tokens\",\
         \"estimated\":true,\"method\":\"bytes/4\"}}\n",
        escape(&e.ts),
        kind(&e.source),
        escape(e.source.label()),
        json_path(e.path.as_deref()),
        e.bytes,
        tokens(e.bytes),
    )
}

/// A quoted path, or the `null` literal -- never an empty string, which
/// would be indistinguishable from a path the tool failed to read.
fn json_path(path: Option<&str>) -> String {
    path.map_or_else(|| "null".to_owned(), |p| format!("\"{}\"", escape(p)))
}

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. Flags mirror `git log`'s, so there is nothing new to
/// learn (V1); a bare word is the session to read.
fn apply<'a>(
    a: &str,
    it: &mut impl Iterator<Item = &'a String>,
    raw: &mut Raw,
) -> Result<(), String> {
    match a {
        "--reverse" => raw.reverse = true,
        "-n" => raw.limit = Some(value(it, "-n")?),
        "--since" => raw.since = Some(value(it, "--since")?),
        "-C" => raw.chdir = Some(value(it, "-C")?),
        "--format" => raw.format = format_of(&value(it, "--format")?)?,
        "--bpe" | "--ollama" => return Err(no_real_tier(a, "trace")),
        other if other.starts_with('-') => {
            return Err(format!("unknown flag {other}"));
        }
        other => raw.session = Some(other.to_owned()),
    }
    Ok(())
}

/// Rejected, not ignored: no content is retained, so there is nothing
/// for a real tokenizer to count (V3/V45). Accepting the flag and
/// quietly producing an estimate would be the confident lie V3 forbids.
pub(crate) fn no_real_tier(flag: &str, verb: &str) -> String {
    format!(
        "{flag} is not available on {verb}: no content is stored, \
         so per-event sizes are always an estimate"
    )
}

/// The two documented output shapes; anything else is a usage error, the
/// same wording every other verb uses (V9).
pub(crate) fn format_of(s: &str) -> Result<Format, String> {
    match s {
        "json" => Ok(Format::Json),
        "human" => Ok(Format::Human),
        other => Err(format!("unknown format '{other}'")),
    }
}

pub(crate) fn value<'a>(
    it: &mut impl Iterator<Item = &'a String>,
    flag: &str,
) -> Result<String, String> {
    it.next()
        .cloned()
        .ok_or_else(|| format!("{flag} needs a value"))
}

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

    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()));
        trace(&args)
    }

    /// V46: one line per load event.
    #[test]
    fn one_line_per_event() {
        let out = run_on("tool-shapes.jsonl", &[]);
        assert_eq!(out.out.lines().count(), 4);
        assert_eq!(out.code, 0);
    }

    /// V46/V1: `-n` keeps the NEWEST events, like `git log -n`.
    #[test]
    fn limit_keeps_the_newest() {
        let out = run_on("tool-shapes.jsonl", &["-n", "2"]);
        let lines: Vec<&str> = out.out.lines().collect();
        assert_eq!(lines.len(), 2);
        assert!(lines.iter().any(|l| l.contains("two.txt")), "kept newest");
    }

    /// V46: `--reverse` flips the order, exactly as in git.
    #[test]
    fn reverse_flips_the_order() {
        let fwd = run_on("tool-shapes.jsonl", &[]);
        let rev = run_on("tool-shapes.jsonl", &["--reverse"]);
        let f: Vec<&str> = fwd.out.lines().collect();
        let mut r: Vec<&str> = rev.out.lines().collect();
        r.reverse();
        assert_eq!(f, r);
    }

    /// `--since` filters on the ISO timestamp. Lexicographic comparison is
    /// correct for ISO-8601, which is why no date library is needed.
    #[test]
    fn since_filters_by_iso_timestamp() {
        let all = run_on("tool-shapes.jsonl", &[]);
        let cut =
            run_on("tool-shapes.jsonl", &["--since", "2026-01-01T00:00:05"]);
        assert!(cut.out.lines().count() < all.out.lines().count());
        assert!(cut.out.contains("two.txt"), "later events survive");
    }

    /// V9: one JSON object per event, carrying the same unit/estimated/
    /// method fields every other verb emits.
    #[test]
    fn json_is_one_object_per_event() {
        let out = run_on("tool-shapes.jsonl", &["--format", "json"]);
        assert_eq!(out.out.lines().count(), 4);
        for line in out.out.lines() {
            assert!(line.starts_with('{') && line.ends_with('}'));
            assert!(line.contains("\"unit\":\"input_tokens\""));
            assert!(line.contains("\"estimated\":true"));
            assert!(line.contains("\"method\":\"bytes/4\""));
        }
    }

    /// V3: no tilde ever appears in a numeric JSON field; the human view
    /// carries it instead.
    #[test]
    fn the_tilde_is_human_only() {
        assert!(run_on("tool-shapes.jsonl", &[]).out.contains('~'));
        assert!(
            !run_on("tool-shapes.jsonl", &["--format", "json"])
                .out
                .contains('~')
        );
    }

    /// V3/V45: a real tokenizer is REJECTED rather than accepted and
    /// ignored -- no content is stored, so there is nothing to count.
    #[test]
    fn a_real_tier_is_refused_not_ignored() {
        for flag in ["--bpe", "--ollama"] {
            let out = run_on("tool-shapes.jsonl", &[flag]);
            assert_eq!(out.code, 2, "{flag} must be a usage error");
            assert!(out.err.contains("no content is stored"));
        }
    }

    /// 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 `trace --bpe` two tests up has always
    /// exited 2 on the same verb.
    #[test]
    fn a_named_miss_is_a_usage_error() {
        let out = trace(&["/nonexistent/session.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);
    }

    /// V43: a torn tail must not change the answer, so a session still
    /// being written reports the same thing twice.
    #[test]
    fn a_torn_tail_does_not_break_the_listing() {
        let out = run_on("torn-tail.jsonl", &[]);
        assert_eq!(out.code, 0);
    }

    /// V78: an attachment is a load event too, and it is labelled as a
    /// different KIND than a tool result so a parser can tell them apart.
    #[test]
    fn attachments_are_listed_and_kinded() {
        let out = run_on("weird.jsonl", &["--format", "json"]);
        assert!(out.out.contains("\"kind\":\"attachment\""));
        assert!(out.out.contains("\"source\":\"hook_success\""));
        // A tool result with no path reports null, never an empty string.
        assert!(out.out.contains("\"path\":null"));
    }

    /// `--format human` is the default AND spellable, like every verb.
    #[test]
    fn human_format_is_default_and_explicit() {
        let a = run_on("tool-shapes.jsonl", &[]);
        let b = run_on("tool-shapes.jsonl", &["--format", "human"]);
        assert_eq!(a.out, b.out);
    }

    #[test]
    fn a_bad_format_is_a_usage_error() {
        let out = run_on("tool-shapes.jsonl", &["--format", "yaml"]);
        assert_eq!(out.code, 2);
        assert!(out.err.contains("unknown format"));
    }

    /// A flag that needs a value and does not get one is a usage error,
    /// not a silent default.
    #[test]
    fn a_flag_missing_its_value_errors() {
        let out = run_on("tool-shapes.jsonl", &["-n"]);
        assert_eq!(out.code, 2);
        assert!(out.err.contains("needs a value"));
    }

    /// Discovery: with no session argument and no transcript for the
    /// directory, there is nothing to report -- and that is exit 0 (V5).
    #[test]
    fn no_session_and_no_transcript_is_empty() {
        let dir = std::env::temp_dir()
            .join(format!("itok-tr-none-{}", std::process::id()));
        std::fs::create_dir_all(&dir).ok();
        let out = trace(&["-C".to_owned(), dir.display().to_string()]);
        assert_eq!(out.code, 0);
        assert!(out.out.is_empty());
    }

    #[test]
    fn unknown_flags_are_usage_errors() {
        let out = run_on("tool-shapes.jsonl", &["--nope"]);
        assert_eq!(out.code, 2);
    }
}