agx-tui 0.2.1

Step-through debugger for your agent โ€” terminal-native session timeline viewer for Claude Code, Codex, Gemini, LangChain, Vercel AI SDK, and OpenTelemetry GenAI traces
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
// Modules live in `src/lib.rs` (the agx library crate) so the bench
// harness under `benches/` and future integration tests can reuse them
// without duplicating code. This binary is a thin shell around the
// library.
use agx::{
    annotations, browser, corpus, debug_unknowns, diff_tui, export, format, loader, pii, slice,
    timeline::{Step, compute_session_totals, compute_tool_stats, count_from_steps},
    tui,
};
use anyhow::Result;
use clap::{CommandFactory, Parser, Subcommand, ValueEnum};
use clap_complete::{Shell, generate};
use loader::load_session;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

#[derive(Copy, Clone, Debug, ValueEnum)]
enum ExportFormat {
    Md,
    Html,
    Json,
    /// OpenAI fine-tuning JSONL (one JSON object per session,
    /// `{messages: [{role, content, tool_calls?, tool_call_id?}]}`).
    /// See docs/suite-conventions.md ยง5 for the stability contract.
    #[value(name = "trajectory-openai")]
    TrajectoryOpenai,
}

#[derive(Parser, Debug)]
#[command(name = "agx", version, about = "Step-through debugger for your agent")]
struct Cli {
    /// Path to a session file (Claude Code JSONL, Codex CLI JSONL, or Gemini CLI JSON).
    /// Omit to browse recent sessions from ~/.claude, ~/.codex, and ~/.gemini.
    session: Option<PathBuf>,

    /// Print a summary of the parsed timeline and exit (no TUI)
    #[arg(long)]
    summary: bool,

    /// Compare two sessions side-by-side (text summary)
    #[arg(long)]
    diff: Option<PathBuf>,

    /// Launch the interactive side-by-side diff TUI instead of the
    /// text summary. Requires `--diff <path>`. Mutually exclusive
    /// with `--summary` / `--export` since those own stdout.
    #[arg(long, requires = "diff", conflicts_with_all = ["summary", "export"])]
    diff_tui: bool,

    /// Live mode: watch for file changes and auto-refresh
    #[arg(long)]
    live: bool,

    /// Generate shell completions and print to stdout
    #[arg(long, value_name = "SHELL")]
    completions: Option<Shell>,

    /// Scan the session for entry types or fields the parser doesn't recognize
    /// and print a report to stderr. Useful for diagnosing format drift.
    #[arg(long)]
    debug_unknowns: bool,

    /// Heuristic scan for PII / credentials in tool outputs and step
    /// detail. Reports matches by category (email, api-key shape,
    /// JWT, IPv4, SSH private-key header) with step index. Does NOT
    /// mutate โ€” pair with `--redact` when the intent is to scrub.
    /// Output: human-readable text by default, JSON when combined
    /// with `--export json`. Phase 6.4 dataset-prep workflow.
    #[arg(long)]
    scan_pii: bool,

    /// Suppress cost estimates in --summary, stats overlay, and TUI status
    /// bar. Token counts are still shown. Use when working with unpriced
    /// custom models or when cost estimates are noise.
    #[arg(long)]
    no_cost: bool,

    /// Export the session to stdout in the given format instead of
    /// launching the TUI. Mutually exclusive with --summary.
    #[arg(long, value_enum, value_name = "FORMAT")]
    export: Option<ExportFormat>,

    /// Mask literal substrings in exported output (tool inputs and
    /// tool results). Repeat the flag to mask multiple patterns. Every
    /// match is replaced with `[REDACTED]`. Useful before publishing
    /// trajectories as a training dataset โ€” strip API keys, paths,
    /// usernames that crept into shell output. Applies to every
    /// `--export` format.
    #[arg(long, value_name = "NEEDLE")]
    redact: Vec<String>,

    /// Print load / parse / render timing breakdown to stderr. Hidden
    /// diagnostic flag for performance-regression reports.
    #[arg(long, hide = true)]
    bench: bool,

    /// Only include steps at or after this offset from the session's
    /// first step. Duration grammar: `30s` / `5m` / `2h` / `1d`, or
    /// compounds like `1h30m`, or a bare integer (seconds). Applied
    /// after load, before rendering.
    #[arg(long, value_name = "DURATION")]
    after: Option<String>,

