scc-cli 0.2.10

System Context Compiler CLI, daemon, MCP server, and Claude Code plugin
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
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
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
//! `scc` — System Context Compiler CLI (docs/API_AND_INTEGRATIONS.md §4).

use clap::{Parser, Subcommand};
use scc_cli::commands;
use scc_core::estimate_tokens;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

#[derive(Parser)]
#[command(
    name = "scc",
    version,
    about = "System Context Compiler — compile repositories into evidence-backed system context for coding agents",
    long_about = "Continuously compiles code, configuration, infrastructure, runtime evidence, and architectural intent \
                   into an evidence-backed machine model of a software system, then emits small task-specific context packs \
                   for coding agents. Give agents more repository understanding per token."
)]
// trace:v1 id=impl.scc.cli.main work=WORK-SCC-014 satisfies=REQ-SCC-IR
struct Cli {
    #[command(subcommand)]
    command: Commands,

    /// Repository root (default: nearest directory containing .git or .scc)
    #[arg(long, global = true)]
    root: Option<PathBuf>,
}

#[derive(Subcommand)]
// trace:exempt reason=internal-detail
enum PluginSub {
    /// List enabled plugins with lock entries
    List,
    /// Describe one plugin manifest
    Describe {
        /// Plugin id
        id: String,
    },
    /// Inspect one plugin manifest (alias for describe, §29 name)
    Inspect {
        /// Plugin id
        id: String,
    },
    /// Plugin environment + failure diagnostics
    Doctor,
    /// Write .scc/plugins.lock from the live plugin set (reproducible installs)
    Lock,
    /// Verify the live plugin set against .scc/plugins.lock (fail on drift)
    Check,
    /// Deterministic extension order per type (priority + before/after DAG)
    Graph,
    /// Invoke a plugin operation: scc plugin invoke <operation> [json-input]
    Invoke {
        /// Operation id (e.g. acme.echo)
        operation: String,
        /// JSON input (default {})
        #[arg(default_value = "{}")]
        input: String,
    },
    /// Add a plugin id to the project allow-list (plugins.enabled)
    Enable {
        /// Plugin id (must be discovered)
        id: String,
    },
    /// Remove a plugin id from the project allow-list
    Disable {
        /// Plugin id
        id: String,
    },
}

#[derive(Subcommand)]
// trace:exempt reason=internal-detail
enum Commands {
    /// Initialize the SCC workspace (.scc/config.yaml + database)
    Init,

    /// Index the repository (cold on first run, incremental afterwards)
    Index {
        /// Only refresh these paths (watch/post-edit)
        #[arg(long, num_args = 1.., value_delimiter = ' ')]
        paths: Vec<String>,
        #[arg(long)]
        quiet: bool,
        /// Run the language-aware semantic backends before recompiling
        /// (Wave 4 lazy resolution: pyright + typescript-language-server)
        #[arg(long)]
        resolve: bool,
    },

    /// Show index status, stats, and freshness
    Status,

    /// Diagnose the scan: what `scc index` would index and what it skips,
    /// per path, with the responsible rule (no indexing, read-only)
    Scan {
        /// One path verdict instead of the summary (exit 1 skipped, 2 missing)
        path: Option<String>,
        /// Full indexed + skipped lists as JSON
        #[arg(long)]
        json: bool,
    },

    /// Print the generated language-support matrix (from the registry)
    Languages,

    /// Watch the filesystem and re-index changed files
    Watch,

    /// Print the startup capsule / system overview
    Overview {
        #[arg(long)]
        json: bool,
    },

    /// Compile context packs
    Context {
        #[command(subcommand)]
        sub: ContextSub,
    },

    /// The System Surface Map: the actual callable API layer (Wave 14)
    Surface {
        /// Personalize the map for a task goal (task PPR re-ranking)
        #[arg(long)]
        task: Option<String>,
        #[arg(long)]
        budget: Option<usize>,
        /// Append per-entry rank reasons
        #[arg(long)]
        explain: bool,
    },

    /// Impact analysis for a change
    Impact {
        /// Git base for the diff (e.g. origin/main, HEAD~1)
        #[arg(long)]
        diff: Option<String>,
        /// Affected files
        #[arg(value_delimiter = ' ')]
        files: Vec<String>,
        #[arg(long)]
        symbols: Vec<String>,
        #[arg(long)]
        json: bool,        /// Human mode: skip hard token caps (soft legacy render, excess
        /// reported not enforced). Agents must never use this.
        #[arg(long)]
        unbounded: bool,
    },

    /// Full System Atlas: complete architecture for agent session startup
    Atlas {
        /// Token budget (default: context.atlas_tokens, 15000)
        #[arg(long)]
        budget: Option<usize>,
        #[arg(long)]
        json: bool,
        /// Full scope: include test/fixture/benchmark evidence in the
        /// architecture sections (default is the production scope)
        #[arg(long)]
        full: bool,        /// Human mode: skip hard token caps (soft legacy render, excess
        /// reported not enforced). Agents must never use this.
        #[arg(long)]
        unbounded: bool,
        /// Resolve unresolved call edges through the language backends first
        #[arg(long)]
        resolve: bool,
    },

    /// Verify freshness, evidence integrity, and drift
    Verify {
        /// Only print warnings (for hooks)
        #[arg(long)]
        warnings: bool,
        #[arg(long)]
        json: bool,        /// Human mode: skip hard token caps (soft legacy render, excess
        /// reported not enforced). Agents must never use this.
        #[arg(long)]
        unbounded: bool,
    },

    /// Show architectural drift findings
    Drift {
        #[arg(long)]
        json: bool,
    },

    /// Multi-repo system: semantic stitches across member checkouts
    System {
        /// Member checkout roots (each already indexed)
        #[arg(long, required = true)]
        member: Vec<PathBuf>,
        #[arg(long)]
        json: bool,
    },

    /// Export the System IR
    Export {
        /// system-ir.json | system-ir.jsonl | ccg | flow-graphs.json
        #[arg(default_value = "system-ir.json")]
        format: String,
    },

    /// Lexical search over entities and symbols
    Query {
        query: String,
        #[arg(long, default_value_t = 20)]
        limit: usize,
    },

    /// Multi-step graph traversal (out|in|both, predicate + kind filters)
    Traverse {
        #[arg(long)]
        kind: Option<String>,
        #[arg(long)]
        name: Option<String>,
        #[arg(long)]
        from: Vec<String>,
        /// Step as dir[:predicate[:where_kind]] (repeatable), e.g. out:calls:symbol
        #[arg(long = "step")]
        steps: Vec<String>,
        #[arg(long, default_value_t = 100)]
        limit: usize,
    },

    /// List components
    Components,

    /// Architecture diagram from the L1 layer (SCC-native gitdiagram)
    Diagram {
        /// mermaid | svg
        #[arg(long, default_value = "mermaid")]
        format: String,
        /// Write to FILE instead of stdout
        #[arg(long)]
        out: Option<String>,
    },

    /// Local web viewer over the live index (loopback only)
    View {
        /// Port (default: ephemeral)
        #[arg(long)]
        port: Option<u16>,
        /// Print the URL without opening a browser
        #[arg(long)]
        no_open: bool,
    },

    /// Snapcompact-style bitmap export of the repo map (default OFF)
    Snap {
        /// Write the map text to FILE (stdout when absent)
        #[arg(long)]
        out: Option<String>,
        /// Max map-text chars (default 40000)
        #[arg(long, default_value_t = 40000)]
        max_chars: usize,
        /// Render PNG via the pinned Pillow recipe to FILE
        #[arg(long)]
        png: Option<String>,
        /// Accepted for recipe parity (monochrome unless recipe edited)
        #[arg(long)]
        color: bool,
    },

    /// List flows
    Flows,

    /// Show git co-change pairs (files changed together across commits)
    Cochange {
        /// Minimum number of shared commits
        #[arg(long, default_value_t = 2)]
        min_commits: u32,
    },

    /// Save or restore the task checkpoint (compaction recovery)
    Checkpoint {
        #[command(subcommand)]
        sub: CheckpointSub,
    },

    /// Graph revision history (durable temporal log)
    History {
        #[arg(long)]
        json: bool,
    },

    /// Semantic diff between two graph revisions
    Diff {
        #[arg(long)]
        from: i64,
        #[arg(long)]
        to: i64,
        #[arg(long)]
        json: bool,
    },

    /// Durable context snapshots: save, show, diff rendered knowledge
    Snapshot {
        #[command(subcommand)]
        sub: SnapshotSub,
    },

    /// Run graph invariant checks; exit nonzero on violation (CI)
    CheckInvariants,

