clustervision 0.14.0

clustervision CLI — search, read, and port AI coding-agent sessions across harnesses.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
//! `cv` — the clustervision CLI.
//!
//! This file holds only the clap surface (`Cli`/`Cmd`), the command groups, and the dispatch into
//! the per-command modules under `cmd/`; shared helpers live in `util.rs` and `cv blame` in `blame.rs`.
//!
//! Interface v2 (0.11.0, `docs/INTERFACE-V2.md`): one verb per act, the same flag means the same
//! thing everywhere, snake_case JSON, no hidden commands. Old names are hidden stubs that error
//! with a pointer and exit 2 — never aliases that work.

mod blame;
mod cmd;
mod util;

// Crate-root re-exports for `blame.rs`, which renders conversation windows via the same
// streaming renderer `cv show` uses.
pub(crate) use cmd::view::{show_header, show_message, stream_session_render, RenderOpts};
pub(crate) use util::short_id;

use anyhow::{Context, Result};
use clap::{CommandFactory, FromArgMatches, Parser, Subcommand};
use cmd::live::BoardCmd;
use cmd::task::TaskCmd;
use cmd::{
    browse, cat, compose, config, doctor, formats, live, orchestrate, pack, port, provenance, recipes, schema, search,
    share, task, view, workflow,
};
use std::path::PathBuf;
use util::{usage, UsageError, WindowArgs};

/// Resolve the caller-supplied `--declassify` term list from a CSV flag and/or a file (one term per
/// line, `#` comments + blanks ignored). Terms are lowercased + de-duplicated. cv ships NO built-in
/// list — the terms are always external (config/data), so cv's own source carries no domain shitlist.
fn resolve_declassify_tokens(csv: Option<String>, file: Option<PathBuf>) -> Result<Vec<String>> {
    let mut seen = std::collections::BTreeSet::new();
    let mut out = Vec::new();
    let mut push = |t: &str| {
        let t = t.trim().to_ascii_lowercase();
        if !t.is_empty() && seen.insert(t.clone()) {
            out.push(t);
        }
    };
    if let Some(csv) = csv {
        for t in csv.split(',') {
            push(t);
        }
    }
    if let Some(path) = file {
        let body = std::fs::read_to_string(&path)
            .with_context(|| format!("reading --declassify-tokens-file {}", path.display()))?;
        for line in body.lines() {
            let line = line.split('#').next().unwrap_or("");
            push(line);
        }
    }
    Ok(out)
}

/// Version with the embedded build commit (set by build.rs; "unknown" outside git), so the
/// binary in your PATH is checkable against source.
const BUILD_VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", env!("CV_BUILD_SHA"), ")");

/// The command groups `cv --help` prints and `cv schema --commands` reports. clap renders
/// subcommands as one flat list (its `next_help_heading` tags *arguments*), so the grouping lives
/// here; `groups_cover_every_visible_command` keeps this table and the `Cmd` enum in lockstep.
pub(crate) const GROUPS: &[(&str, &[&str])] = &[
    (
        "Read",
        &[
            "ls",
            "show",
            "cat",
            "search",
            "events",
            "touched",
            "tools",
            "tree",
            "workflow",
            "compaction",
            "prompts",
            "lanes",
            "deferrals",
            "timeline",
            "stats",
            "diff",
            "blame",
            "doctor",
        ],
    ),
    (
        "Reshape",
        &[
            "prune", "rewind", "distill", "fork", "adopt", "splice", "loom", "port", "redact", "resume",
        ],
    ),
    ("Export", &["export", "dataset", "pack"]),
    ("Fleet & live", &["task", "board", "scry", "share"]),
    ("System", &["index", "config", "schema", "formats", "recipes"]),
];

/// The group a visible command belongs to (`None` for hidden stubs and unknown names).
pub(crate) fn group_of(name: &str) -> Option<&'static str> {
    GROUPS.iter().find(|(_, cmds)| cmds.contains(&name)).map(|(g, _)| *g)
}

const RECIPES_FOOTER: &str = "run `cv recipes` for the agent quickstart";

/// The grouped command listing that replaces clap's flat `Commands:` block — every visible
/// subcommand under its group, each with clap's own `about` line, then the recipes pointer.
fn grouped_help(cmd: &clap::Command) -> String {
    let width = cmd
        .get_subcommands()
        .filter(|s| !s.is_hide_set())
        .map(|s| s.get_name().len())
        .max()
        .unwrap_or(8);
    let mut out = String::from("Commands:\n");
    for (group, names) in GROUPS {
        out.push_str(&format!("  {group}\n"));
        for name in names.iter() {
            let Some(sub) = cmd.get_subcommands().find(|s| s.get_name() == *name) else {
                continue;
            };
            let about = sub.get_about().map(|a| a.to_string()).unwrap_or_default();
            out.push_str(&format!("    {name:<width$}  {about}\n"));
        }
    }
    out.push('\n');
    out.push_str(RECIPES_FOOTER);
    out
}

#[derive(Parser)]
#[command(
    name = "cv",
    version = BUILD_VERSION,
    about = "clustervision — search, read, and port AI agent sessions across harnesses",
    help_template = "{before-help}{about-with-newline}\n{usage-heading} {usage}\n\nOptions:\n{options}\n{after-help}"
)]
struct Cli {
    #[command(subcommand)]
    cmd: Cmd,
}