    /// Only include steps strictly before this offset from the
    /// session's first step. Same duration grammar as `--after`.
    #[arg(long, value_name = "DURATION")]
    before: Option<String>,

    /// Only include steps at or after this 0-based index.
    #[arg(long, value_name = "N", conflicts_with = "range")]
    after_step: Option<usize>,

    /// Only include steps strictly before this 0-based index.
    #[arg(long, value_name = "N", conflicts_with = "range")]
    before_step: Option<usize>,

    /// Shorthand for combining --after-step and --before-step.
    /// Syntax: `start..end` (exclusive end), or open-ended `..500`,
    /// `100..`, or just `..` for a no-op.
    #[arg(long, value_name = "RANGE")]
    range: Option<String>,

    /// Launch the TUI with the cursor pre-positioned at this 0-indexed
    /// step. Clamps to the visible range (post-slice). Ignored in
    /// `--summary` / `--export` / `--diff`-text modes since those don't
    /// render a cursor. The public contract for sift's Timeline-jump
    /// integration per docs/suite-conventions.md ยง5 โ€” sift's `t`
    /// keybind in `sift review` spawns `agx --jump-to <N> <session>`
    /// to land the user directly on the step a pending write came
    /// from.
    #[arg(long, value_name = "STEP")]
    jump_to: Option<usize>,

    /// In `--live` mode, fire a desktop notification whenever a newly
    /// arrived `tool_result` looks like a failure (per the
    /// `is_error_result` heuristic). Requires `--live`. Opt-in compile
    /// feature: rebuild with `--features notifications`.
    #[arg(long, requires = "live")]
    notify_on_error: bool,

    /// In `--live` mode, fire a desktop notification when the watched
    /// session hasn't grown for this duration. Same grammar as
    /// `--after` (`30s` / `5m` / `1h`, compounds, bare-int seconds).
    /// Requires `--live`. Opt-in compile feature: rebuild with
    /// `--features notifications`.
    #[arg(long, value_name = "DURATION", requires = "live")]
    notify_on_idle: Option<String>,

    /// Phase 5.4 โ€” announces intent to use the experimental
    /// tool-call replay feature. Without this flag, `R` in the TUI
    /// is inert. Gated on top of this per-backend flags
    /// (`--allow-shell-replay` for Bash). Even with both flags,
    /// every replay still requires a `y` confirm in the TUI.
    #[arg(long, hide = true)]
    experimental_replay: bool,

    /// Phase 5.4 โ€” allow shell-backend replays. Requires
    /// `--experimental-replay`. When set, `R` on a Bash tool_use
    /// step spawns `/bin/sh -c "<command>"` (with per-invocation
    /// confirm). Output appends to `<session>.replay.log` as JSONL;
    /// the original session file is never modified.
    #[arg(long, hide = true, requires = "experimental_replay")]
    allow_shell_replay: bool,

    /// Optional subcommand. When present, overrides the single-session
    /// flow. Today only `corpus` exists โ€” it aggregates stats across
    /// every session file in a directory tree.
    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// Scan a directory tree, load every session in parallel, and print
    /// aggregate stats (per-model / per-tool / per-format breakdowns,
    /// totals, and cost). Unrecognized files are silently skipped.
    Corpus(CorpusArgs),
    /// Health-check report โ€” agx version, default features, and
    /// which stepwise siblings (sift, rgx, agx-mcp) are installed.
    /// Matches `sift doctor` per docs/suite-conventions.md ยง2.
    Doctor(DoctorArgs),
}

#[derive(clap::Args, Debug)]
struct DoctorArgs {
    /// Emit the report as JSON instead of a human-readable summary.
    /// Shape:
    /// `{agx: {state, version, features},
    ///   agx_mcp / sift / rgx: {state, version?}}`
    /// where state โˆˆ {"ok", "missing", "unknown"}.
    #[arg(long)]
    json: bool,
}

#[derive(clap::Args, Debug)]
struct CorpusArgs {
    /// Directory to scan. Walks recursively up to `--max-depth`.
    dir: PathBuf,