    /// Install harness integrations (bare: auto-detect installed harnesses)
    Setup {
        #[command(subcommand)]
        sub: Option<SetupSub>,
    },

    /// Update the scc binary to the latest (or pinned) release
    Update {
        /// Install a specific release instead of the latest (e.g. 0.2.10)
        #[arg(long)]
        version: Option<String>,
        /// Install directory (default: the directory of the running binary)
        #[arg(long)]
        dir: Option<PathBuf>,
        /// Resolve and print the plan; download nothing
        #[arg(long)]
        dry_run: bool,
    },

    /// Start the local daemon (HTTP API + watcher)
    Serve,

    /// Run the MCP server on stdio
    Mcp,

    /// Structured JSON-RPC over stdio (SDK subprocess mode; never CLI text)
    Rpc {
        /// Force stdio mode (today the only mode)
        #[arg(long)]
        stdio: bool,
    },

    /// List registered engine operations (introspection)
    #[command(alias = "operation")]
    Operations {
        /// Describe one operation in detail
        #[arg(long)]
        describe: Option<String>,
    },

    /// Plugin extensions (list, describe, doctor, invoke)
    Plugin {
        #[command(subcommand)]
        sub: PluginSub,
    },

    /// Ingest runtime observations (POST /v1/runtime/traces body)
    Ingest {
        body: String,
    },

    /// Semantic resolution: upgrade EXTRACTED facts via a language server
    Resolve {
        /// Use the LSP adapter (pyright) for definition resolution
        #[arg(long)]
        lsp: bool,
    },

    /// Compute and store entity embeddings (optional semantic ranker)
    Embed,

    /// Most important symbols (global centrality or task-critical)
    Important {
        /// Max entries (default 15)
        #[arg(long, default_value_t = 15)]
        limit: usize,
        /// Filter to one component (substring)
        #[arg(long)]
        component: Option<String>,
        /// Rank by task relevance instead of global centrality
        #[arg(long)]
        task: Option<String>,
        #[arg(long)]
        json: bool,
    },

    /// List enabled adapters with their declared capability scope (security audit)
    Adapters {
        /// Dump the full capability manifests instead of the scope listing
        #[arg(long)]
        json: bool,
    },

    /// Integration health from the Integration Registry (offline by default)
    Doctor {
        /// Machine-readable report
        #[arg(long)]
        json: bool,
        /// Start LOCAL subprocesses for handshake detail (pyright/tsserver)
        #[arg(long)]
        deep: bool,
        /// Probe remote endpoints (Context7); never probed by default
        #[arg(long)]
        network: bool,
        /// Nonzero exit on any warning
        #[arg(long)]
        strict: bool,
    },

    /// Manage the Hindsight lesson bank (.scc/lessons.jsonl)
    Lessons {
        /// Bare `scc lessons` lists stored lessons (limit: --limit)
        #[command(subcommand)]
        sub: Option<LessonsSub>,
    },

    /// List active bead tasks from .beads/issues.jsonl
    Beads,

    /// Import external evidence (SCIP index, Narsil CCG)
    Import {
        /// scip | ccg | gitnexus
        format: String,
        /// Path to the evidence file
        file: String,
    },

    /// Runtime observations and static-vs-observed reconciliation
    Runtime {
        #[command(subcommand)]
        sub: RuntimeSub,
    },

    /// CI gate: graph invariants + drift severity policy
    Ci {
        #[command(subcommand)]
        sub: CiSub,
    },

    /// Run performance benchmarks on a synthetic repository
    Bench {
        #[command(subcommand)]
        sub: BenchSub,
    },

    /// Print the SCC state directory (honors SCC_STATE_DIR; used by agent
    /// integrations so a read-only repository with external state works)
    StatePath,
}

#[derive(Subcommand)]
// trace:v1 id=impl.crates-scc-cli-src-main.runtime-sub work=WORK-SCC-001 satisfies=REQ-SCC-API
enum RuntimeSub {
    /// List ingested runtime edges (aggregates)
    Status {
        #[arg(long)]
        json: bool,
    },
    /// Static-vs-observed reconciliation report
    Reconcile {
        #[arg(long)]
        json: bool,
    },
}

#[derive(Subcommand)]
// trace:v1 id=impl.crates-scc-cli-src-main.ci-sub work=WORK-SCC-001 satisfies=REQ-SCC-API
enum CiSub {
    /// Check invariants and drift; exit nonzero on violation
    Check {
        /// Highest drift severity that passes (low|medium|high|critical)
        #[arg(long, default_value = "medium")]
        max_severity: String,
    },
}