#[derive(Subcommand)]
enum Cmd {
    // ───────────────────────────── Read ─────────────────────────────
    /// List discovered sessions across all harnesses.
    Ls {
        /// Only this harness (claude, codex, grok, opencode, gemini, cursor, kimi, kimi-code,
        /// qwen, cline, roo, continue, lmstudio, hermes, goose, zed, openclaw, …).
        #[arg(long)]
        harness: Option<String>,
        /// Only sessions whose cwd contains this substring.
        #[arg(long)]
        cwd: Option<String>,
        /// Query calculus to filter rows, e.g. `model:fable`, `harness:codex msgs>=50`,
        /// `after:2026-06-01 widget` (implicit AND; see `cv schema`). A `model:` term forces a
        /// parse of each candidate (the catalog doesn't store the model), so pair it with cheap
        /// terms like `harness:`/`cwd:` to keep it fast.
        #[arg(long, short = 'q')]
        query: Option<String>,
        /// Max rows to show.
        #[arg(long, default_value_t = 40)]
        limit: usize,
        /// Sort key: updated (default), created, or messages.
        #[arg(long = "sort-by", default_value = "updated", value_parser = ["updated", "created", "messages"])]
        sort_by: String,
        /// Force a full fleet re-discovery instead of trusting the catalog's staleness probe.
        #[arg(long)]
        fresh: bool,
        /// Emit the rows as one JSON array of session rows (`id, harness, path, cwd, title,
        /// created_at, updated_at, message_count, size_bytes`) instead of the table — the same rows
        /// the table would show (all filters, sort, and --limit respected). Nothing else goes to
        /// stdout, so the output pipes cleanly.
        #[arg(long)]
        json: bool,
        /// (--json only) Enrich each row with transcript-derived `git` (branch/commit/remote, as
        /// `cv show --json` emits it) and `display_title` (the title with a first-real-user-text
        /// fallback). Costs one lazy transcript parse per emitted row — O(--limit), not the whole
        /// fleet — so plain `ls --json` stays catalog-cheap; opt in when you need these fields.
        #[arg(long)]
        enrich: bool,
    },
    /// Print a single session (by `harness:id` or a unique id prefix).
    Show {
        id: String,
        #[arg(long)]
        harness: Option<String>,
        /// Emit the raw unified IR as JSON instead of a rendered transcript.
        #[arg(long)]
        json: bool,
        #[command(flatten)]
        window: WindowArgs,
        /// Instead of the transcript, list the sub-agent forest this session spawned — each
        /// direct/`Workflow` sub-agent with its type, journaled outcome (workflow agents), and
        /// final return value. The second dimension of a Claude session.
        #[arg(long)]
        subagents: bool,
        /// Render one specific sub-agent's transcript by its `agent-…` id (or id-prefix), resolved
        /// relative to this parent session. Sub-agents aren't in the main pool, so they're read
        /// through their parent.
        #[arg(long)]
        agent: Option<String>,
        /// Read the pre-compaction span: the messages before a compaction boundary (the context a
        /// continued agent lost). Defaults to the FIRST boundary; pass `--pre-compaction <N>` for
        /// the Nth (1-based). It sets the window for you, so it excludes the window flags.
        #[arg(long, value_name = "N", num_args = 0..=1, default_missing_value = "1",
              conflicts_with_all = ["first", "last", "range", "around"])]
        pre_compaction: Option<usize>,
    },
    /// Print one tool call's full output, wherever it lives: inline in the transcript, in a
    /// `prune` sidecar, or in a persisted-output file. `--input` prints the call's arguments instead.
    Cat {
        /// The session (`harness:id` or a unique id prefix).
        session: String,
        /// The tool call's id (`toolu_…`, `call_…`, …) — as `cv show`/`cv tools --timeline` print it.
        tool_use_id: String,
        #[arg(long)]
        harness: Option<String>,
        /// Print the tool call's input (its arguments, as JSON) instead of its output.
        #[arg(long)]
        input: bool,
    },
    /// Full-text search across all session content.
    Search {
        query: String,
        #[arg(long)]
        harness: Option<String>,
        #[arg(long, default_value_t = 20)]
        limit: usize,
        /// Use semantic (embedding) search instead of full-text. Requires `cv index --semantic`
        /// to have been run; downloads a small embedding model on first use.
        #[arg(long)]
        semantic: bool,
        /// Emit the hits as one JSON array instead of the table — the same hits in the same
        /// order (--harness/--limit/--semantic respected): a session row (`id, harness, path, cwd,
        /// title, created_at, updated_at, message_count, size_bytes`) plus `score`, `snippet`, and
        /// the sub-agent provenance `agent_id`/`parent_id`/`workflow`. Nothing else goes to stdout.
        #[arg(long)]
        json: bool,
    },
    /// List what a session DID: its extracted events (file edits/reads, commands, errors).
    ///
    /// Events are ingested during `cv index`; a session that isn't cataloged yet (or whose file
    /// changed since) is ingested on the spot — one streamed pass, large content stays on disk.
    Events {
        id: String,
        #[arg(long)]
        harness: Option<String>,
        /// Only this kind: file_edit, file_read, command, tool, or error.
        #[arg(long)]
        kind: Option<String>,
        /// Also extract events from every sub-agent this session spawned (the forest), attributed
        /// to each agent — so a session's *full* activity (incl. what its Task/Workflow agents did)
        /// is visible, not just the orchestrator's own tool calls.
        #[arg(long)]
        subagents: bool,
        /// Emit the events as one JSON array (snake_case keys) instead of the table.
        #[arg(long)]
        json: bool,
    },
    /// Sessions that touched a file — every session with a file_edit/file_read event on its path.
    ///
    /// The path is matched absolutely and by suffix, so `cv touched src/ir.rs` finds sessions
    /// that edited `/any/repo/src/ir.rs`. Run `cv index` first to (re)ingest events.
    Touched {
        path: String,
        /// Only sessions that EDITED the file (drop read-only appearances).
        #[arg(long)]
        edits_only: bool,
        /// Emit the rows as one JSON array (snake_case keys) instead of the table.
        #[arg(long)]
        json: bool,
    },
    /// Cross-agent tool analytics: per-agent histograms, which-agent-used-what, aggregate usage,
    /// and a tool-call timeline — across the orchestrator and its whole sub-agent forest.
    Tools {
        id: String,
        #[arg(long)]
        harness: Option<String>,
        /// One agent's histogram ("which tools did agent X use"). `<orchestrator>` for the parent.
        #[arg(long)]
        agent: Option<String>,
        /// Which agents used this tool, across the forest (ranked by count).
        #[arg(long)]
        tool: Option<String>,
        /// Restrict the analytics to one workflow run's agents.
        #[arg(long)]
        workflow: Option<String>,
        /// Per-agent breakdown (one row per agent) instead of the aggregate histogram.
        #[arg(long)]
        across: bool,
        /// The time-ordered tool-call timeline (optionally narrowed with `--agent`).
        #[arg(long)]
        timeline: bool,
        #[arg(long)]
        json: bool,
    },
    /// Render a session's message threading (DAG if parent_ids exist, else a numbered list).
    Tree {
        id: String,
        #[arg(long)]
        harness: Option<String>,
    },
    /// A `Workflow`-tool run, first-class: its phase tree, the agents under each phase with their
    /// outcomes, run totals, and the driving script. Without `<run_id>`, lists the session's runs.
    Workflow {
        /// The session that launched the workflow — or a workflow NAME, resolved fleet-wide.
        id: String,
        /// The workflow run id (`wf_…`, or a unique prefix) or the workflow's name. Omit to list
        /// all runs.
        run_id: Option<String>,
        #[arg(long)]
        harness: Option<String>,
        /// Emit the structured workflow (phases → agents → outcomes) as JSON.
        #[arg(long)]
        json: bool,
        /// Also print the driving workflow script (the JS that fanned out the agents).
        #[arg(long)]
        script: bool,
        /// Print each agent's FULL journaled return value (the state file keeps only a ~400-char
        /// preview; the complete results live in the run's journal).
        #[arg(long)]
        results: bool,
        /// Follow a LIVE run: stream agent state transitions as they land in the state file, then
        /// render the full run when it reaches a terminal status.
        #[arg(long, short = 'f')]
        follow: bool,
        /// Salvage a dead or interrupted run: emit a ready-to-paste standalone `Agent` prompt per
        /// lane — the FULL original task plus the work that lane already landed (files written,
        /// commands run, its own last note) — so lanes come back resumed rather than restarted.
        #[arg(long)]
        revive: bool,
        /// With `--revive`, include lanes that completed successfully too (default: only the ones
        /// that did not finish).
        #[arg(long)]
        revive_all: bool,
    },
    /// Compaction boundaries in a session: every `/compact` (or auto-compaction), its trigger,
    /// pre-compaction context size, and the summary that seeded the next window. `--summaries`
    /// prints each full summary; `cv show <id> --pre-compaction` reads the lost pre-span.
    Compaction {
        id: String,
        #[arg(long)]
        harness: Option<String>,
        /// Print each compaction's full summary text (not just the head).
        #[arg(long)]
        summaries: bool,
        #[arg(long)]
        json: bool,
    },
    /// Only what the person said: every human-typed prompt and every `AskUserQuestion` answer, in
    /// order, with message indices and timestamps. The orchestrator's re-read of its brief.
    Prompts {
        id: String,
        #[arg(long)]
        harness: Option<String>,
        /// Emit the rows as one JSON array (`index, timestamp, kind: prompt|answer, text`).
        #[arg(long)]
        json: bool,
        /// Only the prompts in the span a compaction discarded — the Nth boundary's pre-span
        /// (1-based; bare flag = the first), exactly the window `cv show --pre-compaction` reads.
        #[arg(long, value_name = "N", num_args = 0..=1, default_missing_value = "1")]
        pre_compaction: Option<usize>,
    },
    /// The sub-agent forest as a status table: one row per lane with its model, start, duration,
    /// tokens, tool calls, status and last line — and the strand class (`--stranded`): lanes that
    /// stopped saying they are waiting for something that will never wake them.
    Lanes {
        id: String,
        #[arg(long)]
        harness: Option<String>,
        /// Only lanes still running (no stop recorded).
        #[arg(long, group = "lane_filter")]
        running: bool,
        /// Only lanes that completed (harness `completed`, or a journaled `done`).
        #[arg(long, group = "lane_filter")]
        done: bool,
        /// Only stranded lanes: stopped, with a final text that says it is waiting (`Waiting on
        /// notifications`, `I'll continue when the monitor fires`, …). Each row carries the
        /// resume hint.
        #[arg(long, group = "lane_filter")]
        stranded: bool,
        /// Only lanes active in this window: started or last turned within `2h`, `30m`, `1d`, …
        #[arg(long, value_name = "DUR")]
        since: Option<String>,
        /// Join each lane to the task store: the tasks its endpoint (`CV_ENDPOINT=lane:…` from its
        /// own tool calls, else its description's leading token) holds, with the last note.
        #[arg(long)]
        tasks: bool,
        /// Emit the lanes as one JSON array (snake_case; `cv schema` has the shape).
        #[arg(long)]
        json: bool,
    },
    /// A linter for promises: every place the assistant deferred something ("later lane",
    /// "follow-up", "not tonight", "queued", "ember's call", "when X lands", "after FINAL", …) with
    /// its message index and context. `--open-tasks` cross-references the task store and marks
    /// each MATCHED or UNMATCHED; any UNMATCHED exits 1, so a closeout can gate on it.
    Deferrals {
        id: String,
        #[arg(long)]
        harness: Option<String>,
        /// Only messages from this index on (e.g. the post-compaction region).
        #[arg(long, value_name = "MSG")]
        since: Option<usize>,
        /// Cross-reference every task in the store (terminal ones included): a deferral MATCHES a
        /// task when they share three or more significant words.
        #[arg(long)]
        open_tasks: bool,
        /// Emit the deferrals as one JSON array (`index, timestamp, phrase, context, matched?`).
        #[arg(long)]
        json: bool,
    },
    /// Unified chronological feed across all harnesses (oldest → newest).
    Timeline {
        #[arg(long)]
        harness: Option<String>,
        /// Only sessions whose cwd contains this substring.
        #[arg(long)]
        cwd: Option<String>,
        /// Restrict the feed to sessions matching this query (see `cv schema`).
        #[arg(long, short = 'q')]
        query: Option<String>,
        #[arg(long, default_value_t = 60)]
        limit: usize,
        /// Emit the feed as one JSON array of session rows (same shape as `ls --json`), oldest first.
        #[arg(long)]
        json: bool,
    },
    /// Fleet analytics over all discovered sessions.
    Stats {
        /// Restrict the analytics to sessions matching this query (see `cv schema`).
        #[arg(long, short = 'q')]
        query: Option<String>,
        /// Emit the analytics as one JSON object (snake_case keys) instead of the report.
        #[arg(long)]
        json: bool,
        /// Also total token usage per harness and model. Parses every matched transcript and its
        /// sub-agents (slower than the catalog-only default); `--json` adds a `tokens` object.
        #[arg(long)]
        tokens: bool,
    },
    /// Compare two sessions message-by-message (great for loom branches).
    Diff {
        a: String,
        b: String,
        #[arg(long)]
        harness: Option<String>,
    },
    /// Code provenance: which agent session wrote this code, and what was it thinking?
    ///
    /// Correlates the file's git history with the event catalog's file_edit events — an agent
    /// edit shortly before a commit is strong evidence that session authored it. A session whose
    /// own tool output shows the commit being made ranks above all of those as `exact: commit
    /// created here`, with a `cv rewind <id> --at <sha>` hint to resume that agent as of the commit.
    /// Each matched commit gets its best sessions plus a `cv show --range` hint into the
    /// conversation around the edit. Run `cv index` first to ingest events.
    Blame {
        file: String,
        /// Only these lines: `<line>` or `<line>,<endline>` (via `git blame -L`).
        #[arg(short = 'L', value_name = "LINE[,ENDLINE]")]
        lines: Option<String>,
        /// Also print the conversation window around the single best match (the commit itself
        /// for an exact match, else the matched edit).
        #[arg(long)]
        show: bool,
    },
    /// Diagnose why a session's context window keeps filling and compacting: attribute context
    /// pressure by source (tool results split MCP/builtin, thinking, messages), size the fixed
    /// system+tools overhead from token usage, and pair it with compaction frequency. With no
    /// <id>, analyzes the most recent session(s) for the current directory.
    Doctor {
        /// Session id (prefix ok). Omit to analyze recent sessions in the current project.
        id: Option<String>,
        #[arg(long)]
        harness: Option<String>,
        /// With no <id>: how many recent sessions (for this cwd) to aggregate.
        #[arg(long, default_value_t = 1)]
        recent: usize,
        #[arg(long)]
        json: bool,
    },

    // ───────────────────────────── Reshape ─────────────────────────────
    /// Custom, lossless compaction of a Claude session into a NEW resumable session: snip bulky old
    /// tool payloads (large reads/logs/screenshots) into a sidecar, leaving a small `[PRUNED]` marker
    /// — your prompts and flow stay verbatim, the recent turns stay sharp. Resume with
    /// `claude --resume <new-id>`; fetch a stashed original back with `cv cat <new-id> <tool_use_id>`.
    Prune {
        /// Source session id.
        id: String,
        #[arg(long)]
        harness: Option<String>,
        /// Snip a tool payload only if it's larger than this many bytes.
        #[arg(long, default_value_t = 2048)]
        min_size: usize,
        /// Keep the last N conversational turns' payloads verbatim (recent context stays sharp).
        #[arg(long, default_value_t = 25)]
        keep_last: usize,
        /// New session id (default: a fresh UUID).
        #[arg(long)]
        to: Option<String>,
        /// Hard-drop payloads (no sidecar, irreversible) instead of stashing them for retrieval.
        #[arg(long)]
        drop: bool,
        /// Also flatten the OLDEST assistant reasoning (thinking blocks) — recent thinking (within
        /// --keep-last) stays verbatim. On a long session the chain-of-thought dominates the loaded
        /// context; flattening the old reasoning is the biggest lever for shrinking it. Lossless.
        ///
        /// Renamed from `--thinking` in 0.11.0: that spelling now names the emit-side
        /// `--thinking <native|text|drop>`, and one word may not mean two things.
        #[arg(long = "drop-thinking")]
        drop_thinking: bool,
        // Renamed in 0.11.0 — hidden so the old spelling errors with a pointer (exit 2).
        #[arg(long, hide = true)]
        thinking: bool,
        /// Also copy the session's subagents/workflows dir under the new id (off by default; can be
        /// hundreds of MB for big sessions). Resume doesn't need it — only cv's forest features do.
        #[arg(long)]
        copy_resources: bool,
        /// Preserve the original `usage` records byte-for-byte (opt out of revive). By default,
        /// prune corrects the recorded context size so a maxed-out session will resume: Claude
        /// Code's resume gate reads the last turn's stored `usage` (input+cache) as the current
        /// size *before* it re-sends anything, so a session at the wall refuses to resume even
        /// after pruning shrinks it. Revive rewrites that stale number to the honest post-prune
        /// figure — a no-op when the recorded size is already honest. (Source untouched.)
        #[arg(long)]
        no_revive: bool,
        /// Sliding window: keep only the NEWEST turns totalling ≤ this many REAL tokens, dropping
        /// older turns (lossy — the source keeps the full history). Sized from Claude's OWN recorded
        /// `usage` counts (no byte/tokenizer estimation), so the budget lands true; the resumed
        /// session loads ≈ this budget + ~30k system overhead. Re-roots the kept tail into a
        /// standalone resumable session.
        #[arg(long, value_name = "TOKENS")]
        window: Option<u64>,
        /// Keep only this turn-index window, `A..B` (0-based, end-exclusive; `A..` through the
        /// last), dropping everything outside it. Like --window but by index.
        #[arg(long, value_name = "A..B")]
        keep: Option<String>,
        /// Snip message TEXT (user prompts + assistant replies) whose density of caller-supplied
        /// TERMS is high, into the sidecar with a `[PRUNED …]` marker. Motivation: a safeguard
        /// classifier scores the WHOLE loaded context, so term-dense PROSE in the history can silently
        /// downgrade a resumed seat's model tier — and tool/`--thinking` snipping leaves prose verbatim.
        /// Lossless (retrievable). A message is snipped iff it holds ≥2 distinct terms. cv ships NO
        /// built-in term list (that would trip the very classifier this dodges, and can't adapt);
        /// supply the terms with --declassify-tokens / --declassify-tokens-file, else this is a no-op.
        #[arg(long)]
        declassify: bool,
        /// Comma-separated terms for --declassify (lowercase; case-insensitive substring match).
        #[arg(long, value_name = "T1,T2,…")]
        declassify_tokens: Option<String>,
        /// File of --declassify terms, one per line (`#` comments + blank lines ignored). The external,
        /// version-controllable home for your term list — e.g. tuned from a classifier-trip corpus.
        #[arg(long, value_name = "PATH")]
        declassify_tokens_file: Option<PathBuf>,
        /// Report what would be pruned without writing anything.
        #[arg(long)]
        dry_run: bool,
        /// Also emit the prune report as ONE JSON object on stdout (snake_case keys, FULL ids).
        /// The human report stays on stderr, so stdout carries only the JSON. Dry-run honest:
        /// nothing was written, so `new_path`/`sidecar_path` are null and `new_id` is null unless
        /// `--to` pinned it (see `note`).
        #[arg(long)]
        json: bool,
        // Removed in 0.11.0 — kept hidden so the old spelling errors with a pointer (exit 2).
        #[arg(long, hide = true, value_name = "TOOL_USE_ID")]
        retrieve: Option<String>,
        #[arg(long, hide = true, value_name = "RANGE")]
        range: Option<String>,
    },
    /// Rewind a Claude session to a past moment: a NEW resumable session holding the source's
    /// records up to a message or the tool result that made a commit — the agent as it was when it
    /// landed that code, ready for `claude --resume <new-id> --fork-session`. Starts at the last
    /// compaction before the cut (the context the agent actually had); a sub-agent transcript comes
    /// out as a standalone top-level session. Writes `<new-id>.rewind.json` provenance alongside.
    Rewind {
        /// Source session: an id (prefix, `harness:id`), a sub-agent's `agent-<id>`, or a transcript path.
        id: String,
        #[arg(long)]
        harness: Option<String>,
        /// The cut, inclusive: a message index (as `cv show --range` counts) or a commit sha (7+ hex
        /// digits) — resolved to the `git commit`/`git push` tool result whose output names it, or an
        /// error if none does. An all-digit value is an index. Omit for the last message.
        #[arg(long, value_name = "MSG_IDX|SHA")]
        at: Option<String>,
        /// Rewind this sub-agent of <id> instead (its `agent-…` id, bare agentId, or a prefix), as
        /// `cv show --agent` resolves it.
        #[arg(long)]
        agent: Option<String>,
        /// Write under this directory instead of the source's project dir (where `claude --resume`
        /// looks; a sub-agent's is its parent's).
        #[arg(long)]
        out: Option<PathBuf>,
        /// New session id (default: a fresh UUID).
        #[arg(long)]
        to: Option<String>,
        /// Start at the last compaction boundary before the cut (the default): what a resume loads.
        #[arg(long, conflicts_with = "full")]
        from_compaction: bool,
        /// Start at the source's first record instead (the whole history up to the cut).
        #[arg(long)]
        full: bool,
        /// Report the window that would be written without writing anything.
        #[arg(long)]
        dry_run: bool,
        /// Also emit the result as ONE JSON object on stdout (snake_case, FULL ids, the `resume`
        /// lines); the human report stays on stderr. Dry-run honest like `prune --json`.
        #[arg(long)]
        json: bool,
    },
    /// Distill a long session (typically a sub-agent lane) into a compact context: the brief and
    /// every message to the agent verbatim, its own words (text, messages sent, notes written)
    /// verbatim, an index of commits/branches/hosts/paths/verdicts/errors, a one-line-per-call
    /// ledger, and its last N tool calls as real turns. Deterministic (no model calls). Elided
    /// outputs go to a sidecar `cv cat` reads. Prints the markdown pack by default; `--session`
    /// emits a resumable session (`claude -p --resume <id>`); `--agent-of <root>` emits a new
    /// sub-agent of that root, which the root resumes with SendMessage to the printed agent id.
    Distill {
        /// Session id, agent id (`agent-…`), `harness:id`, or a path to a transcript file.
        id: String,
        #[arg(long)]
        harness: Option<String>,
        /// Keep the last N tool calls (and the turns around them) verbatim.
        #[arg(long, default_value_t = 12)]
        keep_last: usize,
        /// Byte cap for one tool result inside the verbatim tail (head+tail kept, rest elided).
        #[arg(long, default_value_t = 6000)]
        tail_result_max: usize,
        /// Byte cap for one note the agent wrote, a sub-agent return, or a spawned prompt.
        #[arg(long, default_value_t = 6000)]
        note_max: usize,
        /// Keep the agent's thinking blocks inside the verbatim tail (dropped by default).
        #[arg(long)]
        keep_tail_thinking: bool,
        /// Omit the one-line-per-tool-call ledger.
        #[arg(long)]
        no_ledger: bool,
        /// Distill the session as it stood at message N (exclusive): a distilled fork.
        #[arg(long, value_name = "N")]
        upto: Option<usize>,
        /// Inject another session's findings (its own words and facts) into this pack. Repeatable.
        #[arg(long = "with", value_name = "SESSION")]
        with: Vec<String>,
        /// Write the markdown pack to this file (instead of stdout).
        #[arg(long, value_name = "FILE")]
        pack: Option<PathBuf>,
        /// Emit a resumable main-thread session (new id) under the Claude store or --out.
        #[arg(long, conflicts_with = "agent_of")]
        session: bool,
        /// Emit a new sub-agent transcript owned by this ROOT session (id or transcript path).
        #[arg(long, value_name = "ROOT")]
        agent_of: Option<String>,
        /// With --session: rehome the new session to this working directory.
        #[arg(long)]
        cwd: Option<PathBuf>,
        /// With --session: write under this directory instead of the Claude store.
        #[arg(long)]
        out: Option<PathBuf>,
        /// Report as JSON on stdout (stats + what was written).
        #[arg(long)]
        json: bool,
    },
    /// Fork a session's context at message N: emit the verbatim prefix as a new resumable session
    /// (`--session`) or as a new sub-agent of a root (`--agent-of`), to branch a lane and run
    /// variants from one point. Calls whose results fall after the cut are dropped.
    Fork {
        /// Session id, agent id, `harness:id`, or a transcript path.
        id: String,
        #[arg(long)]
        harness: Option<String>,
        /// Keep messages [0, N).
        #[arg(long, value_name = "N")]
        at: usize,
        #[arg(long, conflicts_with = "agent_of")]
        session: bool,
        #[arg(long, value_name = "ROOT")]
        agent_of: Option<String>,
        #[arg(long)]
        cwd: Option<PathBuf>,
        #[arg(long)]
        out: Option<PathBuf>,
        #[arg(long)]
        json: bool,
    },
    /// Rescue sub-agents stranded by a dead Claude Code session into a live one, so the live
    /// session can `SendMessage` them and they resume with their whole transcript: copies
    /// `subagents/agent-<id>.jsonl` (with `sessionId` restamped on every line, nothing else
    /// changed) and its `.meta.json` into the live session's `subagents/`. `--list <session>`
    /// lists a session's agents; `--orphans` lists unfinished agents of recent dead sessions.
    Adopt {
        /// Agent ids (`a5d8…` or `agent-a5d8…`, unique prefix ok).
        #[arg(required_unless_present_any = ["list", "orphans"], conflicts_with_all = ["list", "orphans"])]
        agents: Vec<String>,
        /// The live session that adopts them (default: the newest session in the agent's
        /// project other than the one holding it, printed before acting). With --orphans: the
        /// live session to exclude.
        #[arg(long, value_name = "SESSION")]
        into: Option<String>,
        /// The dead session that holds them (default: search every session's `subagents/`;
        /// when several hold a copy, the newest copy is taken).
        #[arg(long, value_name = "SESSION")]
        from: Option<String>,
        /// Print what would be copied; write nothing.
        #[arg(long)]
        dry_run: bool,
        /// Replace an agent file already present in the live session.
        #[arg(long)]
        force: bool,
        /// List a session's sub-agents: status, model, size, description, whether a meta exists.
        #[arg(long, value_name = "SESSION", conflicts_with_all = ["orphans", "from", "dry_run", "force"])]
        list: Option<String>,
        /// List unfinished sub-agents (running / stopped / killed / failed / stranded) of the
        /// project's recent sessions other than the live one (the cwd's project, or --into's).
        #[arg(long, conflicts_with_all = ["from", "dry_run", "force"])]
        orphans: bool,
        /// With --orphans: how many recent sessions to scan.
        #[arg(long, default_value_t = 10, requires = "orphans")]
        recent: usize,
        #[arg(long)]
        json: bool,
    },
    /// Compose a new session from spans of existing ones (`<id>:A..B`).
    Splice {
        /// One or more specs: `<id>:A..B`, `<id>:A..` (through the last), `<id>:..B`, or `<id>`
        /// (the whole session). Indices are 0-based, end-exclusive; `<id>` may be `harness:id`.
        #[arg(required = true)]
        specs: Vec<String>,
        /// Target harness for the composed session (defaults to the first spec's harness).
        #[arg(long)]
        harness: Option<String>,
        /// Write under this directory instead of the target's real storage root.
        #[arg(long)]
        out: Option<PathBuf>,
        /// What to do with the model's reasoning on the way out: `native` keeps it where the target
        /// format holds it and drops it elsewhere, `text` keeps the turn by demoting thinking to
        /// text (a placeholder for provider-signed blobs, which have no text), `drop` omits it.
        #[arg(long, default_value = "native", value_parser = ["native", "text", "drop"])]
        thinking: String,
        /// Print the composed session instead of emitting it: md or json.
        #[arg(long)]
        export: Option<String>,
        /// Rehome the composed session to this working directory.
        #[arg(long)]
        cwd: Option<PathBuf>,
        /// Generate a continuation of the composed session via an LLM and append it (the loom's
        /// generative step). Uses OPENROUTER/ANTHROPIC keys or LMSTUDIO_API_BASE for free local gen.
        #[arg(long)]
        generate: bool,
        /// Model for --generate (provider-specific; defaults to the provider's default).
        #[arg(long = "gen-model")]
        gen_model: Option<String>,
        #[arg(long, hide = true)]
        to: Option<String>,
    },
    /// Loom graft: take base[..N], then graft other[M..] into one new branched session.
    Loom {
        base: String,
        /// Keep `base[..N]`.
        #[arg(long, value_name = "N")]
        at: usize,
        /// The session to graft from.
        #[arg(long)]
        graft: String,
        /// Start grafting at `graft[M..]`.
        #[arg(long, value_name = "M")]
        from: usize,
        /// Target harness for the grafted session (defaults to the base's harness).
        #[arg(long)]
        harness: Option<String>,
        #[arg(long)]
        out: Option<PathBuf>,
        /// What to do with the model's reasoning on the way out: `native` keeps it where the target
        /// format holds it and drops it elsewhere, `text` keeps the turn by demoting thinking to
        /// text (a placeholder for provider-signed blobs, which have no text), `drop` omits it.
        #[arg(long, default_value = "native", value_parser = ["native", "text", "drop"])]
        thinking: String,
        /// Print the grafted session instead of emitting it: md or json.
        #[arg(long)]
        export: Option<String>,
        /// Rehome the grafted session to this working directory.
        #[arg(long)]
        cwd: Option<PathBuf>,
        /// Generate a continuation of the grafted branch via an LLM and append it.
        #[arg(long)]
        generate: bool,
        /// Model for --generate.
        #[arg(long = "gen-model")]
        gen_model: Option<String>,
        #[arg(long, hide = true)]
        to: Option<String>,
    },
    /// Produce a copy of a session that runs elsewhere: in another harness (`--harness`), from
    /// another working directory (`--cwd`, carrying CLAUDE.md/AGENTS.md/… along), or both. The
    /// source is never touched; the source harness rides on the id (`codex:019e…`).
    Port {
        id: String,
        /// Target harness (claude, codex, grok, …). Defaults to the source harness (a pure rehome).
        #[arg(long)]
        harness: Option<String>,
        /// New working directory for the ported session.
        #[arg(long)]
        cwd: Option<PathBuf>,
        /// Write under this directory instead of the target's real storage root (safe dry run).
        #[arg(long)]
        out: Option<PathBuf>,
        /// Don't copy project context files (CLAUDE.md, MEMORY.md, AGENTS.md, …) to the new cwd.
        #[arg(long = "no-context")]
        no_context: bool,
        /// Fail if the fidelity check finds a loss the target format could have carried. Losses the
        /// format inherently cannot hold are still only reported under `⚠ lost`.
        #[arg(long)]
        strict: bool,
        /// What to do with the model's reasoning on the way out: `native` keeps it where the target
        /// format holds it and drops it elsewhere, `text` keeps the turn by demoting thinking to
        /// text (a placeholder for provider-signed blobs, which have no text), `drop` omits it.
        #[arg(long, default_value = "native", value_parser = ["native", "text", "drop"])]
        thinking: String,
        // Renamed in 0.11.0 — hidden so the old spellings error with a pointer (exit 2).
        #[arg(long, hide = true)]
        to: Option<String>,
        #[arg(long = "to-dir", hide = true)]
        to_dir: Option<PathBuf>,
        #[arg(long, hide = true)]
        from: Option<String>,
    },
    /// Scrub secrets/PII from a session and export it (safe to share).
    Redact {
        id: String,
        #[arg(long)]
        harness: Option<String>,
        #[arg(long, default_value = "md")]
        format: String,
        /// Also print redaction counts per class to stderr.
        #[arg(long)]
        stats: bool,
    },
    /// Print (or with --launch, run) the resume incantation for a session in its native harness.
    Resume {
        id: String,
        #[arg(long)]
        harness: Option<String>,
        /// Actually spawn the harness (cd to the session's cwd) instead of just printing.
        #[arg(long)]
        launch: bool,
    },

    // ───────────────────────────── Export ─────────────────────────────
    /// Export a session to markdown, JSON, or self-contained HTML (stdout).
    Export {
        id: String,
        /// Output format: `md` (default), `json`, or `html`.
        #[arg(long, default_value = "md")]
        format: String,
        #[arg(long)]
        harness: Option<String>,
        #[command(flatten)]
        window: WindowArgs,
    },
    /// Export the corpus as a fine-tuning dataset (JSONL, one session per line).
    /// `chatml`/`sharegpt` import directly into Unsloth Studio / TRL / HF — no adapter.
    Dataset {
        /// `chatml` (default) → {"messages":[…]}, or `sharegpt` → {"conversations":[…]}.
        #[arg(long, default_value = "chatml")]
        format: String,
        /// Only this harness (claude, codex, hermes, …); omit for all.
        #[arg(long)]
        harness: Option<String>,
        /// Query calculus selecting which sessions to include, e.g. `model:fable`,
        /// `harness:claude msgs>=20`, `after:2026-01-01 cwd:/pug` (implicit AND; see `cv schema`).
        #[arg(long, short = 'q')]
        query: Option<String>,
        /// Also emit each Claude session's sub-agent forest (directly- and `Workflow`-spawned
        /// transcripts in sidecar files). These are first-class training data — and a parent on one
        /// model often spawns sub-agents on another, so `model:` queries need this to catch them.
        #[arg(long)]
        subagents: bool,
        /// Stop after N emitted records.
        #[arg(long)]
        limit: Option<usize>,
        /// Skip sessions with fewer than this many messages (drops trivial/empty ones).
        #[arg(long, default_value_t = 2)]
        min_messages: usize,
        /// Scrub secrets/PII from every session before emitting (cv_core::redact).
        #[arg(long)]
        redact: bool,
        /// Scrub only these secret classes (comma list: `private_key`, `api_key`, `jwt`, `email`,
        /// `blob`, `assignment`), leaving everything else intact — e.g. `--redact-only private_key`
        /// to strip PEM blocks but keep identities. Implies redaction; overrides `--redact`.
        #[arg(long, value_name = "CLASSES")]
        redact_only: Option<String>,
        /// Write to this file instead of stdout.
        #[arg(long)]
        out: Option<PathBuf>,
    },
    /// Compile a context bundle for a new task from your whole session corpus.
    Pack {
        /// What you're about to work on — recall finds the relevant past spans.
        task: String,
        /// Output shape: `md` (CLAUDE.md-style digest, default), `prompt` (system prompt),
        /// or `session` (a synthetic resumable session — see `--harness`).
        #[arg(long, default_value = "md")]
        format: String,
        /// Target harness when `--format session`.
        #[arg(long)]
        harness: Option<String>,
        /// Max past sessions to draw from.
        #[arg(long, default_value_t = 8)]
        limit: usize,
        #[arg(long)]
        out: Option<PathBuf>,
        /// What to do with the model's reasoning on the way out: `native` keeps it where the target
        /// format holds it and drops it elsewhere, `text` keeps the turn by demoting thinking to
        /// text (a placeholder for provider-signed blobs, which have no text), `drop` omits it.
        #[arg(long, default_value = "native", value_parser = ["native", "text", "drop"])]
        thinking: String,
        #[arg(long, hide = true)]
        to: Option<String>,
    },

    // ───────────────────────────── Fleet & live ─────────────────────────────
    /// Fleet task substrate: dispatch, review, and git-observed landing.
    Task {
        #[command(subcommand)]
        action: TaskCmd,
    },
    /// Post to / read from the agent coordination board.
    Board {
        #[command(subcommand)]
        action: BoardCmd,
    },
    /// Follow live agent activity across harnesses (tail -f for sessions).
    Scry {
        #[arg(long)]
        harness: Option<String>,
        /// Only follow sessions whose cwd contains this substring.
        #[arg(long)]
        cwd: Option<String>,
        /// Poll interval in seconds.
        #[arg(long, default_value_t = 2.0)]
        interval: f64,
        /// Also emit the sessions that already exist at startup (default: only new activity).
        #[arg(long)]
        existing: bool,
    },
    /// Redact a session and emit a single self-contained HTML artifact anyone can open.
    Share {
        id: String,
        #[arg(long)]
        harness: Option<String>,
        /// Write here instead of `./<id>.html`.
        #[arg(long)]
        out: Option<PathBuf>,
        /// Skip the redaction pass (default is to scrub secrets/PII before sharing).
        #[arg(long)]
        no_redact: bool,
    },

    // ───────────────────────────── System ─────────────────────────────
    /// Build/refresh the tantivy full-text index that makes `cv search` instant.
    ///
    /// Incremental by default: only changed/new sessions are re-indexed and vanished ones reaped,
    /// so routine refreshes are fast and light. Use `--rebuild` to clear and rebuild from scratch.
    /// Tool-call events (file edits/reads, commands, errors) ride along on the same pass into the
    /// catalog, powering `cv events` and `cv touched`.
    Index {
        /// Also build semantic embeddings (`cv search --semantic`). Downloads a small embedding
        /// model (~30MB) on first use.
        #[arg(long)]
        semantic: bool,
        /// Clear and rebuild the index from scratch instead of incrementally updating it.
        #[arg(long)]
        rebuild: bool,
        /// Also fold every session's sub-agent forest (its Task/Workflow agent transcripts) into
        /// BOTH the full-text index and the event catalog, tagged with provenance (which agent of
        /// which workflow of which parent). Off by default: it can add ~900MB to the index and many
        /// hundreds of transcripts to ingest. Without it, only top-level sessions are indexed.
        #[arg(long)]
        subagents: bool,
    },
    /// View the user config (`~/.config/clustervision/config.toml`) and manage the export-source index.
    /// With no flag, prints the config path + registered export sources. Account data exports
    /// (ChatGPT/Claude.ai `conversations.json`) have no fixed home, so register the dirs/files you want
    /// the `chatgpt-export`/`claude-export` harnesses to discover.
    Config {
        /// Register an export source (a dir to scan, or a `conversations.json` file).
        #[arg(long, value_name = "PATH")]
        add_export: Option<PathBuf>,
        /// Unregister a previously-added export source.
        #[arg(long, value_name = "PATH")]
        rm_export: Option<PathBuf>,
    },
    /// The reference: the `-q` query calculus (every field, operator, example) and, with `--json`,
    /// the machine-readable schema of every shape cv emits (session row, message, block, query).
    /// `--commands --json` dumps the whole command tree for tool generation.
    Schema {
        /// Emit the machine-readable schema as JSON instead of the human reference.
        #[arg(long)]
        json: bool,
        /// The command tree instead of the data schema: every visible command and subcommand with
        /// its group, about text, and args (name, kind, value_type, possible_values, default, help,
        /// required). Human list without `--json`, one JSON array with it.
        #[arg(long)]
        commands: bool,
    },
    /// Audit cv against the harnesses themselves: what recent sessions actually contain
    /// (`census`), and whether each adapter still matches its pinned manifest (`check`).
    Formats {
        #[command(subcommand)]
        action: cmd::formats::FormatsCmd,
    },
    /// The agent quickstart: the ten things agents do with cv, each as one command line with the
    /// JSON keys it returns.
    Recipes,

    // ───────────────────────────── Removed in 0.11.0 (hidden stubs) ─────────────────────────────
    #[command(hide = true)]
    Convert {
        #[arg(trailing_var_arg = true, allow_hyphen_values = true, num_args = 0..)]
        rest: Vec<String>,
    },
    #[command(hide = true)]
    Query {
        #[arg(trailing_var_arg = true, allow_hyphen_values = true, num_args = 0..)]
        rest: Vec<String>,
    },
    #[command(hide = true)]
    Recall {
        #[arg(trailing_var_arg = true, allow_hyphen_values = true, num_args = 0..)]
        rest: Vec<String>,
    },
}