    /// Keep only sessions matching ALL of the given filters. Value shapes:
    /// `model=<name>`, `tool=<name>`, or the bare keyword `errored`.
    /// Can be repeated.
    #[arg(long, value_name = "FILTER")]
    filter: Vec<String>,

    /// Emit the aggregate stats as JSON instead of a human-readable summary.
    #[arg(long)]
    json: bool,

    /// Suppress cost estimates (mirror of the top-level --no-cost flag).
    #[arg(long)]
    no_cost: bool,

    /// Maximum directory-tree depth to walk. Default is 8, enough for
    /// every format's canonical storage layout (Claude Code's
    /// `~/.claude/projects/<encoded>/<uuid>.jsonl` sits at depth 4 from
    /// `~/.claude`, Codex at depth 5 from `~/.codex`, etc.).
    #[arg(long, default_value_t = 8)]
    max_depth: usize,

    /// Print walk / load / aggregate timing breakdown to stderr.
    #[arg(long, hide = true)]
    bench: bool,

    /// Launch the interactive corpus TUI โ€” session list + selected-session
    /// summary + drill-in to per-session step-through. Mutually exclusive
    /// with `--json` / `--jsonl` (TUI owns the terminal).
    #[arg(long, conflicts_with_all = ["json", "jsonl"])]
    tui: bool,

    /// Emit one JSON object per session to stdout (line-delimited JSON,
    /// not pretty-printed). Parse errors go to stderr. Pipe into `jq`
    /// / `xargs` / a file for eval or CI pipelines.
    #[arg(long, conflicts_with = "json")]
    jsonl: bool,

    /// Exit with a nonzero status when any parse error or any tool-error
    /// result is present in the corpus. Orthogonal to rendering mode;
    /// combine with any of --json / --jsonl / --tui / default text.
    #[arg(long)]
    fail_on_errored: bool,

    /// Replace the default aggregate output with a distributional
    /// breakdown: per-session percentiles (min / p50 / p90 / p99 /
    /// max / mean / total) for steps, tool calls, tokens_in, tokens_out;
    /// plus branched / annotated / errored rates. Combines with
    /// `--json` for machine-readable output. Phase 6.2 spot-check
    /// for dataset prep.
    #[arg(long)]
    trajectory_stats: bool,

    /// Keep only the N most-recent sessions (by mtime descending)
    /// after filters. Applied *after* `--filter` so
    /// `--filter model=X --sample 20` gives the 20 newest X-model
    /// sessions. Deterministic โ€” random sampling is a follow-up
    /// tracked in the roadmap.
    #[arg(long, value_name = "N")]
    sample: Option<usize>,
}

// `load_session` itself lives in src/loader.rs so both the single-session
// flow below and the corpus subcommand dispatch through the same entry.

/// Print a PII scan report to stdout. Groups matches by category and
/// shows the first match from each category with its step index. The
/// intent is "fast glance โ€” do I have anything to redact before
/// publishing this session?" rather than a full secrets-management
/// tool. Exit code 0 whether or not matches are found (the dataset-
/// prep workflow is iterative โ€” scan, redact, re-scan).
/// Probe a sibling tool by spawning `<tool> --version`. Returns
/// `None` when the binary isn't on PATH or the spawn fails;
/// returns `Some(stdout.trim().first_line())` on success. The first
/// line convention matches every stepwise tool โ€” their
/// `--version` output starts with `name X.Y.Z` on line 1 and may
/// have feature banners or build info on subsequent lines.
fn probe_tool_version(bin: &str) -> Option<String> {
    use std::process::Command;
    let output = Command::new(bin).arg("--version").output().ok()?;
    if !output.status.success() {
        return None;
    }
    let stdout = String::from_utf8_lossy(&output.stdout);
    let first_line = stdout.lines().next()?.trim().to_string();
    if first_line.is_empty() {
        None
    } else {
        Some(first_line)
    }
}