#[derive(Subcommand)]
// trace:exempt reason=internal-detail  # CLI subcommand enum (impl.scc.cli.main)
enum BenchSub {
    /// Cold/incremental index + task-pack latency on a generated repo
    Index {
        /// Number of generated files
        #[arg(long, default_value_t = 200)]
        files: usize,
        /// Lines per file
        #[arg(long, default_value_t = 250)]
        lines: usize,
    },
    /// Ground-truth context benchmark (docs/TEST_PLAN.md §84): recall,
    /// precision, localization, hallucinations, budgets
    Context {
        /// Minimum mean recall gate
        #[arg(long, default_value_t = 0.6)]
        min_recall: f64,
        /// Minimum mean precision gate (0.0 = recall-only, the default)
        #[arg(long, default_value_t = 0.0)]
        min_precision: f64,
    },
    /// Retrieval Recall@k / MRR over fixture gold (lexical vs production arms).
    /// Does not change the production fused ranker.
    Retrieval {
        #[arg(long, default_value_t = 10)]
        k: usize,
        /// Comma-separated ranking arms
        #[arg(long, default_value = "lexical-then-graph,query-routed,production-blended")]
        arms: String,
        /// Optional fixture repo filter (e.g. http-service-python)
        #[arg(long)]
        repo: Option<String>,
        /// Minimum mean recall@10 across printed arms (0 = measure only)
        #[arg(long, default_value_t = 0.0)]
        min_recall: f64,
        #[arg(long)]
        json: bool,
    },
    /// Locator loop vs baseline and Ripwire (clustered localization).
    /// Does not change production ranking. Missing Ripwire is skipped.
    Loop {
        /// Comma-separated arms: baseline,scc,ripwire
        #[arg(long, default_value = "baseline,scc,ripwire")]
        arms: String,
        /// Files opened per task
        #[arg(long, default_value_t = 10)]
        k: usize,
        /// Optional fixture repo filter
        #[arg(long)]
        repo: Option<String>,
        /// Ripwire binary (else RIPWIRE_BIN / PATH / vendored build)
        #[arg(long)]
        ripwire_bin: Option<PathBuf>,
        /// Fail when SCC clustered localization is below baseline by more than this
        #[arg(long, default_value_t = 0.0)]
        min_delta: f64,
        #[arg(long)]
        json: bool,
        /// JSONL pack-consumer protocol (search/read events) instead of locator
        #[arg(long)]
        explore: bool,
    },
    /// Agent-run recorder (SCC-002): run the corpus through an external
    /// agent command and record outcome metrics
    Agent {
        /// Agent command; receives the goal via $SCC_GOAL, runs in the repo
        #[arg(long)]
        cmd: String,
        /// Minimum mean localization gate
        #[arg(long, default_value_t = 0.0)]
        min_files: f64,
        /// Agent-behavior release gate: run the baseline (--baseline-cmd)
        /// AND the atlas variant (--cmd), then FAIL when the atlas variant
        /// does not reduce exploration (E.search_tool_calls < A.search,
        /// E.files_opened <= A.files_opened + 1, E.first_correct_ms <=
        /// A.first_correct_ms; means)
        #[arg(long)]
        gate: bool,
        /// Baseline (A) agent command for --gate; receives the goal via
        /// $SCC_GOAL, runs in the repo
        #[arg(long)]
        baseline_cmd: Option<String>,
    },
    /// Differential resolution benchmark (SCC-126): native vs LSP upgrades
    /// over the fixture corpus, gated on upgrades and unresolved externals
    Resolution {
        /// Maximum allowed fraction of external call candidates left
        /// unresolved after the LSP pass
        #[arg(long, default_value_t = scc_cli::benchres::DEFAULT_MIN_AGREEMENT)]
        min_agreement: f64,
    },
    /// Atlas recall benchmark (Wave 8 §57): recall of independently
    /// documented ground truth against the startup System Atlas on real
    /// repos (defaults: <repo-root>/benchmarks/corpus +
    /// <repo-root>/benchmarks/ground-truth; falls back to the fixtures when
    /// the corpus dir is absent)
    Atlas {
        /// Corpus directory (default: <repo-root>/benchmarks/corpus)
        #[arg(long)]
        corpus: Option<PathBuf>,
        /// Ground-truth docs directory (default: <repo-root>/benchmarks/ground-truth)
        #[arg(long)]
        ground_truth: Option<PathBuf>,
        /// Emit the full report as JSON (per-repo recall + all missed keys)
        #[arg(long)]
        json: bool,
        /// Classify every missed ground-truth item by gap kind
        /// (PARSER/EXTRACTOR/RESOLUTION/COMPILER/PROJECTION/ALIAS) and print
        /// a per-kind histogram plus per-repo gap lines (the regeneration
        /// source for benchmarks/results/ground-truth-gaps.md)
        #[arg(long)]
        diagnose: bool,
        /// Blind holdout protocol: score the dev corpus AND the holdout
        /// corpus (benchmarks/holdout + benchmarks/holdout-ground-truth),
        /// compare per-layer recall, write benchmarks/results/holdout-v3.txt
        /// and print the overfit verdict
        #[arg(long, conflicts_with = "blind")]
        holdout: bool,
        /// Blind-test protocol: score the validation corpus
        /// (benchmarks/holdout) AND the blind-test corpus
        /// (benchmarks/blind-test + benchmarks/blind-test-ground-truth),
        /// print ONLY aggregates (overall, per-section means, the
        /// validation-vs-blind generalization gap, precision, density — no
        /// per-repo rows, no missed keys, no filenames), and write
        /// benchmarks/results/blind-v1.txt. blind-test failures are never
        /// shown to tuning agents; --diagnose is refused on the blind corpus
        #[arg(long, conflicts_with = "holdout")]
        blind: bool,
        /// Skip the semantic resolution pass (pyright + tsserver) before
        /// scoring: the atlas then runs on native extraction only, and
        /// `resolved_calls` reports 0. Default is ON (resolve before
        /// scoring, so behavior flows seed from resolved call chains)
        /// for both the dev and holdout corpora.
        #[arg(long)]
        no_resolve: bool,
        /// Wave-11 generalization gates over two saved holdout result files
        /// (JSON `HoldoutComparison`s, e.g. `scc bench atlas --holdout
        /// --json` output): loads OLD (the earlier run) and NEW (the current
        /// run), prints the per-section deltas, the generalization
        /// efficiency GE = validation_delta / development_delta, and the
        /// per-section regression guard, then exits nonzero when a gate
        /// fails (semantic waves must generalize)
        #[arg(long, num_args = 2, value_names = ["OLD", "NEW"], conflicts_with_all = ["blind", "holdout"])]
        compare: Option<Vec<PathBuf>>,
        /// GE gate floor for `--compare`: fail when
        /// GE = validation_delta / development_delta <= MIN (default 0.0 —
        /// semantic waves must generalize to validation)
        #[arg(long, default_value_t = 0.0)]
        gate_ge: f64,
        /// Per-section regression guard for `--compare`: fail when ANY
        /// startup-required section (architecture/entrypoints/behavior/
        /// state_authority/contracts) drops by more than MAX between the
        /// two runs, in development or validation (default 0.05)
        #[arg(long, default_value_t = 0.05)]
        guard_section_delta: f64,
    },
    /// Wave-15 external benchmark suite: run one A-H context variant over
    /// a repo's ground-truth tasks through the benchagent protocol and
    /// print the spec §72 metric row (variant, success rate, mean
    /// exploration, first-plan accuracy, context tokens). Native variants
    /// (raw, scc-*, and the PPR ablation matrix lexical/global-ppr/
    /// task-ppr/ppr-mmr/ppr-quotas/ppr-optimizer) run in-process;
    /// aider-repomap / repomix-compress delegate to
    /// benchmarks/external/run_context_bench.py, which owns those pinned
    /// tools and reports SKIPPED-UNINSTALLED (missing) or PIN-MISMATCH
    /// (wrong installed commit) when they are not available.
    External {
        /// Variant: raw | aider-repomap | repomix-compress | scc-atlas |
        /// scc-surface | scc-atlas-surface | scc-full | lexical |
        /// global-ppr | task-ppr | ppr-mmr | ppr-quotas | ppr-optimizer
        #[arg(long)]
        variant: String,
        /// Restrict to one fixture repo (default: every ground-truth repo)
        #[arg(long)]
        repo: Option<String>,
        /// Context-artifact token budget (equal-token mode)
        #[arg(long, default_value_t = 8000)]
        budget: usize,
        /// Agent command; the prompt (context artifact + task goal) is
        /// piped to it on stdin and $SCC_GOAL carries the goal (the
        /// benchagent protocol, see benchmarks/run_agent_bench.sh)
        #[arg(long)]
        cmd: Option<String>,
        /// Workdir for generated artifacts and result JSON
        #[arg(long)]
        workdir: Option<PathBuf>,
        /// Emit the metric row as JSON
        #[arg(long)]
        json: bool,
        /// Generate ONLY the context artifact for ONE goal in --repo and
        /// print {artifact, tokens, budget} as JSON (the authoritative
        /// builder, reused by external harnesses — e.g. the writable
        /// coding matrix — so they never reconstruct SCC semantics in
        /// Python). No agent runs.
        #[arg(long)]
        artifact_only: Option<String>,
    },
}

#[derive(Subcommand)]
// trace:exempt reason=internal-detail
enum ContextSub {
    /// Wave 14C startup artifact: Atlas + Surface fusion, deterministic per
    /// epoch (prompt-cache stable)
    Startup {
        /// Token budget (default: the full startup split, 20000)
        #[arg(long)]
        budget: Option<usize>,
    },
    /// Structural Source: per-file signature/structural representation of
    /// the requested files, or of the files matched to a task goal
    Structural {
        /// Repository-relative file paths to render structurally
        #[arg(long, value_delimiter = ' ', required_unless_present = "task")]
        files: Vec<String>,
        /// Task goal: resolve to the matching files via the PPR->Surface
        /// pipeline (build_surface Task mode)
        #[arg(long)]
        task: Option<String>,
        /// Token budget (default: context.structural_source, 6000; scales
        /// the unit cap)
        #[arg(long)]
        budget: Option<usize>,
    },
    /// Task context pack for a goal
    Task {
        goal: String,
        #[arg(long, value_delimiter = ' ')]
        files: Vec<String>,
        #[arg(long)]
        symbols: Vec<String>,
        #[arg(long)]
        budget: Option<usize>,
        #[arg(long)]
        json: bool,
        /// Hook mode (UserPromptSubmit): prints nothing unless
        /// context.inject_task_focus is enabled; caps the focus budget.
        #[arg(long, hide = true)]
        hook: bool,
        /// Resolve unresolved call edges through the language backends first
        #[arg(long)]
        resolve: bool,
    },
    /// Component context pack
    Component {
        id: String,
        #[arg(long)]
        json: bool,        /// Human mode: skip hard token caps (soft legacy render, excess
        /// reported not enforced). Agents must never use this.
        #[arg(long)]
        unbounded: bool,
    },
    /// Flow context pack
    Flow {
        id: String,
        #[arg(long)]
        json: bool,        /// Human mode: skip hard token caps (soft legacy render, excess
        /// reported not enforced). Agents must never use this.
        #[arg(long)]
        unbounded: bool,
    },
    /// Compress a task pack (structural; optional external summarizer)
    Compress {
        goal: String,
        /// External summarizer command (stdin -> stdout); output is labeled INFERRED
        #[arg(long)]
        cmd: Option<String>,
        /// Constrained mode: summarizer must emit typed claims with known evidence
        #[arg(long)]
        claims: bool,
        #[arg(long)]
        budget: Option<usize>,
        #[arg(long)]
        json: bool,
    },
    /// External library docs via Context7 (labeled external)
    Docs {
        /// dependency in owner/name form (e.g. fastapi/fastapi)
        dependency: String,
    },
    /// Subagent-scoped task pack (tight budget + scope boundaries)
    Subagent {
        goal: String,
        #[arg(long, value_delimiter = ' ')]
        files: Vec<String>,
        #[arg(long)]
        symbols: Vec<String>,
        #[arg(long)]
        budget: Option<usize>,
        #[arg(long)]
        json: bool,
    },
}

#[derive(Subcommand)]
// trace:v1 id=impl.crates-scc-cli-src-main.snapshot-sub work=WORK-SI-MMMJA4G6 satisfies=REQ-SI-503JSBGP
enum SnapshotSub {
    /// Render a task pack and persist it as a durable snapshot
    Save {
        /// Task goal to render
        #[arg(long)]
        task: String,
        /// Token budget for the render
        #[arg(long)]
        budget: Option<usize>,
        #[arg(long)]
        json: bool,
    },
    /// Print a stored snapshot render (resume)
    Show {
        /// Snapshot id
        id: String,
    },
    /// Diff a snapshot against the current model
    Diff {
        /// Snapshot id
        id: String,
        #[arg(long)]
        json: bool,
    },
}