/// The clap tree with the grouped listing attached (`after_help` is computed from the tree itself,
/// so it can't drift from the commands).
fn build_cli() -> clap::Command {
    let cmd = Cli::command();
    let listing = grouped_help(&cmd);
    cmd.after_help(listing)
}

fn main() {
    // Die quietly on a closed pipe (`cv task list | head`) instead of panicking:
    // Rust ignores SIGPIPE by default, which turns EPIPE into a write panic.
    #[cfg(unix)]
    unsafe {
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
    }
    if let Err(e) = run() {
        // Caller mistakes (unknown/ambiguous id, removed command/flag, bad window) exit 2 with the
        // bare message; everything else is a real failure: the anyhow chain, exit 1.
        if let Some(u) = e.downcast_ref::<UsageError>() {
            eprintln!("{u}");
            std::process::exit(2);
        }
        eprintln!("Error: {e:?}");
        std::process::exit(1);
    }
}

fn run() -> Result<()> {
    let matches = build_cli().get_matches();
    let cli = match Cli::from_arg_matches(&matches) {
        Ok(cli) => cli,
        Err(e) => e.exit(),
    };
    match cli.cmd {
        Cmd::Ls {
            harness,
            cwd,
            query,
            limit,
            sort_by,
            fresh,
            json,
            enrich,
        } => browse::cmd_ls(harness, cwd, query, limit, &sort_by, fresh, json, enrich),
        Cmd::Search {
            query,
            harness,
            limit,
            semantic,
            json,
        } => search::cmd_search(&query, harness, limit, semantic, json),
        Cmd::Show {
            id,
            harness,
            json,
            window,
            subagents,
            agent,
            pre_compaction,
        } => view::cmd_show(&id, harness, json, &window, subagents, agent, pre_compaction),
        Cmd::Cat {
            session,
            tool_use_id,
            harness,
            input,
        } => cat::cmd_cat(&session, &tool_use_id, harness, input),
        Cmd::Export {
            id,
            format,
            harness,
            window,
        } => view::cmd_export(&id, &format, harness, &window),
        Cmd::Dataset {
            format,
            harness,
            query,
            subagents,
            limit,
            min_messages,
            redact,
            redact_only,
            out,
        } => compose::cmd_dataset(
            &format,
            harness,
            query,
            subagents,
            limit,
            min_messages,
            redact,
            redact_only,
            out,
        ),
        Cmd::Port {
            id,
            harness,
            cwd,
            out,
            no_context,
            strict,
            thinking,
            to,
            to_dir,
            from,
        } => {
            if to.is_some() {
                return usage("`cv port --to <harness>` was renamed in 0.11.0 — use `--harness <harness>`");
            }
            if to_dir.is_some() {
                return usage("`cv port --to-dir <dir>` was renamed in 0.11.0 — use `--cwd <dir>`");
            }
            if from.is_some() {
                return usage(
                    "`cv port --from <harness>` was removed in 0.11.0 — the source harness rides on the id: \
                     `cv port <harness>:<id>`",
                );
            }
            port::cmd_port(&id, harness, cwd, out, no_context, strict, util::parse_thinking(&thinking)?)
        }
        Cmd::Scry {
            harness,
            cwd,
            interval,
            existing,
        } => live::cmd_scry(harness, cwd, interval, existing),
        Cmd::Index {
            semantic,
            rebuild,
            subagents,
        } => search::cmd_index(semantic, rebuild, subagents),
        Cmd::Events {
            id,
            harness,
            kind,
            subagents,
            json,
        } => provenance::cmd_events(&id, harness, kind, subagents, json),
        Cmd::Touched {
            path,
            edits_only,
            json,
        } => provenance::cmd_touched(&path, edits_only, json),
        Cmd::Blame { file, lines, show } => blame::cmd_blame(&file, lines.as_deref(), show),
        Cmd::Share {
            id,
            harness,
            out,
            no_redact,
        } => share::cmd_share(&id, harness, out, no_redact),
        Cmd::Pack {
            task,
            format,
            harness,
            limit,
            out,
            thinking,
            to,
        } => {
            if to.is_some() {
                return usage("`cv pack --to <harness>` was renamed in 0.11.0 — use `--harness <harness>`");
            }
            pack::cmd_pack(&task, &format, harness, limit, out, util::parse_thinking(&thinking)?)
        }
        Cmd::Stats { query, json, tokens } => browse::cmd_stats(query, json, tokens),
        Cmd::Prune {
            id,
            harness,
            min_size,
            keep_last,
            to,
            drop,
            drop_thinking,
            thinking,
            copy_resources,
            no_revive,
            window,
            keep,
            declassify,
            declassify_tokens,
            declassify_tokens_file,
            dry_run,
            json,
            retrieve,
            range,
        } => {
            if retrieve.is_some() {
                return usage(
                    "`cv prune --retrieve <tool_use_id>` was removed in 0.11.0 — use `cv cat <session> <tool_use_id>`",
                );
            }
            if range.is_some() {
                return usage(
                    "`cv prune --range A-B` was renamed in 0.11.0 — use `--keep A..B` (the turn indices to KEEP; \
                     0-based, end-exclusive, `A..` through the last)",
                );
            }
            let keep_range = keep.as_deref().map(util::parse_range).transpose()?;
            let tokens = resolve_declassify_tokens(declassify_tokens, declassify_tokens_file)?;
            if declassify && tokens.is_empty() {
                eprintln!(
                    "cv prune --declassify: no terms supplied (--declassify-tokens / \
                     --declassify-tokens-file) — nothing will be snipped. cv ships no built-in list."
                );
            }
            if thinking {
                return usage(
                    "`cv prune --thinking` was renamed in 0.11.0 — use `--drop-thinking` (plain \
                     `--thinking <native|text|drop>` now means what an EMIT does with reasoning)",
                );
            }
            compose::cmd_prune(
                &id,
                harness,
                min_size,
                keep_last,
                to,
                drop,
                drop_thinking,
                copy_resources,
                !no_revive,
                window,
                keep_range,
                declassify,
                tokens,
                dry_run,
                json,
            )
        }
        Cmd::Rewind {
            id,
            harness,
            at,
            agent,
            out,
            to,
            from_compaction: _,
            full,
            dry_run,
            json,
        } => compose::cmd_rewind(&id, harness, agent, at.as_deref(), out, to, full, dry_run, json, BUILD_VERSION),
        Cmd::Config { add_export, rm_export } => config::cmd_config(add_export, rm_export),
        Cmd::Schema { json, commands } => schema::cmd_schema(&build_cli(), json, commands),
        Cmd::Formats { action } => formats::cmd_formats(action),
        Cmd::Recipes => recipes::cmd_recipes(),
        Cmd::Resume { id, harness, launch } => port::cmd_resume(&id, harness, launch),
        Cmd::Tree { id, harness } => view::cmd_tree(&id, harness),
        Cmd::Workflow {
            id,
            run_id,
            harness,
            json,
            script,
            results,
            follow,
            revive,
            revive_all,
        } => workflow::cmd_workflow(&id, run_id, harness, json, script, results, follow, revive, revive_all),
        Cmd::Tools {
            id,
            harness,
            agent,
            tool,
            workflow: wf,
            across,
            timeline,
            json,
        } => workflow::cmd_tools(&id, harness, agent, tool, wf, across, timeline, json),
        Cmd::Compaction {
            id,
            harness,
            summaries,
            json,
        } => workflow::cmd_compaction(&id, harness, summaries, json),
        Cmd::Prompts {
            id,
            harness,
            json,
            pre_compaction,
        } => orchestrate::cmd_prompts(&id, harness, json, pre_compaction),
        Cmd::Lanes {
            id,
            harness,
            running,
            done,
            stranded,
            since,
            tasks,
            json,
        } => {
            let filter = if running {
                orchestrate::LaneFilter::Running
            } else if done {
                orchestrate::LaneFilter::Done
            } else if stranded {
                orchestrate::LaneFilter::Stranded
            } else {
                orchestrate::LaneFilter::All
            };
            orchestrate::cmd_lanes(&id, harness, filter, since, tasks, json)
        }
        Cmd::Deferrals {
            id,
            harness,
            since,
            open_tasks,
            json,
        } => {
            // An unmatched deferral is a finding, not a failure: plain exit 1, no error text.
            if !orchestrate::cmd_deferrals(&id, harness, since, open_tasks, json)? {
                std::process::exit(1);
            }
            Ok(())
        }
        Cmd::Doctor {
            id,
            harness,
            recent,
            json,
        } => doctor::cmd_doctor(id, harness, recent, json),
        Cmd::Board { action } => live::cmd_board(action),
        Cmd::Task { action } => task::cmd_task(action),
        Cmd::Timeline {
            harness,
            cwd,
            query,
            limit,
            json,
        } => browse::cmd_timeline(harness, cwd, query, limit, json),
        Cmd::Diff { a, b, harness } => view::cmd_diff(&a, &b, harness),
        Cmd::Distill {
            id,
            harness,
            keep_last,
            tail_result_max,
            note_max,
            keep_tail_thinking,
            no_ledger,
            upto,
            with,
            pack,
            session,
            agent_of,
            cwd,
            out,
            json,
        } => {
            let opts = cv_core::distill::DistillOptions {
                keep_last,
                tail_result_max,
                note_max,
                keep_tail_thinking,
                ledger: !no_ledger,
                retrieve_ref: None,
            };
            let target = cmd::distill::target(session, agent_of, cwd, out)?;
            cmd::distill::cmd_distill(&id, harness, opts, upto, &with, pack, target, json)
        }
        Cmd::Fork {
            id,
            harness,
            at,
            session,
            agent_of,
            cwd,
            out,
            json,
        } => {
            let target = cmd::distill::target(session, agent_of, cwd, out)?;
            cmd::distill::cmd_fork(&id, harness, at, target, json)
        }
        Cmd::Adopt {
            agents,
            into,
            from,
            dry_run,
            force,
            list,
            orphans,
            recent,
            json,
        } => cmd::adopt::cmd_adopt(cmd::adopt::AdoptArgs {
            agents,
            into,
            from,
            dry_run,
            force,
            list,
            orphans,
            recent,
            json,
        }),
        Cmd::Splice {
            specs,
            harness,
            out,
            export,
            cwd,
            generate,
            gen_model,
            thinking,
            to,
        } => {
            if to.is_some() {
                return usage("`cv splice --to <harness>` was renamed in 0.11.0 — use `--harness <harness>`");
            }
            compose::cmd_splice(&specs, harness, out, export, cwd, generate, gen_model, util::parse_thinking(&thinking)?)
        }
        Cmd::Redact {
            id,
            harness,
            format,
            stats,
        } => view::cmd_redact(&id, harness, &format, stats),
        Cmd::Loom {
            base,
            at,
            graft,
            from,
            harness,
            out,
            export,
            cwd,
            generate,
            gen_model,
            thinking,
            to,
        } => {
            if to.is_some() {
                return usage("`cv loom --to <harness>` was renamed in 0.11.0 — use `--harness <harness>`");
            }
            compose::cmd_loom(
                &base, at, &graft, from, harness, out, export, cwd, generate, gen_model,
                util::parse_thinking(&thinking)?,
            )
        }
        // Removed commands: one line each, pointing at the replacement; exit 2.
        Cmd::Convert { .. } => usage(
            "`cv convert` was removed in 0.11.0 — use `cv port <id> --harness <harness>` \
             (`--cwd <dir>` to rehome, `--out <dir>` for a dry run)",
        ),
        Cmd::Query { .. } => usage("`cv query` was renamed in 0.11.0 — use `cv schema` (`cv schema --json` for the machine schema)"),
        Cmd::Recall { .. } => usage(
            "`cv recall` was removed in 0.11.0 — use `cv search <query>` to find content, or `cv pack <task>` to build context",
        ),
    }
}

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

    #[test]
    fn declassify_tokens_resolve_from_csv_and_file() {
        // CSV alone: trimmed, lowercased, de-duplicated, order-preserving.
        let got = resolve_declassify_tokens(Some("Exploit, credential ,exploit,".into()), None).unwrap();
        assert_eq!(got, vec!["exploit", "credential"]);

        // File alone: one term per line, `#` comments (inline too) and blanks ignored.
        let dir = std::env::temp_dir().join(format!("cv-declass-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("terms.txt");
        std::fs::write(&path, "# a comment\nExfil\n\nauth bypass  # trailing note\n exfil \n").unwrap();
        let got = resolve_declassify_tokens(None, Some(path.clone())).unwrap();
        assert_eq!(got, vec!["exfil", "auth bypass"]);

        // CSV + file compose; duplicates across sources collapse; neither source is required.
        let got = resolve_declassify_tokens(Some("exfil,Attacker".into()), Some(path)).unwrap();
        assert_eq!(got, vec!["exfil", "attacker", "auth bypass"]);
        assert!(resolve_declassify_tokens(None, None).unwrap().is_empty());

        // A missing file is a real error naming the path, not a silent empty list.
        let err = resolve_declassify_tokens(None, Some(dir.join("nope.txt"))).unwrap_err();
        assert!(err.to_string().contains("declassify-tokens-file"), "{err}");
        std::fs::remove_dir_all(&dir).ok();
    }

    /// The clap tree is well-formed (debug asserts: conflicting ids, bad defaults, …).
    /// Building the clap tree is deep: `Cli::command()` for ~40 commands with their args is a
    /// large stack frame in a debug build, and the default 2 MB test-thread stack overflows on
    /// it (the binary's main thread has 8 MB and is fine). Run the tree-building tests on a
    /// thread sized like main.
    fn on_main_sized_stack(f: impl FnOnce() + Send + 'static) {
        std::thread::Builder::new()
            .stack_size(16 * 1024 * 1024)
            .spawn(f)
            .expect("spawn")
            .join()
            .expect("test thread panicked");
    }

    #[test]
    fn clap_tree_is_valid() {
        on_main_sized_stack(|| build_cli().debug_assert());
    }

    /// Every visible command sits in exactly one group, and every grouped name is a real
    /// command — the table and the enum cannot drift apart.
    #[test]
    fn groups_cover_every_visible_command() {
        on_main_sized_stack(groups_cover_every_visible_command_body);
    }

    fn groups_cover_every_visible_command_body() {
        let cmd = Cli::command();
        let visible: Vec<&str> = cmd
            .get_subcommands()
            .filter(|s| !s.is_hide_set())
            .map(|s| s.get_name())
            .collect();
        for name in &visible {
            let n = GROUPS.iter().filter(|(_, cmds)| cmds.contains(name)).count();
            assert_eq!(
                n, 1,
                "visible command {name:?} must be in exactly one group (found {n})"
            );
        }
        for (group, names) in GROUPS {
            for name in names.iter() {
                assert!(
                    visible.contains(name),
                    "group {group:?} lists {name:?}, which is not a visible command"
                );
            }
        }
        // Old names are hidden stubs, never visible commands.
        for old in ["convert", "query", "recall"] {
            assert!(!visible.contains(&old), "{old} must be hidden");
            assert!(
                cmd.get_subcommands().any(|s| s.get_name() == old),
                "{old} stub must exist"
            );
        }
    }

    /// `cv --help` lists the groups and ends with the recipes pointer.
    #[test]
    fn help_is_grouped_and_ends_with_recipes() {
        on_main_sized_stack(help_is_grouped_and_ends_with_recipes_body);
    }

    fn help_is_grouped_and_ends_with_recipes_body() {
        let help = build_cli().render_long_help().to_string();
        for (group, _) in GROUPS {
            assert!(
                help.contains(&format!("  {group}\n")),
                "group {group:?} missing:\n{help}"
            );
        }
        assert!(help.trim_end().ends_with(RECIPES_FOOTER), "footer:\n{help}");
        assert!(
            !help.contains("    convert ") && !help.contains("    recall "),
            "stubs leak:\n{help}"
        );
        // The flat clap list is gone — commands appear under their group only.
        assert_eq!(help.matches("\n    ls ").count(), 1, "{help}");
    }
}