/// Render the doctor report. Matches the four-state shape from
/// `sift doctor` (sift uses `ok / too-old / unknown / missing`);
/// agx v0.1 ships only the `ok` / `missing` / `unknown` states
/// because the cross-tool compat table doesn't commit to version
/// floors yet. `too-old` becomes meaningful once the table lands
/// minimums โ€” per docs/stability.md.
fn run_doctor(args: &DoctorArgs) -> Result<()> {
    // Self: we know our own version statically.
    let agx_version = env!("CARGO_PKG_VERSION").to_string();
    // Feature list โ€” populated at compile time so the output reflects
    // the actual binary's capabilities.
    let mut features: Vec<&'static str> = Vec::new();
    if cfg!(feature = "otel-proto") {
        features.push("otel-proto");
    }
    if cfg!(feature = "embedding-search") {
        features.push("embedding-search");
    }
    if cfg!(feature = "notifications") {
        features.push("notifications");
    }

    // Siblings: agx-mcp / sift / rgx. Probed in the same order as
    // the suite-conventions ยง2 table so humans scanning the output
    // see the expected reading order.
    let agx_mcp = probe_tool_version("agx-mcp");
    let sift = probe_tool_version("sift");
    let rgx = probe_tool_version("rgx");

    if args.json {
        let mut payload = serde_json::Map::new();
        payload.insert(
            "agx".into(),
            serde_json::json!({
                "state": "ok",
                "version": agx_version,
                "features": features,
            }),
        );
        payload.insert("agx_mcp".into(), sibling_json(&agx_mcp));
        payload.insert("sift".into(), sibling_json(&sift));
        payload.insert("rgx".into(), sibling_json(&rgx));
        println!("{}", serde_json::to_string_pretty(&payload)?);
        return Ok(());
    }

    // Text output โ€” fixed-width label column so entries align in a
    // terminal without reaching for a tabwriter crate.
    println!("agx doctor\n");
    let feat = if features.is_empty() {
        "default".to_string()
    } else {
        features.join(", ")
    };
    println!("  {:<10} ok     ({agx_version}, features: {feat})", "agx:");
    print_sibling("agx-mcp:", agx_mcp.as_deref());
    print_sibling("sift:", sift.as_deref());
    print_sibling("rgx:", rgx.as_deref());

    let detected = [&agx_mcp, &sift, &rgx]
        .iter()
        .filter(|v| v.is_some())
        .count();
    println!("\nstepwise suite: {} of 3 siblings present", detected);
    Ok(())
}

fn sibling_json(version: &Option<String>) -> serde_json::Value {
    match version {
        Some(v) => serde_json::json!({"state": "ok", "version": v}),
        None => serde_json::json!({"state": "missing"}),
    }
}

fn print_sibling(label: &str, version: Option<&str>) {
    match version {
        Some(v) => println!("  {:<10} ok     ({v})", label),
        None => println!("  {:<10} missing", label),
    }
}

fn print_pii_scan(steps: &[Step]) {
    use std::collections::BTreeMap;
    let matches = pii::scan_steps(steps);
    if matches.is_empty() {
        println!("agx --scan-pii: no matches");
        return;
    }
    // Group by category for a tidy summary. BTreeMap keeps the
    // output order stable across runs.
    let mut by_cat: BTreeMap<&str, Vec<&pii::Match>> = BTreeMap::new();
    for m in &matches {
        by_cat.entry(m.category.label()).or_default().push(m);
    }
    println!(
        "agx --scan-pii: {} match(es) across {} categor(ies)",
        matches.len(),
        by_cat.len()
    );
    for (cat, hits) in &by_cat {
        let first = hits.first().expect("non-empty by construction");
        // Show up to 3 step indices so users can jump-to them via
        // `--jump-to`. Truncated when > 3.
        let step_preview: Vec<String> = hits
            .iter()
            .take(3)
            .map(|h| format!("step {}", h.step_index + 1))
            .collect();
        let more = if hits.len() > 3 {
            format!(" (+{} more)", hits.len() - 3)
        } else {
            String::new()
        };
        println!(
            "  {cat:<24} {:>3} match(es)  [{}]{more}  eg: {}",
            hits.len(),
            step_preview.join(", "),
            truncate_for_display(&first.snippet, 40),
        );
    }
    println!();
    println!(
        "agx: to scrub these, pipe back through `--redact <NEEDLE>` or `--export trajectory-openai --redact โ€ฆ`"
    );
}