#[derive(Subcommand)]
// trace:v1 id=impl.crates-scc-cli-src-main.checkpoint-sub work=WORK-SCC-001 satisfies=REQ-SCC-API
enum CheckpointSub {
    /// Capture the current task state
    Save {
        /// Emit the checkpoint JSON on stdout
        #[arg(long)]
        json: bool,
    },
    /// Load and print the checkpoint (rehydration)
    Load {
        /// Silent when no checkpoint exists (hook use)
        #[arg(long)]
        inject: bool,
    },
}

#[derive(Subcommand)]
// trace:v1 id=impl.crates-scc-cli-src-main.lessons-sub work=WORK-SCC-001 satisfies=REQ-SCC-API
enum LessonsSub {
    /// Append a lesson to .scc/lessons.jsonl (ingest with `scc import hindsight .scc/lessons.jsonl`)
    Add {
        text: String,
    },
    /// List stored lessons from the store (after `scc import hindsight`)
    List {
        #[arg(long, default_value_t = 20)]
        limit: usize,
    },
}

#[derive(Subcommand)]
// trace:exempt reason=evolved
enum SetupSub {
    /// Install Claude Code hooks
    Claude,
    /// Write AGENTS.md with the system capsule (Codex and other harnesses)
    Codex,
    /// Write AGENTS.md + .opencode/opencode.json (SCC MCP server)
    Opencode,
    /// Install the Hermes plugin (native tools + skill)
    Hermes,
    /// Install the Oh My Pi (OMP) native integration (extension + MCP + skill + AGENTS)
    Omp,
    /// Install the upstream Pi project-local extension (.pi/extensions/scc)
    Pi,
    /// Install for every supported harness (no detection)
    All,
}

