1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
//! `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`.
//!
//! 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. A name removed in the current release is
//! a hidden stub that errors with a pointer and exits 2 — never an alias that works — and the
//! stub itself goes at the next release (the 0.11 tombstones left at 0.15).
#[cfg(all(test, feature = "probe-heap"))]
#[global_allocator]
static ALLOCATOR: cv_testkit::heap::Allocator = cv_testkit::heap::Allocator;
mod cmd;
mod http;
mod util;
/// A hermetic world whose environment this thread's library calls read (see `cv_core::env`).
#[cfg(test)]
fn test_world(tag: &str) -> cv_testkit::InProcess<cv_core::env::Isolated> {
cv_testkit::World::in_process(tag, cv_core::env::Env::enter_isolated)
}
use anyhow::{Context, Result};
use clap::{CommandFactory, FromArgMatches, Parser, Subcommand};
use cmd::hooks::{HookName, HooksCmd};
use cmd::task::TaskCmd;
use cmd::{
archive, blame, browse, cat, config, doctor, events, formats, hooks, pack, port, recipes, reshape, schema, search,
serve, session_reports, share, task, tools, view, workflow,
};
use std::path::PathBuf;
use util::{usage, UsageError, WindowArgs};
/// 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 clap tree is well-formed (debug asserts: conflicting ids, bad defaults, …).
/// Building the clap tree is deep: `Cli::command()` for every command with its 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.
#[cfg(test)]
pub(crate) 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");
}
/// 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", "workflow", "lanes", "stats", "blame",
"doctor",
],
),
(
"Reshape",
&[
"prune", "rewind", "distill", "adopt", "retire", "splice", "port", "resume",
],
),
("Export", &["export", "dataset", "pack"]),
("Fleet & live", &["task", "watch", "archive", "serve", "share"]),
(
"System",
&["index", "config", "schema", "formats", "recipes", "hooks", "hook"],
),
];
/// 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 {
/// Leave cv's stores untouched (also CV_FROZEN=1). Normally full reads record counts and
/// affordances, and events refreshes stale sessions for later reads. Frozen reads record
/// nothing: events streams stale sessions, ls keeps unknown counts as a dash, and scan/usage
/// caches and skipped sources are not saved. Commands that write stores or sessions exit 2.
#[arg(long, global = true)]
frozen: bool,
#[command(subcommand)]
cmd: Cmd,
}
#[derive(Subcommand)]
enum Cmd {
/// 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,
/// Print the shown rows oldest-first (ascending): the same newest `--limit` rows, read as
/// a feed. `cv ls --sort-by updated --asc` is what `cv timeline` used to print.
#[arg(long)]
asc: bool,
/// 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. A
/// row whose transcript cannot be read carries `enrich_error` instead.
#[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>,
/// Instead of the transcript, the message threading — a DAG when messages carry
/// `parent_id`, else a numbered list — then the sub-agent forest, over the whole session.
/// With `--json`, the IR itself: every message carries the same `parent_id`.
#[arg(long, conflicts_with_all = ["kind", "subagents", "agent", "pre_compaction"])]
tree: bool,
/// Only messages of these kinds, comma-separated, as a compact view. `prompt,answer`: what
/// the person said — every typed prompt and question-tool answer with its index and
/// timestamp, printed whole (`--json`: `index, timestamp, kind, text` rows; window flags
/// and `--max-bytes` slice the projected rows). `compaction_boundary,compaction_summary`: every compaction seam — trigger,
/// pre-compaction size, the summary that seeded the next window (`--json`: one row per
/// boundary with its `pre_compaction_span`). An affordance — `plan`, `goal`, `schedule`,
/// `background_job`, `subagent_spawn`, `subagent_return`, `skill`, `hook`, `question`,
/// `approval`, `checkpoint`, `branch`, `fork`, `model_change`, or `affordances` for all —
/// lists those rows across harnesses, side stores included (`--json`: `kind, action,
/// index, timestamp, tool, tool_use_id, summary, items, source` rows).
#[arg(long, value_name = "KIND,…", conflicts_with = "subagents")]
kind: Option<String>,
/// With the compaction kinds: print each summary in full, not just its head.
#[arg(long, requires = "kind")]
summaries: bool,
},
/// 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>,
/// Only sessions whose cwd contains this substring.
#[arg(long, value_name = "DIR")]
cwd: Option<String>,
/// Query calculus to filter candidate sessions before ranking (same as `cv ls -q`; see `cv schema`).
#[arg(long = "query", short = 'q', value_name = "QUERY")]
filter_query: Option<String>,
/// Hits to show. Every match is still counted: the footer says `N of M matches`.
#[arg(long, default_value_t = 20)]
limit: usize,
/// Stream every top-level transcript live (case-insensitive substring match across each
/// session's whole searchable exchange) instead of reading the full-text index: slow, skips
/// folded-in sub-agent lanes, and is never taken unasked. Without `--scan`, `cv search`
/// reads the Tantivy index plus the live suffix of sessions changed since `cv index` (even
/// when no index exists yet, unless `--live-bytes 0` or `--frozen`), and errors if an
/// existing index is unusable.
#[arg(long)]
scan: bool,
/// Match a literal substring with the trigram index and revision-verified source text.
#[arg(long, conflicts_with = "scan")]
exact: bool,
/// Which text to match: `exchange` (default: what the person asked, what the model
/// replied and ran, what came back), `context` (what surrounds it: injected instruction
/// files, system prompts, skill bodies, hook output, notices, compaction summaries), or
/// `all`. Context repeats across sessions, so it is matched only when asked for.
#[arg(long, value_name = "exchange|context|all", conflicts_with = "scan")]
kind: Option<String>,
/// The index answers plus a live read of the sessions it has not seen as they are now
/// (grown, rewritten, new since `cv index`), from where the index stopped: all of them by
/// default; with this, at most BYTES of source, newest sessions first, and the footer
/// names what the budget left out. 0 (or global --frozen) answers from the index alone.
/// Without it, `$CV_LIVE_BYTES` (bytes, or `all`) and then the config's
/// `[search] live_bytes` set the budget.
#[arg(long, value_name = "BYTES", conflicts_with = "scan")]
live_bytes: Option<u64>,
/// Emit `{"hits": [...], "total": M}` instead of the table — the same hits in the same
/// order (--harness/--cwd/-q/--limit respected), each 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`; `total` counts every
/// session that matched. 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.
/// This read command writes derived events and counts to cv's catalog; it never changes
/// harness transcripts. Use global --frozen (or CV_FROZEN=1) to stream stale events without
/// publishing them or updating other cv stores; see --frozen in the global options.
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. Every
/// target and detail is whole: the full command, the full error text.
#[arg(long)]
json: bool,
/// Print each table cell whole (newlines as spaces). Without it the target column is
/// shortened to 90 characters and the detail line to 100, a cut marked with `…`.
#[arg(long, conflicts_with = "json")]
wide: 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"): its full id, or a unique prefix
/// (several matches exit 2). `<orchestrator>` for the parent. With `--timeline` it narrows
/// the timeline instead.
#[arg(long)]
agent: Option<String>,
/// Which agents used this tool, across the forest (ranked by count). Not with `--agent`
/// unless `--timeline` narrows by both.
#[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, conflicts_with_all = ["agent", "tool", "timeline"])]
across: bool,
/// The time-ordered tool-call timeline (optionally narrowed with `--agent`).
#[arg(long)]
timeline: bool,
#[arg(long)]
json: bool,
},
/// 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,
/// Follow for this long (30s, 5m, 2h), then render the run as it stands; implies --follow.
#[arg(id = "for", long = "for", value_name = "DURATION")]
for_: Option<String>,
/// 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.
/// Prints prompts, so it excludes `--json`, `--script`, `--results` and `--follow`/`--for`.
#[arg(long, conflicts_with_all = ["json", "script", "results", "follow", "for"])]
revive: bool,
/// With `--revive`, include lanes that completed successfully too (default: only the ones
/// that did not finish).
#[arg(long, requires = "revive")]
revive_all: bool,
},
/// 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 while still holding an open obligation (an unreturned sub-agent, an open tool call,
/// a claimed task, an unanswered decision) or whose process died mid-turn. `--recent N`
/// reads the forests of a project's N most recent sessions instead of one session's;
/// with `--unfinished` that is the rescue list for `cv adopt`.
Lanes {
/// The session (`harness:id` or a unique prefix). Omit it with `--recent`.
#[arg(required_unless_present = "recent", conflicts_with = "recent")]
id: Option<String>,
#[arg(long)]
harness: Option<String>,
/// Instead of one session: the N most recently active sessions (of a harness whose hooks
/// record lanes: Claude Code, Codex) whose cwd is `--cwd` (default: the current
/// directory), each row tagged with its session.
#[arg(long, value_name = "N")]
recent: Option<usize>,
/// With --recent: the project directory the sessions ran in.
#[arg(long, value_name = "DIR", requires = "recent")]
cwd: Option<PathBuf>,
/// 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 (not failed or killed) with a recorded open obligation
/// (unreturned sub-agent, open tool call, claimed task, unanswered decision) or a process
/// that exited mid-turn. Decided from recorded structure, never from what the lane's last
/// text says. Each row carries the resume hint.
#[arg(long, group = "lane_filter")]
stranded: bool,
/// Only lanes not finished for real: running, stopped, killed, failed or stranded.
#[arg(long, group = "lane_filter")]
unfinished: 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,
},
/// 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,
},
/// 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,
/// Emit structured provenance attribution as JSON (`file`, `lines`, `commits`, `event_only_sessions`).
#[arg(long)]
json: 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,
/// Diagnose local cv stores (state.db, catalog.db, packs, search segments, disk/device health) without requiring a session.
#[arg(long, conflicts_with_all = ["id", "harness"])]
store: bool,
#[arg(long)]
json: bool,
},
/// 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, sub-agent's agent-<id>, or Claude transcript path.
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). An id whose transcript or sidecar already
/// exists is refused (exit 2) unless --force.
#[arg(long)]
to: Option<String>,
/// Replace an existing --to session (transcript and sidecar) by atomic rename.
#[arg(long, requires = "to")]
force: bool,
/// Hard-drop payloads (no sidecar, irreversible) instead of stashing them for retrieval.
#[arg(long)]
drop: bool,
/// Also omit the OLDEST assistant reasoning (thinking blocks) — recent thinking (within
/// --keep-last) stays verbatim. Omitted blocks leave no marker; `cv cat <new-id>
/// <record-uuid>#think<i>` returns each from the sidecar. 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,
/// 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>,
/// Restored Claude skills: keep all, drop all, or drop entries whose files changed or disappeared.
#[arg(long = "skills", value_parser = ["keep", "drop", "drop-stale"], default_value = "keep")]
skills: String,
/// Decide tool results by a plan file instead of --min-size/--keep-last: `{"results":
/// {"<tool_use_id>": {"action": "keep" | "precis" | "excerpt", "precis": "…", "keep":
/// ["literal passage", …]}}, "attachments": {"drop_kinds": ["hook_success", …]}}`. Only
/// planned results change; a précis or excerpt follows the usual marker and `cv cat` returns
/// the original. Dropped attachments are stashed by record uuid. A plan naming unknown ids,
/// or passages not in their payload, is refused (exit 2) before anything is written.
#[arg(long, value_name = "PATH", conflicts_with = "min_size")]
plan: 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,
},
/// 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 source's first record instead of the last compaction boundary before the
/// cut (the default: what a resume loads).
#[arg(long)]
full: bool,
/// Reasoning policy, two of the four `--thinking` values (a rewind writes Claude): `native`
/// keeps the source's reasoning and identifiers; `portable` demotes plaintext thinking to
/// text, removes signature-only reasoning and repairs tool IDs. `text` and `drop` are
/// refused here. Default: native when every model the window records is `claude-*`, else portable.
#[arg(long, value_parser = ["native", "portable"])]
thinking: Option<String>,
/// Restored Claude skills: keep all, drop all, or drop entries whose files changed or disappeared.
#[arg(long = "skills", value_parser = ["keep", "drop", "drop-stale"], default_value = "keep")]
skills: String,
/// 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: a hand-off (its
/// last message, the heads, tips and PID files it last saw), a grounding (its last state file,
/// the open items and decisions it wrote down, verbatim), the brief and every message to the
/// agent verbatim, its own words (text, messages sent, notes written; commit messages cut to
/// 700 bytes) verbatim, earlier generations' briefs, commits and state when it was distilled
/// before, an index of commits/branches/hosts/paths/verdicts/errors, a one-line-per-call
/// ledger naming each elided output's id and size, 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>,
/// Replace an existing --pack file by atomic rename (otherwise a taken name exits 2).
#[arg(long, requires = "pack")]
force: bool,
/// 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, visible_alias = "into", value_name = "ROOT")]
agent_of: Option<String>,
/// With --agent-of: the model the new sub-agent runs on, written to its meta (`opus`,
/// `sonnet`, a full model id, or `inherit`: the root's current model, which is also what
/// a meta without `model` means). Default: the source's meta value.
#[arg(long, value_name = "ID", requires = "agent_of")]
model: Option<String>,
/// With --agent-of: leave a sub-agent source unretired. By default the source is recorded
/// as retired with the new agent as its successor, which `cv hook retired` enforces
/// (`cv retire --undo <source>` reverses it). A distilled fork (`--upto`) never retires.
#[arg(long, requires = "agent_of")]
keep_source: bool,
/// 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,
},
/// 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/`. Find the agents with
/// `cv lanes <session>` (one session) or `cv lanes --recent N --unfinished` (the project's
/// recent sessions). An agent already in the live session is retargeted in place with
/// `--model` (a lane that hit one model's usage limit resumes on another).
Adopt {
/// Agent ids (`a5d8…` or `agent-a5d8…`, unique prefix ok).
#[arg(required = true)]
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).
#[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,
/// The model the adopted sub-agent runs on when resumed, written to its `agent-<id>.meta.json`
/// (`opus`, `sonnet`, a full model id, or `inherit`: the root's current model, which is
/// also what a meta without `model` means). Default: the copied meta's own value. The
/// meta's `pickedEffortModel` is dropped. For an agent already in `--into` and nowhere
/// else, nothing is copied: its meta is rewritten in place (`--into S --model ID`).
#[arg(long, value_name = "ID")]
model: Option<String>,
#[arg(long)]
json: bool,
},
/// The retired-agent ledger: `cv distill --agent-of` records the sub-agent it replaced, with
/// its successor. With `--list` (or no agent), lists who is retired; `<agent> [--successor <id>]`
/// retires one or updates an existing `PENDING` successor in place; `--undo <agent>` reverses.
/// `cv hooks install --retired` installs the PreToolUse guard that refuses a retired agent's
/// tool calls and messages to it.
Retire {
/// The agent id (`a5d8…` or `agent-a5d8…`). Omit it (or pass `--list`) to list.
agent: Option<String>,
/// List retired agents (same as omitting `<AGENT>`).
#[arg(long, conflicts_with_all = ["agent", "successor", "undo"])]
list: bool,
/// The agent that continues its work (named in the guard's refusal); updates an existing
/// retirement in place.
#[arg(long, value_name = "ID", requires = "agent", conflicts_with = "undo")]
successor: Option<String>,
/// Reverse a retirement.
#[arg(long, requires = "agent")]
undo: bool,
#[arg(long)]
json: bool,
},
/// Compose a new session from spans of existing ones (`<id>:A..B`): a verbatim prefix
/// (`<id>:..N`) forks a lane at message N; two spans graft one session's continuation onto
/// another's head. `--session` emits a resumable Claude session, `--agent-of <root>` a new
/// sub-agent of that root (as `distill` does); `--harness`/`--out` emit to any harness; with
/// neither, a summary prints (`--export md|json` prints the composed session).
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` or a
/// transcript path.
#[arg(required = true)]
specs: Vec<String>,
/// Emit a resumable main-thread Claude session (new id) under the Claude store or --out.
#[arg(long, conflicts_with_all = ["agent_of", "harness", "export"])]
session: bool,
/// Emit a new sub-agent transcript owned by this ROOT session (id or transcript path).
#[arg(
long,
visible_alias = "into",
value_name = "ROOT",
conflicts_with_all = ["harness", "export", "out", "cwd"]
)]
agent_of: Option<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>,
/// With --session / --agent-of: report as JSON on stdout (what was written, how to resume).
#[arg(long)]
json: 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.
/// `portable` demotes plaintext Claude reasoning, removes signature-only reasoning and repairs tool IDs;
/// other targets use the text policy.
#[arg(long, default_value = "native", value_parser = ["native", "text", "drop", "portable"])]
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>,
},
/// 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 `⚠ lossy:`.
#[arg(long)]
strict: bool,
/// Native keeps reasoning where the target holds it; portable demotes plaintext thinking to
/// text, removes signature-only reasoning and repairs tool IDs (other targets: the text
/// policy); text keeps unsupported reasoning as text/placeholders; drop omits reasoning.
/// Default: native when every recorded model is `claude-*`, else portable.
#[arg(long, value_parser = ["native", "text", "drop", "portable"])]
thinking: Option<String>,
/// Restored Claude skills: keep all, drop all, or drop entries whose files changed or disappeared.
#[arg(long = "skills", value_parser = ["keep", "drop", "drop-stale"], default_value = "keep")]
skills: String,
/// Emit the result as JSON on stdout (`path`, `id`, `harness`, `resume_hint`, `warnings`).
#[arg(long)]
json: 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 a session to markdown or OpenSession JSON (stdout); `cv share` is the HTML artifact.
Export {
id: String,
/// Output format: `md` (default) or `json`.
#[arg(long, default_value = "md")]
format: String,
#[arg(long)]
harness: Option<String>,
#[command(flatten)]
window: WindowArgs,
/// Scrub secrets/PII first — API keys, private keys, JWTs, emails, `KEY=value` assignments,
/// high-entropy blobs — with the same pass `cv share` runs; per-class counts go to stderr.
#[arg(long)]
redact: bool,
},
/// Export the corpus as a fine-tuning dataset (JSONL, one session per line).
/// `chatml`/`sharegpt`/`openai-tools` import directly into Unsloth Studio / TRL / HF — no adapter.
Dataset {
/// `chatml` (default) → {"messages":[…]}, `sharegpt` → {"conversations":[…]}, or
/// `openai-tools` → structured OpenAI `tool_calls` + `tool_call_id`.
#[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 session's sub-agent forest (the transcripts its adapter keeps beside it:
/// Claude's direct and `Workflow` agents, Codex children, Kimi and Hermes delegates). 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>,
/// Export only the active conversation branch (omitting rewound turns and sidechains).
#[arg(long = "active-branch")]
active_branch: bool,
/// Export only clean-outcome trajectories (omitting sessions ending in errors or unanswered tool calls).
#[arg(long = "clean-outcome")]
clean_outcome: bool,
/// Write to this file instead of stdout.
#[arg(long)]
file: Option<PathBuf>,
/// Replace an existing output file by atomic rename (otherwise a taken name exits 2).
#[arg(long)]
force: bool,
},
/// 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", value_parser = ["md", "prompt", "session"])]
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,
/// Write the md/prompt bundle to this file, or `--format session` under this directory.
#[arg(long)]
out: Option<PathBuf>,
/// Replace an existing output file by atomic rename (otherwise a taken name exits 2).
#[arg(long)]
force: 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.
/// `portable` demotes plaintext Claude reasoning, removes signature-only reasoning and repairs tool IDs;
/// other targets use the text policy.
#[arg(long, default_value = "native", value_parser = ["native", "text", "drop", "portable"])]
thinking: String,
/// Return the bundle or written artifact as a JSON result.
#[arg(long)]
json: bool,
/// Bytes of one message an excerpt shows; a longer one is cut there, an open code fence
/// closed, and marked `…`. The bundle's header states this and every other bound, and
/// what each cut.
#[arg(long, value_name = "N", default_value_t = pack::EXCERPT_BYTES)]
excerpt_bytes: usize,
},
/// Fleet task substrate: dispatch, review, and git-observed landing.
Task {
#[command(subcommand)]
action: TaskCmd,
},
/// Follow live activity and archive every session as it changes, forever (archives what
/// already exists on the first poll).
Watch {
/// Poll interval in seconds (0.25 minimum; negative is a usage error).
#[arg(long, default_value_t = 3.0)]
interval: f64,
/// Only this harness (e.g. claude, codex, gemini).
#[arg(long)]
harness: Option<String>,
/// Only sessions whose cwd contains this substring.
#[arg(long)]
cwd: Option<String>,
/// Archive home (default: $CLUSTERVISION_HOME or ~/.clustervision).
#[arg(long, value_name = "DIR")]
home: Option<PathBuf>,
/// Replicate sealed custody packs and events to this hub URL or `[replication.<target>]` profile.
#[arg(long, value_name = "TARGET")]
to: Option<String>,
/// Bearer credential for `--to` hub replication (overrides $CV_SERVE_TOKEN and profile token).
#[arg(long, value_name = "TOKEN", requires = "to")]
token: Option<String>,
},
/// The durable archive: every session snapshotted as IR under one home, for search and
/// safekeeping across machines (`sync` once, `ls`, `path`; `cv watch` keeps it current).
Archive {
/// Archive home (default: $CLUSTERVISION_HOME or ~/.clustervision).
#[arg(long, global = true, value_name = "DIR")]
home: Option<PathBuf>,
#[command(subcommand)]
action: ArchiveCmd,
},
/// One local HTTP server: the read API at /api/* (what the dashboard and app read), the task
/// inbox at /inbox (decisions as buttons; writes record the same events the CLI does, as
/// `web:<who>`), and with `--web DIR` the dashboard at /. Loopback only unless `--host` is
/// non-loopback AND a token (or `--insecure-expose`) is given.
Serve {
/// Port to listen on (0 picks a free one; the banner prints the real port).
#[arg(long, default_value_t = 7777)]
port: u16,
/// Host/interface to bind.
#[arg(long, default_value = "127.0.0.1")]
host: String,
/// Also host the browser dashboard from this directory (the repo's `web/`).
#[arg(long, value_name = "DIR")]
web: Option<PathBuf>,
/// Require `Authorization: Bearer <token>` on every /api/* request ($CV_SERVE_TOKEN works too).
#[arg(long, value_name = "TOKEN")]
token: Option<String>,
/// Allow a non-loopback --host without a token. The transcript corpus can contain
/// secrets; anyone who can reach the port can read all of it and act in the inbox.
#[arg(long)]
insecure_expose: bool,
/// Whose inbox /inbox opens on, and who a write is by when it names nobody. Default: $CV_ENDPOINT.
#[arg(long)]
who: Option<String>,
/// Open the inbox in the default browser once the server is up.
#[arg(long)]
open: bool,
/// Enable fleet replication hub receiver & pinned snapshot routes (/api/hub/*).
#[arg(long)]
hub: 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>,
/// Replace an existing output file by atomic rename (otherwise a taken name exits 2).
#[arg(long)]
force: bool,
/// Skip the redaction pass (default is to scrub secrets/PII before sharing).
#[arg(long)]
no_redact: bool,
},
/// 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 {
/// Clear and rebuild the index from scratch instead of incrementally updating it.
#[arg(long)]
rebuild: bool,
/// Also build the trigram accelerator for `cv search --exact` (an additional source pass).
#[arg(long)]
exact: 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,
/// Skip the pass when a stat-only probe shows nothing changed since the last index —
/// for timers and other scheduled callers that fire whether or not the corpus moved.
/// An explicit bare `cv index` still means "run now".
#[arg(long, conflicts_with = "rebuild")]
if_changed: bool,
/// Fail (exit 1) when any session cannot be read. By default such sessions are warnings:
/// the index commits the rest and a later pass retries them.
#[arg(long)]
strict: bool,
/// Print the result as JSON: `{indexed, changed, removed, errors, path, unreadable:
/// [{id, harness, reason}]}`.
#[arg(long)]
json: 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,
},
/// The format census: what the most recent sessions actually contain, per harness — message
/// kinds, block types and the record vocabulary the adapter did not interpret. Types the
/// manifest does not name are marked `NEW`, the drift signal.
Formats {
/// Only this harness.
#[arg(long)]
harness: Option<String>,
/// How many recent sessions per harness to parse.
#[arg(long, default_value_t = 20, value_name = "N")]
recent: usize,
#[arg(long)]
json: bool,
},
/// The agent quickstart: the things agents do with cv, each as one command line with the JSON
/// keys it returns.
Recipes,
/// Wire cv into Claude Code or Codex: install / remove / show the five hooks (`cv hook …`),
/// `--retired` (retired-agent PreToolUse guard), `--receipts` (hash-chained tool receipt log),
/// and the `cv` skill in settings. Idempotent and reversible; agents set this up for themselves.
Hooks {
#[command(subcommand)]
action: HooksCmd,
},
/// One hook's body, run by the harness: reads the hook JSON on stdin, prints a line or two of
/// hook JSON (or nothing). `cv hooks install <harness>` writes the entries that call these.
Hook {
#[arg(value_enum)]
name: HookName,
/// The harness whose payload is on stdin (`claude` or `codex`; default `claude`).
#[arg(long)]
harness: Option<String>,
},
}
#[derive(Subcommand)]
enum ArchiveCmd {
/// Discover and archive every session once, then exit (idempotent: unchanged ones are skipped).
Sync {
/// Replicate sealed custody packs and events to this hub URL or `[replication.<target>]` profile.
#[arg(long, value_name = "TARGET")]
to: Option<String>,
/// Bearer credential for `--to` hub replication (overrides $CV_SERVE_TOKEN and profile token).
#[arg(long, value_name = "TOKEN", requires = "to")]
token: Option<String>,
},
/// List what's in the archive, newest activity first.
Ls,
/// Print the archive location.
Path,
}
/// 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, a taken output
// name) exit 2 with the bare message; everything else is a real failure: the anyhow
// chain, exit 1.
if e.downcast_ref::<UsageError>().is_some() || e.downcast_ref::<cv_core::publish::Exists>().is_some() {
eprintln!("{e:#}");
std::process::exit(2);
}
eprintln!("Error: {e:?}");
std::process::exit(1);
}
}
fn run() -> Result<()> {
let mut tree = build_cli();
let matches = tree.get_matches_mut();
let cli = match Cli::from_arg_matches(&matches) {
Ok(cli) => cli,
Err(e) => e.exit(),
};
drop((matches, tree));
// Install before any library read, and enter it so subprocesses inherit the flag
// as CV_FROZEN without mutating the process environment.
let env = cv_core::env::Env::from_process();
let env = if cli.frozen { env.with_frozen() } else { env };
cv_core::env::Env::install(env.clone());
let _env = env.enter();
if cv_core::env::frozen() {
let writes = match &cli.cmd {
Cmd::Index { .. } | Cmd::Port { .. } | Cmd::Share { .. } | Cmd::Hook { .. } | Cmd::Watch { .. } => true,
Cmd::Task { action } => !matches!(
action,
task::TaskCmd::List { .. }
| task::TaskCmd::Show { .. }
| task::TaskCmd::Inbox { .. }
| task::TaskCmd::Events { .. }
),
Cmd::Prune { dry_run, .. } | Cmd::Rewind { dry_run, .. } | Cmd::Adopt { dry_run, .. } => !*dry_run,
Cmd::Distill {
session,
agent_of,
pack,
out,
..
} => *session || agent_of.is_some() || pack.is_some() || out.is_some(),
Cmd::Splice {
session,
agent_of,
harness,
out,
..
} => *session || agent_of.is_some() || harness.is_some() || out.is_some(),
Cmd::Hooks { action } => !matches!(action, HooksCmd::Show { .. }),
Cmd::Archive { action, .. } => matches!(action, ArchiveCmd::Sync { .. }),
Cmd::Config { add_export, rm_export } => add_export.is_some() || rm_export.is_some(),
Cmd::Pack { format, out, .. } => format == "session" || out.is_some(),
Cmd::Dataset { file, .. } => file.is_some(),
Cmd::Resume { launch, .. } => *launch,
Cmd::Retire { agent, .. } => agent.is_some(),
_ => false,
};
if writes {
return usage("--frozen (CV_FROZEN=1) forbids this command: it writes stores or sessions");
}
}
// Long-running services scope reuse per request/poll, so cold private snapshots do not
// survive idle server time. Ordinary commands share one cache across their session reads.
let _reads = (!matches!(
&cli.cmd,
Cmd::Serve { .. }
| Cmd::Watch { .. }
| Cmd::Workflow { follow: true, .. }
| Cmd::Workflow { for_: Some(_), .. }
))
.then(cv_core::source::read_scope);
match cli.cmd {
Cmd::Ls {
harness,
cwd,
query,
limit,
sort_by,
asc,
fresh,
json,
enrich,
} => browse::cmd_ls(browse::LsArgs {
harness,
cwd,
query,
limit,
sort_by: &sort_by,
asc,
fresh,
json,
enrich,
}),
Cmd::Search {
query,
harness,
cwd,
filter_query,
limit,
scan,
exact,
kind,
live_bytes,
json,
} => search::cmd_search(search::SearchArgs {
query: &query,
harness,
cwd,
filter_query,
limit,
scan,
exact,
kind,
live_bytes,
json,
}),
Cmd::Show {
id,
harness,
json,
window,
subagents,
agent,
pre_compaction,
tree,
kind,
summaries,
} => view::cmd_show(
&id,
harness,
json,
&window,
view::ShowView {
subagents,
agent,
pre_compaction,
tree,
kind,
summaries,
},
),
Cmd::Cat {
session,
tool_use_id,
harness,
input,
} => cat::cmd_cat(&session, &tool_use_id, harness, input),
Cmd::Export {
id,
format,
harness,
window,
redact,
} => view::cmd_export(&id, &format, harness, &window, redact),
Cmd::Dataset {
format,
harness,
query,
subagents,
limit,
min_messages,
redact,
redact_only,
active_branch,
clean_outcome,
file,
force,
} => reshape::cmd_dataset(reshape::DatasetArgs {
format: &format,
harness,
query,
subagents,
limit,
min_messages,
redact,
redact_only,
active_branch,
clean_outcome,
file,
force,
}),
Cmd::Port {
id,
harness,
cwd,
out,
no_context,
strict,
thinking,
skills,
json,
} => port::cmd_port(
&id,
harness,
cwd,
out,
no_context,
strict,
thinking.as_deref().map(util::parse_thinking).transpose()?,
skills.parse()?,
json,
),
Cmd::Index {
rebuild,
exact,
subagents,
if_changed,
strict,
json,
} => search::cmd_index(rebuild, subagents, if_changed, strict, json, exact),
Cmd::Events {
id,
harness,
kind,
subagents,
json,
wide,
} => events::cmd_events(&id, harness, kind, subagents, json, wide),
Cmd::Touched { path, edits_only, json } => events::cmd_touched(&path, edits_only, json),
Cmd::Blame {
file,
lines,
show,
json,
} => blame::cmd_blame(&file, lines.as_deref(), show, json),
Cmd::Share {
id,
harness,
out,
force,
no_redact,
} => share::cmd_share(&id, harness, out, force, no_redact),
Cmd::Pack {
task,
format,
harness,
limit,
out,
force,
thinking,
json,
excerpt_bytes,
} => pack::cmd_pack(pack::PackArgs {
task: &task,
format: &format,
harness,
limit,
out,
force,
thinking: util::parse_thinking(&thinking)?,
json,
excerpt_bytes,
}),
Cmd::Stats { query, json, tokens } => browse::cmd_stats(query, json, tokens),
Cmd::Prune {
id,
harness,
min_size,
keep_last,
to,
force,
drop,
drop_thinking,
copy_resources,
no_revive,
window,
keep,
declassify,
declassify_tokens,
declassify_tokens_file,
skills,
plan,
dry_run,
json,
} => reshape::cmd_prune(reshape::PruneArgs {
id: &id,
harness,
min_size,
keep_last,
to,
force,
drop,
thinking: drop_thinking,
copy_resources,
revive: !no_revive,
window,
keep,
declassify,
declassify_tokens,
declassify_tokens_file,
skills_policy: skills.parse()?,
plan,
dry_run,
json,
}),
Cmd::Rewind {
id,
harness,
at,
agent,
out,
to,
thinking,
skills,
full,
dry_run,
json,
} => reshape::cmd_rewind(reshape::RewindArgs {
id: &id,
harness,
agent,
at: at.as_deref(),
out,
to,
full,
thinking: thinking.as_deref().map(util::parse_thinking).transpose()?,
skills_policy: skills.parse()?,
dry_run,
json,
generator: 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 { harness, recent, json } => formats::cmd_formats(harness, recent, json),
Cmd::Recipes => recipes::cmd_recipes(),
Cmd::Hooks { action } => hooks::cmd_hooks(action),
Cmd::Hook { name, harness } => hooks::cmd_hook(name, harness),
Cmd::Retire {
agent,
list: _,
successor,
undo,
json,
} => cmd::retire::cmd_retire(agent, successor, undo, json),
Cmd::Resume { id, harness, launch } => port::cmd_resume(&id, harness, launch),
Cmd::Workflow {
id,
run_id,
harness,
json,
script,
results,
follow,
for_,
revive,
revive_all,
} => workflow::cmd_workflow(workflow::WorkflowArgs {
id: &id,
run_id,
harness,
json,
script,
results,
follow,
for_,
revive,
revive_all,
}),
Cmd::Tools {
id,
harness,
agent,
tool,
workflow: wf,
across,
timeline,
json,
} => tools::cmd_tools(tools::ToolsArgs {
id: &id,
harness,
agent,
tool,
workflow: wf,
across,
timeline,
json,
}),
Cmd::Lanes {
id,
harness,
recent,
cwd,
running,
done,
stranded,
unfinished,
since,
tasks,
json,
} => {
let filter = if running {
session_reports::LaneFilter::Running
} else if done {
session_reports::LaneFilter::Done
} else if stranded {
session_reports::LaneFilter::Stranded
} else if unfinished {
session_reports::LaneFilter::Unfinished
} else {
session_reports::LaneFilter::All
};
let scope = match (id, recent) {
(Some(id), _) => session_reports::LaneScope::Session { id, harness },
(None, Some(n)) => session_reports::LaneScope::Recent {
n,
dir: match cwd {
Some(d) => d,
None => std::env::current_dir().context("reading the current directory")?,
},
},
(None, None) => unreachable!("clap requires <ID> unless --recent is present"),
};
session_reports::cmd_lanes(scope, filter, since, tasks, json)
}
Cmd::Doctor {
id,
harness,
recent,
store,
json,
} => {
if store {
doctor::cmd_doctor_store(json)
} else {
doctor::cmd_doctor(id, harness, recent, json)
}
}
Cmd::Task { action } => task::cmd_task(action),
Cmd::Watch {
interval,
harness,
cwd,
home,
to,
token,
} => archive::cmd_watch(&archive::Archive::resolve(home)?, interval, harness, cwd, to, token),
Cmd::Archive { home, action } => {
let a = archive::Archive::resolve(home)?;
match action {
ArchiveCmd::Sync { to, token } => archive::cmd_sync(&a, to, token),
ArchiveCmd::Ls => archive::cmd_ls(&a),
ArchiveCmd::Path => archive::cmd_path(&a),
}
}
Cmd::Serve {
port,
host,
web,
token,
insecure_expose,
who,
open,
hub,
} => {
let opts = serve::ServeOpts {
host,
port,
web,
token,
insecure_expose,
who: who.or_else(cv_core::task::default_endpoint),
open,
};
if hub {
serve::cmd_serve_with_hub(opts, true)
} else {
serve::cmd_serve(opts)
}
}
Cmd::Distill {
id,
harness,
keep_last,
tail_result_max,
note_max,
keep_tail_thinking,
no_ledger,
upto,
with,
pack,
force,
session,
agent_of,
model,
keep_source,
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, model, cwd, out)?;
let retire = !keep_source && upto.is_none();
cmd::distill::cmd_distill(&id, harness, opts, upto, &with, pack, force, target, retire, json)
}
Cmd::Adopt {
agents,
into,
from,
dry_run,
force,
model,
json,
} => cmd::adopt::cmd_adopt(cmd::adopt::AdoptArgs {
agents,
into,
from,
dry_run,
force,
model,
json,
}),
Cmd::Splice {
specs,
session,
agent_of,
harness,
out,
json,
export,
cwd,
thinking,
} => {
// `--session` / `--agent-of` take the distill destinations (`--out`/`--cwd` ride along
// with `--session`); without them `--out`/`--cwd` keep their harness-emit meaning.
let resumable = if session || agent_of.is_some() {
Some(cmd::distill::target(session, agent_of, None, cwd.clone(), out.clone())?)
} else {
None
};
reshape::cmd_splice(reshape::SpliceArgs {
specs: &specs,
harness,
out,
export,
cwd,
thinking: util::parse_thinking(&thinking)?,
resumable,
json,
})
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cmd::reshape::resolve_declassify_tokens;
#[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();
}
#[test]
fn clap_tree_is_valid() {
crate::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() {
crate::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"
);
}
}
// Removed commands are gone outright (no hidden stubs).
for old in [
"timeline",
"redact",
"diff",
"board",
"fork",
"loom",
"tree",
"compaction",
"prompts",
"mcp",
"scry",
"deferrals",
] {
assert!(
!cmd.get_subcommands().any(|s| s.get_name() == old),
"{old} must not exist"
);
}
}
/// `cv --help` lists the groups and ends with the recipes pointer.
#[test]
fn help_is_grouped_and_ends_with_recipes() {
crate::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(" timeline ") && !help.contains(" redact "),
"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}");
}
}