/// Truncate a string for terminal display, keeping the head and
/// appending `โ€ฆ` when trimmed. Used by the PII scan output only.
fn truncate_for_display(s: &str, n: usize) -> String {
    let head: String = s.chars().take(n).collect();
    if s.chars().count() > n {
        format!("{head}โ€ฆ")
    } else {
        head
    }
}

fn print_diff(path_a: &Path, steps_a: &[Step], path_b: &Path, steps_b: &[Step]) {
    let fmt_a = format::detect(path_a).map_or_else(|_| "?".into(), |f| f.to_string());
    let fmt_b = format::detect(path_b).map_or_else(|_| "?".into(), |f| f.to_string());
    let counts_a = count_from_steps(steps_a);
    let counts_b = count_from_steps(steps_b);
    let stats_a = compute_tool_stats(steps_a);
    let stats_b = compute_tool_stats(steps_b);

    println!("agx diff\n");
    println!(
        "  {:<40} {:<40}",
        format!("A: {} ({})", fmt_a, path_a.display()),
        format!("B: {} ({})", fmt_b, path_b.display())
    );
    println!();
    println!(
        "  {:<40} {:<40}",
        format!("Steps: {}", steps_a.len()),
        format!("Steps: {}", steps_b.len())
    );
    println!(
        "  {:<40} {:<40}",
        format!(
            "user:{} asst:{} tool:{} result:{}",
            counts_a.user, counts_a.assistant, counts_a.tool_uses, counts_a.tool_results
        ),
        format!(
            "user:{} asst:{} tool:{} result:{}",
            counts_b.user, counts_b.assistant, counts_b.tool_uses, counts_b.tool_results
        ),
    );
    println!();

    let names_a: HashSet<String> = stats_a.iter().map(|s| s.name.clone()).collect();
    let names_b: HashSet<String> = stats_b.iter().map(|s| s.name.clone()).collect();

    // Build lookup maps once so the pairing loop is O(both) instead of
    // O(both ยท |stats|) linear scans, and no longer needs `.unwrap()`.
    let map_a: HashMap<&str, &agx::timeline::ToolStats> =
        stats_a.iter().map(|s| (s.name.as_str(), s)).collect();
    let map_b: HashMap<&str, &agx::timeline::ToolStats> =
        stats_b.iter().map(|s| (s.name.as_str(), s)).collect();

    let both: Vec<&String> = names_a.intersection(&names_b).collect();
    println!("  Tools in both ({}):", both.len());
    for name in &both {
        let Some((a, b)) = map_a.get(name.as_str()).zip(map_b.get(name.as_str())) else {
            continue;
        };
        #[allow(clippy::cast_possible_wrap)]
        let delta = b.use_count as i64 - a.use_count as i64;
        let sign = if delta >= 0 { "+" } else { "" };
        println!(
            "    {:<20} A:{:<4} B:{:<4} ({sign}{delta})",
            name, a.use_count, b.use_count
        );
    }
    let only_a: Vec<&String> = names_a.difference(&names_b).collect();
    let only_b: Vec<&String> = names_b.difference(&names_a).collect();
    if !only_a.is_empty() {
        let list: Vec<&str> = only_a.iter().map(|s| s.as_str()).collect();
        println!("  Tools only in A: {}", list.join(", "));
    }
    if !only_b.is_empty() {
        let list: Vec<&str> = only_b.iter().map(|s| s.as_str()).collect();
        println!("  Tools only in B: {}", list.join(", "));
    }

    let errors_a: usize = stats_a.iter().map(|s| s.error_count).sum();
    let errors_b: usize = stats_b.iter().map(|s| s.error_count).sum();
    println!();
    println!(
        "  {:<40} {:<40}",
        format!("Errors: {errors_a}"),
        format!("Errors: {errors_b}")
    );
}