// trace:exempt reason=internal-detail
fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Default SIGPIPE behavior: dying silently on `scc ... | head` is the
    // standard Unix contract; ignoring it makes println! panic on EPIPE.
    unsafe {
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
    }
    let cli = Cli::parse();
    let root = match cli.root.clone() {
        // explicit --root is exact: no upward walk
        Some(r) if r.is_absolute() => r,
        Some(r) => std::env::current_dir().unwrap().join(r),
        None => scc_cli::find_root(&std::env::current_dir().unwrap()),
    };

    let result = match cli.command {
        Commands::Init => commands::cmd_init(&root),
        Commands::Index { paths, quiet, resolve } => {
            if resolve {
                commands::cmd_index(&root, quiet)?;
                let rep = scc_cli::resolve_and_recompile(&root)?;
                if !quiet {
                    println!(
                        "resolved: {} upgraded, {} unresolved, {} errors",
                        rep.upgraded, rep.unresolved, rep.errors
                    );
                }
                Ok(())
            } else if paths.is_empty() {
                commands::cmd_index(&root, quiet)
            } else {
                commands::cmd_index_paths(&root, &paths, quiet)
            }
        }
        Commands::Status => commands::cmd_status(&root),
        Commands::Scan { path, json } => commands::cmd_scan(&root, path.as_deref(), json),
        Commands::Languages => commands::cmd_languages(),
        Commands::Watch => commands::cmd_watch(&root),
        Commands::Overview { json } => commands::cmd_overview(&root, json),
        Commands::Context { sub } => match sub {
            ContextSub::Startup { budget } => commands::cmd_context_startup(&root, budget),
            ContextSub::Structural { files, task, budget } => {
                let out =
                    commands::cmd_context_structural(&root, &files, task.as_deref(), budget)?;
                print!("{out}");
                Ok(())
            }
            ContextSub::Task { goal, files, symbols, budget, json, hook, resolve } => {
                if resolve {
                    let rep = scc_cli::resolve_and_recompile(&root)?;
                    eprintln!(
                        "resolved: {} upgraded, {} unresolved, {} errors",
                        rep.upgraded, rep.unresolved, rep.errors
                    );
                }
                commands::cmd_context_task(&root, &goal, &files, &symbols, budget, json, hook)
            }
            ContextSub::Component { id, json, unbounded } => commands::cmd_context_component(&root, &id, json, unbounded),
            ContextSub::Flow { id, json, unbounded } => commands::cmd_context_flow(&root, &id, json, unbounded),
            ContextSub::Docs { dependency } => commands::cmd_context_docs(&root, &dependency),
            ContextSub::Subagent { goal, files, symbols, budget, json } => {
                commands::cmd_context_subagent(&root, &goal, &files, &symbols, budget, json)
            }
            ContextSub::Compress { goal, cmd, claims, budget, json } => {
                if claims {
                    let out = scc_cli::compress::cmd_context_compress_json_claims(
                        &root, &goal, cmd, budget, true,
                    )?;
                    if json {
                        println!("{out}");
                    } else {
                        let pack: scc_context::ContextPack = serde_json::from_str(&out)?;
                        print!("{}", pack.content);
                    }
                    Ok(())
                } else {
                    scc_cli::compress::cmd_context_compress(&root, &goal, cmd, budget, json)
                }
            }
        },
        Commands::Impact { diff, files, symbols, json, unbounded } => {
            commands::cmd_impact(&root, &files, &symbols, diff.as_deref(), json, unbounded)
        }
        Commands::Surface { task, budget, explain } => {
            commands::cmd_surface(&root, task.as_deref(), budget, explain)
        }
        Commands::Atlas { budget, json, full, unbounded, resolve } => {
            if resolve {
                let rep = scc_cli::resolve_and_recompile(&root)?;
                eprintln!(
                    "resolved: {} upgraded, {} unresolved, {} errors",
                    rep.upgraded, rep.unresolved, rep.errors
                );
            }
            commands::cmd_atlas(&root, budget, json, full, unbounded)
        }
        Commands::Verify { warnings, json, unbounded } => commands::cmd_verify(&root, warnings, json, unbounded),
        Commands::Drift { json } => commands::cmd_drift(&root, json),
        Commands::System { member, json } => commands::cmd_system(&root, &member, json),
        Commands::Export { format } => commands::cmd_export(&root, &format),
        Commands::Query { query, limit } => commands::cmd_query(&root, &query, limit),
        Commands::Traverse { kind, name, from, steps, limit } => {
            commands::cmd_traverse(&root, kind.as_deref(), name.as_deref(), &from, &steps, limit)
        }
        Commands::Components => commands::cmd_list_components(&root),
        Commands::Diagram { format, out } => {
            commands::cmd_diagram(&root, &format, out.as_deref())
        }
        Commands::View { port, no_open } => commands::cmd_view(&root, port, no_open),
        Commands::Snap { out, max_chars, png, color } => {
            commands::cmd_snap(&root, out.as_deref(), max_chars, png.as_deref(), color)
        }
        Commands::Flows => commands::cmd_list_flows(&root),
        Commands::Cochange { min_commits } => commands::cmd_cochange(&root, min_commits),
        Commands::Checkpoint { sub } => match sub {
            CheckpointSub::Save { json } => commands::cmd_checkpoint_save(&root, json),
            CheckpointSub::Load { inject } => commands::cmd_checkpoint_load(&root, inject),
        },
        Commands::History { json } => commands::cmd_history(&root, json),
        Commands::Diff { from, to, json } => commands::cmd_diff(&root, from, to, json),
        Commands::Snapshot { sub } => match sub {
            SnapshotSub::Save { task, budget, json } => {
                commands::cmd_snapshot_save(&root, &task, budget, json)
            }
            SnapshotSub::Show { id } => commands::cmd_snapshot_show(&root, &id),
            SnapshotSub::Diff { id, json } => commands::cmd_snapshot_diff(&root, &id, json),
        },
        Commands::CheckInvariants => match commands::cmd_check_invariants(&root) {
            Ok(true) => Ok(()),
            Ok(false) => Err(scc_cli::CliError::Other(
                "graph invariants violated".into(),
            )),
            Err(e) => Err(e),
        },
        Commands::Update { version, dir, dry_run } => {
            commands::cmd_update(version.as_deref(), dir.as_deref(), dry_run)
        }
        Commands::Setup { sub } => match sub {
            None => commands::cmd_setup_detected(&root, false),
            Some(SetupSub::Claude) => commands::cmd_setup_claude(&root),
            Some(SetupSub::Codex) => scc_cli::compress::cmd_setup_codex(&root),
            Some(SetupSub::Opencode) => scc_cli::compress::cmd_setup_opencode(&root),
            Some(SetupSub::Hermes) => scc_cli::plugin_hermes::cmd_setup_hermes(&root),
            Some(SetupSub::Omp) => scc_cli::plugin_omp::cmd_setup_omp(&root),
            Some(SetupSub::Pi) => scc_cli::plugin_omp::cmd_setup_pi(&root),
            Some(SetupSub::All) => commands::cmd_setup_detected(&root, true),
        },
        Commands::Serve => commands::cmd_serve(&root),
        Commands::Mcp => commands::cmd_mcp(&root),
        Commands::Rpc { stdio } => commands::cmd_rpc(&root, stdio),
        Commands::Operations { describe } => commands::cmd_operations(describe.as_deref()),
        Commands::Plugin { sub } => match sub {
            PluginSub::List => commands::cmd_plugin_list(&root),
            PluginSub::Describe { id } => commands::cmd_plugin_describe(&root, id.as_str()),
            PluginSub::Inspect { id } => commands::cmd_plugin_describe(&root, id.as_str()),
            PluginSub::Doctor => commands::cmd_plugin_doctor(&root),
            PluginSub::Lock => commands::cmd_plugin_lock(&root),
            PluginSub::Check => commands::cmd_plugin_check(&root),
            PluginSub::Graph => commands::cmd_plugin_graph(&root),
            PluginSub::Invoke { operation, input } => commands::cmd_plugin_invoke(&root, operation.as_str(), input.as_str()),
            PluginSub::Enable { id } => commands::cmd_plugin_enable(&root, id.as_str()),
            PluginSub::Disable { id } => commands::cmd_plugin_disable(&root, id.as_str()),
        },
        Commands::Ingest { body } => commands::cmd_ingest_runtime(&root, &body),
        Commands::Embed => scc_cli::embed_cli::cmd_embed(&root),
        Commands::Important { limit, component, task, json } => {
            commands::cmd_important(&root, limit, component.as_deref(), task.as_deref(), json)
        }
        Commands::Adapters { json } => commands::cmd_adapters(&root, json),
        Commands::Doctor { json, deep, network, strict } => match commands::cmd_doctor(&root, json, deep, network, strict) {
            Ok(true) => Ok(()),
            Ok(false) => Err(scc_cli::CliError::Other("scc doctor: issues found".into())),
            Err(e) => Err(e),
        },
        Commands::Lessons { sub } => match sub.unwrap_or(LessonsSub::List { limit: 20 }) {
            LessonsSub::Add { text } => commands::cmd_lessons_add(&root, &text),
            LessonsSub::List { limit } => commands::cmd_lessons_list(&root, limit),
        },
        Commands::Beads => commands::cmd_beads(&root),
        Commands::Resolve { lsp: true } => {
            // SCC-125: capture native EXTRACTED edges before the LSP pass so
            // target changes can be recorded as resolution_conflict drift
            // findings (the upgrade preserves the evidence id, which lets the
            // diff link each EXTRACTED edge to its RESOLVED successor).
            let pre = {
                let store = scc_cli::open_store(&root)?;
                scc_cli::benchres::collect_external_edges(&store)?
            };
            scc_cli::resolve::cmd_resolve_lsp(&root)?;
            let store = scc_cli::open_store(&root)?;
            // upgrades changed the reality graph — rebuild the derived layer
            // first (recompile regenerates drift findings, so the resolution
            // conflicts are recorded after it)
            scc_cli::recompile(&store)?;
            let mut by_file: std::collections::BTreeMap<
                String,
                Vec<scc_indexer::conflicts::UpgradeRecord>,
            > = std::collections::BTreeMap::new();
            for (file, rec) in scc_cli::benchres::diff_upgrades(&store, &pre)? {
                by_file.entry(file).or_default().push(rec);
            }
            for (file, recs) in &by_file {
                let report =
                    scc_indexer::conflicts::record_resolution_conflicts(&store, file, recs)?;
                if report.conflicts > 0 {
                    println!(
                        "scc resolve: {} resolution conflict(s) in {file}",
                        report.conflicts
                    );
                }
            }
            Ok(())
        }
        Commands::Resolve { lsp: false } => Err(scc_cli::CliError::Other(
            "no resolver selected (use --lsp)".into(),
        )),
        Commands::Import { format, file } => commands::cmd_import(&root, &format, &file),
        Commands::Runtime { sub } => match sub {
            RuntimeSub::Status { json } => commands::cmd_runtime_status(&root, json),
            RuntimeSub::Reconcile { json } => commands::cmd_runtime_reconcile(&root, json),
        },
        Commands::Ci { sub } => match sub {
            CiSub::Check { max_severity } => match commands::cmd_ci_check(&root, &max_severity) {
                Ok(true) => Ok(()),
                Ok(false) => Err(scc_cli::CliError::Other(
                    "CI check failed: invariants or drift policy violated".into(),
                )),
                Err(e) => Err(e),
            },
        },
        Commands::Bench { sub } => match sub {
            BenchSub::Agent { cmd, min_files, gate, baseline_cmd } => {
                if gate {
                    let bc = baseline_cmd.ok_or(scc_cli::CliError::Other(
                        "--gate requires --baseline-cmd (the A-variant command)".into(),
                    ))?;
                    match scc_cli::benchagent::run_agent_gate(&bc, &cmd, min_files) {
                        Ok(g) => {
                            scc_cli::benchagent::print_agent_gate(&g);
                            if g.passed {
                                Ok(())
                            } else {
                                Err(scc_cli::CliError::Other(
                                    "agent-behavior gate FAILED: the atlas variant does not reduce exploration (search calls / files opened / first-correct time)".into(),
                                ))
                            }
                        }
                        Err(e) => Err(scc_cli::CliError::Other(e)),
                    }
                } else {
                    match scc_cli::benchagent::run_agent_benchmark(&cmd, min_files) {
                        Ok(summary) => {
                            scc_cli::benchagent::print_agent_summary(&summary);
                            Ok(())
                        }
                        Err(e) => Err(scc_cli::CliError::Other(e)),
                    }
                }
            },
            BenchSub::Loop {
                arms,
                k,
                repo,
                ripwire_bin,
                min_delta,
                json,
                explore,
            } => {
                let parsed: Vec<scc_cli::benchloop::LoopArm> = arms
                    .split(',')
                    .map(|s| s.trim())
                    .filter(|s| !s.is_empty())
                    .map(|s| {
                        scc_cli::benchloop::LoopArm::parse(s).ok_or_else(|| {
                            scc_cli::CliError::Other(format!("unknown loop arm {s}"))
                        })
                    })
                    .collect::<std::result::Result<Vec<_>, _>>()?;
                let opts = scc_cli::benchloop::LoopOptions {
                    k,
                    repo_filter: repo,
                    ripwire_bin,
                    explore,
                    agent_cmd: std::env::var("SCC_EXPLORE_AGENT_CMD").ok().filter(|s| !s.is_empty()),
                };
                match scc_cli::benchloop::run_agent_loop(&parsed, &opts) {
                    Ok(summary) => {
                        if json {
                            println!("{}", serde_json::to_string_pretty(&summary)?);
                        } else {
                            scc_cli::benchloop::print_loop_summary(&summary);
                        }
                        let gate_fail = {
                            let base = summary.arms.iter().find(|a| a.arm == "baseline");
                            let scc = summary.arms.iter().find(|a| a.arm == "scc");
                            match (base, scc) {
                                (Some(b), Some(s))
                                    if s.clustered_localization + min_delta
                                        < b.clustered_localization =>
                                {
                                    Some(format!(
                                        "agent-loop gate failed: SCC clustered {:.3} < baseline {:.3} + {min_delta}",
                                        s.clustered_localization, b.clustered_localization
                                    ))
                                }
                                _ => None,
                            }
                        };
                        match gate_fail {
                            Some(msg) => Err(scc_cli::CliError::Other(msg)),
                            None => Ok(()),
                        }
                    }
                    Err(e) => Err(scc_cli::CliError::Other(e)),
                }
            },
            BenchSub::Context { min_recall, min_precision } => match scc_cli::benchctx::run_context_benchmark(min_recall, min_precision)
            {
                Ok(summary) => {
                    scc_cli::benchctx::print_summary(&summary);
                    Ok(())
                }
                Err(e) => Err(scc_cli::CliError::Other(e)),
            },
            BenchSub::Retrieval {
                k,
                arms,
                repo,
                min_recall,
                json,
            } => {
                let parsed: Vec<scc_core::RankingArm> = arms
                    .split(',')
                    .map(|s| s.trim())
                    .filter(|s| !s.is_empty())
                    .map(|s| {
                        scc_core::RankingArm::parse(s).ok_or_else(|| {
                            scc_cli::CliError::Other(format!("unknown ranking arm {s}"))
                        })
                    })
                    .collect::<std::result::Result<Vec<_>, _>>()?;
                match scc_cli::benchret::run_retrieval_benchmark(
                    k,
                    &parsed,
                    min_recall,
                    repo.as_deref(),
                ) {
                    Ok(summary) => {
                        if json {
                            println!("{}", serde_json::to_string_pretty(&summary)?);
                        } else {
                            scc_cli::benchret::print_summary(&summary);
                        }
                        Ok(())
                    }
                    Err(e) => Err(scc_cli::CliError::Other(e)),
                }
            },
            BenchSub::Index { files, lines } => {
                let dir = std::env::temp_dir().join(format!("scc-bench-{}", std::process::id()));
                let _ = std::fs::remove_dir_all(&dir);
                std::fs::create_dir_all(&dir)?;
                match scc_cli::bench::bench_index(&dir, files, lines) {
                    Ok(r) => {
                        scc_cli::bench::print_report(&r);
                        let _ = std::fs::remove_dir_all(&dir);
                        Ok(())
                    }
                    Err(e) => {
                        let _ = std::fs::remove_dir_all(&dir);
                        Err(e)
                    }
                }
            }
            BenchSub::Resolution { min_agreement } => {
                match scc_cli::benchres::run_resolution_benchmark(min_agreement) {
                    Ok(summary) => {
                        scc_cli::benchres::print_summary(&summary);
                        Ok(())
                    }
                    Err(e) => Err(scc_cli::CliError::Other(e)),
                }
            }
            BenchSub::External { variant, repo, budget, cmd, workdir, json, artifact_only } => {
                let v = variant.as_str();
                if let Some(goal) = artifact_only {
                    if !NATIVE_VARIANTS.contains(&v) {
                        return Err(scc_cli::CliError::Other(format!(
                            "--artifact-only supports native variants only, got {v:?}"
                        ))
                        .into());
                    }
                    let repo = repo.ok_or_else(|| {
                        scc_cli::CliError::Other("--artifact-only requires --repo".into())
                    })?;
                    let workdir = workdir
                        .clone()
                        .unwrap_or_else(|| std::env::temp_dir().join("scc-artifact-only"));
                    std::fs::create_dir_all(&workdir)
                        .map_err(|e| scc_cli::CliError::Other(e.to_string()))?;
                    let task = scc_cli::benchagent::VariantTask {
                        id: format!("{repo}--artifact-only"),
                        repo: repo.clone(),
                        goal: goal.clone(),
                        files: vec![],
                        plan_keys: vec![],
                    };
                    // Generate against the FIXTURE repo (the same corpus
                    // the read-only benchmark uses), not the harness cwd.
                    let fixtures = scc_cli::benchctx::locate_fixtures_dir()
                        .ok_or_else(|| scc_cli::CliError::Other(
                            "cannot locate fixtures/ directory".into(),
                        ))?;
                    let root = fixtures.join(&repo);
                    let (path, tokens) = generate_variant_artifact(
                        v, &task, &root, budget, &workdir,
                    )
                    .map_err(scc_cli::CliError::Other)?;
                    let _ = json; // artifact-only always prints JSON
                    println!(
                        "{}",
                        serde_json::json!({
                            "artifact": path,
                            "tokens": tokens,
                            "budget": budget,
                            "variant": v,
                            "goal": goal,
                            "repo": repo,
                        })
                    );
                    return Ok(());
                }
                // Paid-model safety interlock: the branches below pipe prompts
                // to a paid coding agent. --artifact-only (handled above) only
                // generates local context and stays available without opt-in.
                scc_cli::benchagent::require_paid_opt_in().map_err(scc_cli::CliError::Other)?;
                if EXTERNAL_VARIANTS.contains(&v) {
                    run_external_python_delegation(v, repo.as_deref(), budget, cmd.as_deref(), json)
                } else if NATIVE_VARIANTS.contains(&v) {
                    run_external_variant(v, repo.as_deref(), budget, cmd.as_deref(), workdir.as_deref(), json)
                } else {
                    Err(scc_cli::CliError::Other(format!(
                        "unknown external variant {v:?} (expected one of: {})",
                        EXTERNAL_VARIANTS
                            .iter()
                            .chain(NATIVE_VARIANTS.iter())
                            .copied()
                            .collect::<Vec<_>>()
                            .join(", ")
                    )))
                }
            }
            BenchSub::Atlas {
                corpus,
                ground_truth,
                json,
                diagnose,
                holdout,
                blind,
                no_resolve,
                compare,
                gate_ge,
                guard_section_delta,
            } => {
                let resolve = !no_resolve;
                if let Some(pair) = compare {
                    if pair.len() != 2 {
                        return Err(scc_cli::CliError::Other(
                            "--compare requires exactly two result files: OLD NEW".into(),
                        )
                        .into());
                    }
                    let old = scc_cli::benchatlas::load_holdout_result(&pair[0])?;
                    let new = scc_cli::benchatlas::load_holdout_result(&pair[1])?;
                    let mut report = scc_cli::benchatlas::compare_runs(
                        &old,
                        &new,
                        gate_ge,
                        guard_section_delta,
                    );
                    report.old_file = pair[0].display().to_string();
                    report.new_file = pair[1].display().to_string();
                    if json {
                        println!(
                            "{}",
                            serde_json::to_string_pretty(&report)
                                .map_err(|e| scc_cli::CliError::Other(e.to_string()))?
                        );
                    } else {
                        scc_cli::benchatlas::print_compare_report(&report);
                    }
                    if report.passed() {
                        Ok(())
                    } else {
                        Err(scc_cli::CliError::Other(
                            "Wave-11 generalization gates FAILED: the semantic wave does not generalize (see --compare report)".into(),
                        ))
                    }
                } else if blind {
                    match scc_cli::benchatlas::run_atlas_blind(diagnose, resolve) {
                        Ok(comparison) => {
                            if json {
                                println!(
                                    "{}",
                                    serde_json::to_string_pretty(&comparison)
                                        .map_err(|e| scc_cli::CliError::Other(e.to_string()))?
                                );
                            } else {
                                scc_cli::benchatlas::print_blind_report(&comparison);
                            }
                            Ok(())
                        }
                        Err(e) => Err(scc_cli::CliError::Other(e)),
                    }
                } else if holdout {
                    match scc_cli::benchatlas::run_atlas_holdout(
                        corpus.as_deref(),
                        ground_truth.as_deref(),
                        diagnose,
                        resolve,
                    ) {
                        Ok(comparison) => {
                            if json {
                                println!(
                                    "{}",
                                    serde_json::to_string_pretty(&comparison)
                                        .map_err(|e| scc_cli::CliError::Other(e.to_string()))?
                                );
                            } else {
                                scc_cli::benchatlas::print_holdout_report(&comparison, diagnose);
                            }
                            Ok(())
                        }
                        Err(e) => Err(scc_cli::CliError::Other(e)),
                    }
                } else {
                    match scc_cli::benchatlas::run_atlas_bench(
                        corpus.as_deref(),
                        ground_truth.as_deref(),
                        diagnose,
                        resolve,
                    ) {
                        Ok(report) => {
                            if json {
                                println!(
                                    "{}",
                                    serde_json::to_string_pretty(&report)
                                        .map_err(|e| scc_cli::CliError::Other(e.to_string()))?
                                );
                            } else {
                                scc_cli::benchatlas::print_report(&report, diagnose);
                            }
                            Ok(())
                        }
                        Err(e) => Err(scc_cli::CliError::Other(e)),
                    }
                }
            },
        },
        Commands::StatePath => {
            println!("{}", scc_cli::state_dir(&root).display());
            Ok(())
        }
    };

    match result {
        Ok(()) => Ok(()),
        Err(e) => {
            eprintln!("error: {e}");
            std::process::exit(1);
        }
    }
}

// ---------------------------------------------------------------------------
// `scc bench external` — Wave-15 external benchmark variants (A–H).
// Native variants generate their context artifact in-process (or via the
// `scc` binary itself) and run the benchagent protocol; the aider/repomix
// variants delegate to benchmarks/external/run_context_bench.py.
// ---------------------------------------------------------------------------

const EXTERNAL_VARIANTS: [&str; 2] = ["aider-repomap", "repomix-compress"];
const NATIVE_VARIANTS: [&str; 11] = [
    "raw",
    "scc-atlas",
    "scc-surface",
    "scc-atlas-surface",
    "scc-full",
    // Wave-15 PPR ablation matrix (harness-level mode flags; see
    // scc_cli::benchagent::SurfaceAblation):
    "lexical",
    "global-ppr",
    "task-ppr",
    "ppr-mmr",
    "ppr-quotas",
    "ppr-optimizer",
];
const DEFAULT_AGENT_CMD: &str = "codex exec --json --sandbox read-only --skip-git-repo-check --ephemeral --color never -C . -";

// trace:exempt reason=internal-detail  # external-bench arm helpers (impl.scc.cli.main)
fn benchmarks_dir() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(|p| p.parent())
        .map(|p| p.join("benchmarks"))
        .unwrap_or_else(|| PathBuf::from("benchmarks"))
}