fn main() -> Result<()> {
    let cli = Cli::parse();

    if let Some(shell) = cli.completions {
        let mut cmd = Cli::command();
        generate(shell, &mut cmd, "agx", &mut std::io::stdout());
        return Ok(());
    }

    // `agx doctor` is the smallest and most stateless subcommand โ€”
    // dispatch before corpus so a user without a session can still
    // ask "what's installed?" without seeing any of the single-
    // session scaffolding errors.
    if let Some(Commands::Doctor(args)) = &cli.command {
        return run_doctor(args);
    }

    // `agx corpus <dir>` subcommand takes over before the single-session
    // flow when the user asks for corpus-level analytics.
    if let Some(Commands::Corpus(args)) = cli.command {
        let filters = args
            .filter
            .iter()
            .map(|s| corpus::Filter::parse(s))
            .collect::<Result<Vec<_>>>()?;
        let corpus_args = corpus::CorpusArgs {
            dir: args.dir,
            filters,
            json: args.json,
            no_cost: args.no_cost,
            max_depth: args.max_depth,
            bench: args.bench,
            tui: args.tui,
            jsonl: args.jsonl,
            fail_on_errored: args.fail_on_errored,
            trajectory_stats: args.trajectory_stats,
            sample: args.sample,
        };
        // agx-core doesn't carry TUI deps, so it can't drop into
        // the interactive corpus TUI itself. The bin crate owns
        // `corpus_tui::run`; thread it through as the launcher.
        return corpus::run(&corpus_args, &|parsed, stats, no_cost| {
            agx::corpus_tui::run(parsed, stats, no_cost)
        });
    }

    let session_path = if let Some(p) = cli.session {
        p
    } else if cli.diff.is_some() {
        return Err(anyhow::anyhow!(
            "--diff requires a session path as the first argument"
        ));
    } else {
        let files = browser::discover_all();
        match browser::prompt_user_to_choose(&files)? {
            Some(p) => p,
            None => return Ok(()),
        }
    };

    if cli.debug_unknowns {
        let fmt = format::detect(&session_path)?;
        let report = debug_unknowns::scan(fmt, &session_path)?;
        report.print(&mut std::io::stderr())?;
    }

    // Bench timing wraps the whole load path so users filing perf issues
    // can attach a concrete number. Writes to stderr so stdout stays
    // pipeable for --summary / --export.
    let load_start = std::time::Instant::now();
    let steps = load_session(&session_path)?;
    if cli.bench {
        eprintln!(
            "[bench] load: {:.2}ms ({} steps)",
            load_start.elapsed().as_secs_f64() * 1000.0,
            steps.len()
        );
    }

    // Resolve and apply slicing (--range / --after-step / --before-step /
    // --after / --before). The range string takes precedence over the
    // scalar step bounds (clap-level `conflicts_with = "range"` on the
    // scalars means we won't see both from the same invocation, but
    // checking here keeps the precedence obvious).
    let range = if let Some(r) = cli.range.as_deref() {
        slice::parse_step_range(r)?
    } else {
        slice::step_range_from_bounds(cli.after_step, cli.before_step)
    };
    let after_ms = cli
        .after
        .as_deref()
        .map(slice::parse_duration_ms)
        .transpose()?;
    let before_ms = cli
        .before
        .as_deref()
        .map(slice::parse_duration_ms)
        .transpose()?;
    slice::warn_if_time_filter_ignored(&steps, after_ms, before_ms);
    let sliced_any = !range.is_identity() || after_ms.is_some() || before_ms.is_some();
    let steps = if sliced_any {
        let before_count = steps.len();
        let sliced = slice::slice_steps(steps, &range, after_ms, before_ms);
        if cli.bench {
            eprintln!("[bench] slice: {} โ†’ {} steps", before_count, sliced.len());
        }
        sliced
    } else {
        steps
    };

    if cli.scan_pii {
        // PII scan is a non-interactive mode that takes over stdout;
        // mutually compatible with slice flags (scan operates on the
        // already-sliced steps) but not with TUI or export flows.
        print_pii_scan(&steps);
        return Ok(());
    }

    if let Some(diff_path) = &cli.diff {
        let steps_b = load_session(diff_path)?;
        if cli.diff_tui {
            // Interactive two-pane diff โ€” requires both session formats
            // for the header labels.
            let fmt_a =
                format::detect(&session_path).map_or_else(|_| "?".into(), |f| f.to_string());
            let fmt_b = format::detect(diff_path).map_or_else(|_| "?".into(), |f| f.to_string());
            diff_tui::run(
                &steps,
                &steps_b,
                &session_path,
                diff_path,
                &fmt_a,
                &fmt_b,
                cli.no_cost,
            )?;
        } else {
            print_diff(&session_path, &steps, diff_path, &steps_b);
        }
        return Ok(());
    }

    if let Some(fmt) = cli.export {
        // Redact first (no-op when `--redact` wasn't passed), then
        // recompute totals on the redacted shape so any model /
        // token counts that happened to contain a redacted substring
        // stay internally consistent. Every exporter below sees the
        // same redacted slice.
        let steps = export::redacted_steps(&steps, &cli.redact);
        let totals = compute_session_totals(&steps);
        // Load annotations eagerly for export so the rendered output
        // reflects on-disk notes. Fault-tolerant: a missing or malformed
        // notes file returns an empty set without erroring.
        let annotations = annotations::Annotations::load_for(&session_path);
        let ann_ref = if annotations.is_empty() {
            None
        } else {
            Some(&annotations)
        };
        let out = match fmt {
            ExportFormat::Json => export::json(&steps, &totals, ann_ref)?,
            ExportFormat::Md => export::markdown(&steps, &totals, cli.no_cost, ann_ref),
            ExportFormat::Html => export::html(&steps, &totals, cli.no_cost, ann_ref),
            ExportFormat::TrajectoryOpenai => export::trajectory_openai(&steps)?,
        };
        print!("{out}");
        return Ok(());
    }

    if cli.summary {
        let fmt = format::detect(&session_path)?;
        let counts = count_from_steps(&steps);
        let totals = compute_session_totals(&steps);
        println!("Loaded {} session from {}", fmt, session_path.display());
        println!(
            "  {} timeline steps: {} user, {} assistant, {} tool_uses, {} tool_results",
            steps.len(),
            counts.user,
            counts.assistant,
            counts.tool_uses,
            counts.tool_results
        );
        if totals.has_tokens() {
            println!(
                "  {} input tokens, {} output, {} cache_read, {} cache_create",
                totals.tokens_in, totals.tokens_out, totals.cache_read, totals.cache_create
            );
        }
        if !totals.unique_models.is_empty() {
            println!("  models: {}", totals.unique_models.join(", "));
        }
        if !cli.no_cost {
            match totals.cost_usd {
                Some(c) => println!("  estimated cost: ${c:.4} USD"),
                None if totals.has_tokens() => {
                    println!("  estimated cost: (unknown โ€” no pricing entry for model)")
                }
                None => {}
            }
        }
        println!("First 20:");
        for (i, step) in steps.iter().take(20).enumerate() {
            println!("  {:>3}  {}", i + 1, step.label);
        }
        return Ok(());
    }

    let reload_fn: Option<Box<dyn Fn() -> Result<Vec<Step>>>> = if cli.live {
        let path = session_path.clone();
        Some(Box::new(move || load_session(&path)))
    } else {
        None
    };

    // Build the notify config. Idle duration parsing reuses the same
    // duration grammar as `--after` / `--before` for consistency. When
    // the `notifications` feature is off and the user passed a flag,
    // print a one-time stderr hint so the flag isn't silently a no-op
    // and proceed without notifications (same posture as the
    // semantic-search feature-off dispatch).
    let notify_idle_ms = match cli.notify_on_idle.as_deref() {
        Some(s) => match agx::slice::parse_duration_ms(s) {
            Ok(ms) => Some(ms),
            Err(e) => {
                eprintln!("agx: ignoring --notify-on-idle `{s}`: {e}");
                None
            }
        },
        None => None,
    };
    if (cli.notify_on_error || notify_idle_ms.is_some()) && !cfg!(feature = "notifications") {
        eprintln!("agx: {}", agx::notify::FEATURE_DISABLED_MESSAGE);
    }
    let notify_cfg = tui::NotifyConfig {
        on_error: cli.notify_on_error,
        on_idle_ms: notify_idle_ms,
    };

    let replay_cfg = agx::replay::ReplayConfig {
        enabled: cli.experimental_replay,
        allow_shell: cli.allow_shell_replay,
    };

    tui::run(
        steps,
        reload_fn.as_deref(),
        cli.no_cost,
        Some(&session_path),
        cli.jump_to,
        notify_cfg,
        replay_cfg,
    )?;
    Ok(())
}