// --- ground truth: benchmarks/tasks.json + external/ground-truth.yaml -----

#[derive(Debug, Clone, serde::Deserialize)]
// trace:exempt reason=internal-detail  # external-bench ground-truth schema (impl.scc.cli.main)
struct ExternalGroundTruth {
    #[serde(default)]
    repos: BTreeMap<String, ExternalRepoTasks>,
}

#[derive(Debug, Clone, Default, serde::Deserialize)]
// trace:exempt reason=internal-detail  # external-bench ground-truth schema (impl.scc.cli.main)
struct ExternalRepoTasks {
    #[serde(default)]
    tasks: Vec<ExternalTaskDef>,
}

#[derive(Debug, Clone, serde::Deserialize)]
// trace:exempt reason=internal-detail  # external-bench ground-truth schema (impl.scc.cli.main)
struct ExternalTaskDef {
    id: String,
    goal: String,
    #[serde(default)]
    public_surfaces: Vec<String>,
    #[serde(default)]
    important_types: Vec<String>,
    #[serde(default)]
    implementation_landmarks: Vec<String>,
    #[serde(default)]
    symbols: Vec<String>,
}

/// Load the variant ground truth: the canonical `benchmarks/tasks.json`
/// corpus merged with `benchmarks/external/ground-truth.yaml` (extra repos
/// such as cli-service; Wave-14 §75 vocabulary). Optionally restricted to
/// one fixture repo. Localization ground truth = files; first-plan keys =
/// files + symbols.
// trace:exempt reason=internal-detail  # external-bench ground-truth loader (impl.scc.cli.main)
fn load_external_tasks(repo_filter: Option<&str>) -> Result<Vec<scc_cli::benchagent::VariantTask>, String> {
    let mut by_id: BTreeMap<String, scc_cli::benchagent::VariantTask> = BTreeMap::new();

    let tasks_json = benchmarks_dir().join("tasks.json");
    if tasks_json.is_file() {
        let text = std::fs::read_to_string(&tasks_json).map_err(|e| e.to_string())?;
        let corpus: scc_cli::benchctx::BenchmarkCorpus =
            serde_json::from_str(&text).map_err(|e| e.to_string())?;
        for t in &corpus.tasks {
            let mut plan_keys = t.ground_truth.files.clone();
            plan_keys.extend(t.ground_truth.symbols.iter().cloned());
            by_id.insert(
                t.id.clone(),
                scc_cli::benchagent::VariantTask {
                    id: t.id.clone(),
                    repo: t.repo.clone(),
                    goal: t.goal.clone(),
                    files: t.ground_truth.files.clone(),
                    plan_keys,
                },
            );
        }
    }

    let yaml_path = benchmarks_dir().join("external").join("ground-truth.yaml");
    if yaml_path.is_file() {
        let text = std::fs::read_to_string(&yaml_path).map_err(|e| e.to_string())?;
        let gt: ExternalGroundTruth = serde_yaml::from_str(&text).map_err(|e| e.to_string())?;
        for (repo, spec) in gt.repos {
            for t in spec.tasks {
                let mut plan_keys = t.implementation_landmarks.clone();
                plan_keys.extend(t.public_surfaces.iter().cloned());
                plan_keys.extend(t.important_types.iter().cloned());
                plan_keys.extend(t.symbols.iter().cloned());
                by_id.insert(
                    t.id.clone(),
                    scc_cli::benchagent::VariantTask {
                        id: t.id.clone(),
                        repo: repo.clone(),
                        goal: t.goal.clone(),
                        files: t.implementation_landmarks.clone(),
                        plan_keys,
                    },
                );
            }
        }
    }

    let mut tasks: Vec<scc_cli::benchagent::VariantTask> = by_id.into_values().collect();
    if let Some(r) = repo_filter {
        tasks.retain(|t| t.repo == r);
    }
    tasks.sort_by(|a, b| a.repo.cmp(&b.repo).then(a.id.cmp(&b.id)));
    Ok(tasks)
}

// --- artifact generation ----------------------------------------------------

/// Run the `scc` binary itself (the current executable) and capture stdout.
/// The variant artifacts are generated through the exact production CLI so
/// benchmark output never diverges from what an agent would receive.
// trace:exempt reason=internal-detail  # external-bench artifact generator (impl.scc.cli.main)
fn run_scc_capture(root: &Path, args: &[&str]) -> Result<String, String> {
    let exe = std::env::current_exe().map_err(|e| format!("current exe: {e}"))?;
    let out = std::process::Command::new(&exe)
        .args(args)
        .current_dir(root)
        .output()
        .map_err(|e| format!("spawn {}: {e}", exe.display()))?;
    if !out.status.success() {
        return Err(format!(
            "`scc {}` exited {}: {}",
            args.join(" "),
            out.status,
            String::from_utf8_lossy(&out.stderr).trim()
        ));
    }
    Ok(String::from_utf8_lossy(&out.stdout).to_string())
}

/// Generate the variant's context artifact for one task (after the runner
/// has copied + indexed the repo). Writes `<artifacts_dir>/<repo>.txt` and
/// returns its path and token estimate.
///
/// GROUND-TRUTH DISCIPLINE: `task.files` is the localization ground truth —
/// it enters SCORING only (the benchagent protocol compares tool events
/// against it). Context construction never reads it. The structural
/// section of `scc-full` selects its files from the task-personalized
/// surface (`scc context structural --task` when the binary supports it,
/// else `scc surface --task` + the rendered entries); the PPR ablation
/// modes rank the surface in-process.
// trace:exempt reason=internal-detail  # external-bench artifact generator (impl.scc.cli.main)
fn generate_variant_artifact(
    variant: &str,
    task: &scc_cli::benchagent::VariantTask,
    root: &Path,
    budget: usize,
    artifacts_dir: &Path,
) -> Result<(PathBuf, usize), String> {
    std::fs::create_dir_all(artifacts_dir).map_err(|e| e.to_string())?;
    let artifact_path = artifacts_dir.join(format!("{}.txt", task.repo));
    let budget_s = budget.to_string();

    let text: String = match variant {
        "raw" => String::new(),
        "scc-atlas" => {
            // Atlas-only variant: the FULL requested budget goes to the
            // Atlas (no 13:7 startup split handicap).
            run_scc_capture(root, &["atlas", "--budget", &budget_s])?
        }
        "scc-surface" => run_scc_capture(root, &["surface", "--budget", &budget_s])?,
        "scc-atlas-surface" => run_scc_capture(root, &["context", "startup", "--budget", &budget_s])?,
        "scc-full" => {
            // FINAL-artifact budget enforcement: the concatenated
            // startup + task-delta + structural context must fit `budget`
            // (enforced on the concatenated artifact, not per piece).
            // Pieces are sized so the total never exceeds N: startup gets
            // N/2, the task delta N/4, the structural section gets the
            // remainder of what the first two actually consumed.
            let startup_budget = (budget / 2).max(1);
            let startup = run_scc_capture(
                root,
                &["context", "startup", "--budget", &startup_budget.to_string()],
            )?;
            let est_s = estimate_tokens(&startup);
            let remaining = budget.saturating_sub(est_s);
            let task_budget = (budget / 4).min(remaining / 2).max(1);
            let task_pack = run_scc_capture(
                root,
                &["context", "task", &task.goal, "--budget", &task_budget.to_string()],
            )?;
            let est_t = estimate_tokens(&task_pack);
            let mut structural_budget = budget.saturating_sub(est_s + est_t);
            let mut structural = scc_cli::benchagent::structural_source_for_goal(
                root,
                &task.goal,
                structural_budget,
            )?;
            let mut text = format!("{startup}\n\n{task_pack}\n\n# STRUCTURAL SOURCE\n\n{structural}");
            text = text.trim_end().to_string();
            // Hard enforcement on the concatenated artifact: shrink the
            // structural section (complete-file units) until it fits.
            while estimate_tokens(&text) > budget && structural_budget > 0 {
                structural_budget =
                    structural_budget.saturating_sub(estimate_tokens(&text) - budget + 1);
                structural = scc_cli::benchagent::structural_source_for_goal(
                    root,
                    &task.goal,
                    structural_budget,
                )?;
                text = format!("{startup}\n\n{task_pack}\n\n# STRUCTURAL SOURCE\n\n{structural}")
                    .trim_end()
                    .to_string();
            }
            text
        }
        other => {
            // Wave-15 PPR ablation matrix: harness-level mode flags (see
            // scc_cli::benchagent::SurfaceAblation).
            let mode = scc_cli::benchagent::SurfaceAblation::parse(other).ok_or_else(|| {
                format!("unsupported native variant: {other}")
            })?;
            scc_cli::benchagent::render_ablation_surface(root, mode, &task.goal, budget)?
        }
    };

    std::fs::write(&artifact_path, &text).map_err(|e| e.to_string())?;
    Ok((artifact_path, estimate_tokens(&text)))
}

/// Shell single-quote escaping for embedding the agent command inside the
/// variant command.
// trace:exempt reason=internal-detail  # external-bench shell quoting (impl.scc.cli.main)
fn sh_single_quote(s: &str) -> String {
    format!("'{}'", s.replace('\'', "'\\''"))
}

/// The benchagent variant command: the context artifact is catted into
/// $CTX, then the prompt `SCC CONTEXT: <artifact> \n TASK: <goal>` is piped
/// to the agent command on stdin ($SCC_GOAL carries the goal).
// trace:exempt reason=internal-detail  # external-bench agent command builder (impl.scc.cli.main)
fn build_variant_command(agent_cmd: &str, artifact_path: &Path) -> String {
    let art = sh_single_quote(&artifact_path.display().to_string());
    let agent = sh_single_quote(agent_cmd);
    format!(
        "CTX=$(cat {art} 2>/dev/null || true); printf 'SCC CONTEXT:\\n%s\\n\\nTASK: %s\\n' \"$CTX\" \"$SCC_GOAL\" | sh -c {agent}"
    )
}

/// Run one native variant through the benchagent runner and print the §72
/// metric row (variant, success rate, mean exploration, first-plan
/// accuracy, context tokens).
// trace:exempt reason=internal-detail  # external-bench native arm (impl.scc.cli.main)
fn run_external_variant(
    variant: &str,
    repo: Option<&str>,
    budget: usize,
    agent_cmd: Option<&str>,
    workdir: Option<&Path>,
    json: bool,
) -> Result<(), scc_cli::CliError> {
    let agent = agent_cmd.unwrap_or(DEFAULT_AGENT_CMD);
    let tasks = load_external_tasks(repo).map_err(scc_cli::CliError::Other)?;
    if tasks.is_empty() {
        return Err(scc_cli::CliError::Other(format!(
            "no ground-truth tasks for repo {}",
            repo.unwrap_or("(all)")
        )));
    }
    let workdir = workdir.map(Path::to_path_buf).unwrap_or_else(|| {
        std::env::temp_dir().join(format!("scc-external-{}", std::process::id()))
    });
    let artifacts_dir = workdir.join("artifacts");
    std::fs::create_dir_all(&artifacts_dir).map_err(|e| scc_cli::CliError::Other(e.to_string()))?;

    // context-token mean over tasks (scc-full artifacts are goal-dependent)
    let mut tokens_seen: Vec<usize> = Vec::new();
    let summary = scc_cli::benchagent::run_variant_tasks(variant, &tasks, |task, root| {
        let (path, tokens) = generate_variant_artifact(variant, task, root, budget, &artifacts_dir)?;
        tokens_seen.push(tokens);
        Ok(build_variant_command(agent, &path))
    }, 0.0)
    .map_err(scc_cli::CliError::Other)?;

    let mean_tokens = if tokens_seen.is_empty() {
        0
    } else {
        tokens_seen.iter().sum::<usize>() / tokens_seen.len()
    };
    let n = summary.tasks.max(1) as f64;
    let row = serde_json::json!({
        "variant": variant,
        "budget": budget,
        "repo": repo.unwrap_or("all"),
        "tasks": summary.tasks,
        "success_rate": summary.passed as f64 / n,
        "mean_exploration": summary.mean_files_opened
            + summary.mean_search_tool_calls
            + summary.mean_graph_tool_calls,
        "first_plan_accuracy": summary.mean_first_plan_correct,
        "context_tokens": mean_tokens,
        "mean_files_opened": summary.mean_files_opened,
        "mean_search_tool_calls": summary.mean_search_tool_calls,
        "mean_graph_tool_calls": summary.mean_graph_tool_calls,
        "mean_files_opened_before_first_correct": summary.mean_wrong_first_locations,
    });

    // persist the row + full summary for later aggregation
    let results_dir = workdir.join("results");
    std::fs::create_dir_all(&results_dir).map_err(|e| scc_cli::CliError::Other(e.to_string()))?;
    let result_path = results_dir.join(format!(
        "{variant}_{}_{budget}.json",
        repo.unwrap_or("all")
    ));
    let result_json = serde_json::json!({ "row": row, "summary": summary });
    let _ = std::fs::write(
        &result_path,
        serde_json::to_string_pretty(&result_json)
            .map_err(|e| scc_cli::CliError::Other(e.to_string()))?,
    );

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&row).map_err(|e| scc_cli::CliError::Other(e.to_string()))?
        );
    } else {
        println!(
            "{variant:<18} success {:>6.3}   mean exploration {:>7.2}   first-plan accuracy {:>6.3}   context tokens {:>6}",
            summary.passed as f64 / n,
            summary.mean_files_opened + summary.mean_search_tool_calls + summary.mean_graph_tool_calls,
            summary.mean_first_plan_correct,
            mean_tokens
        );
        scc_cli::benchagent::print_agent_summary(&summary);
    }
    Ok(())
}

/// Delegate the external-tool variants (aider-repomap, repomix-compress) to
/// benchmarks/external/run_context_bench.py, which owns the pinned tools.
/// Exit 2 from the harness = SKIPPED-UNINSTALLED: the variant row is
/// reported with that status and the arm succeeds (the caller decides
/// whether missing tools are acceptable).
// trace:exempt reason=internal-detail  # external-bench delegation arm (impl.scc.cli.main)
fn run_external_python_delegation(
    variant: &str,
    repo: Option<&str>,
    budget: usize,
    agent_cmd: Option<&str>,
    json: bool,
) -> Result<(), scc_cli::CliError> {
    let script = benchmarks_dir().join("external").join("run_context_bench.py");
    if !script.is_file() {
        return Err(scc_cli::CliError::Other(format!(
            "missing harness: {}",
            script.display()
        )));
    }
    let mut cmd = std::process::Command::new("python3");
    cmd.arg(&script)
        .arg("--variant")
        .arg(variant)
        .arg("--budget")
        .arg(budget.to_string())
        .arg("--single");
    if let Some(r) = repo {
        cmd.arg("--repo").arg(r);
    }
    if let Some(a) = agent_cmd {
        cmd.arg("--agent-cmd").arg(a);
    }
    if json {
        cmd.arg("--json");
    }
    let out = cmd
        .output()
        .map_err(|e| scc_cli::CliError::Other(format!("spawn python harness: {e}")))?;
    let stdout = String::from_utf8_lossy(&out.stdout);
    if out.status.code() == Some(2) {
        // SKIPPED-UNINSTALLED: report the variant row with that status
        if json {
            print!("{stdout}");
        } else {
            println!("{variant}  SKIPPED-UNINSTALLED");
            eprintln!("{stdout}");
        }
        return Ok(());
    }
    if out.status.code() == Some(3) {
        // PIN-MISMATCH: the installed tool does not match the pinned commit
        if json {
            print!("{stdout}");
        } else {
            println!("{variant}  PIN-MISMATCH");
            eprintln!("{stdout}");
        }
        return Ok(());
    }
    if out.status.code() == Some(4) {
        // PIN-UNVERIFIED: the installed tool's commit cannot be proven to
        // match the pin — never treated as a passing pin, excluded from
        // the official showdown.
        if json {
            print!("{stdout}");
        } else {
            println!("{variant}  PIN-UNVERIFIED");
            eprintln!("{stdout}");
        }
        return Ok(());
    }
    if !out.status.success() {
        return Err(scc_cli::CliError::Other(format!(
            "run_context_bench.py exited {}: {}",
            out.status,
            String::from_utf8_lossy(&out.stderr).trim()
        )));
    }
    print!("{stdout}");
    Ok(())
}