supercode-harness 0.4.15

The optional native Supercode agent and tool harness
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
//! Behavior-parity ledger: the product's own gap count, for the `cc-parity`
//! and `cx-parity` presets and for the orchestration harnesses.
//!
//! Two embedded ledgers, one report shape:
//!
//! * `parity/ledger.json` — one row per capability in
//!   `docs/composable-harness/CAPABILITY-CATALOG.md` (263 rows, ids derived
//!   from the capability name), columns `cc` / `cx`.
//! * `parity/orchestration.json` — one row per (orchestration concept × verb
//!   group) from `docs/composable-harness/inventory/orchestration.md`,
//!   columns `hermes` / `openclaw`.
//!
//! Each row records which harness has the capability and supercode's audited
//! status, with EVIDENCE that the test suite resolves mechanically against
//! the real preset resolver, module registry, tool registry, runtime
//! backends, the committed harness `--help` fixtures and the source tree —
//! an "implemented" claim that cites nothing checkable does not parse as
//! implemented. The ledger is the denominator for the parity program:
//! `supercode harness parity --preset cc-parity|cx-parity|hermes|openclaw`
//! prints the headline count, and only zero is done.
//!
//! The embedded JSON is the single source; the catalog's "supercode today"
//! column is a snapshot of the survey and is NOT consulted at runtime.

use std::collections::BTreeMap;
use std::path::Path;

use serde::{Deserialize, Serialize};

use crate::configfile::{resolve, ResolveOptions, Resolved};
use crate::presets;
use crate::runtime::{RuntimeBackend, RuntimeCapabilities};
use crate::tools::ToolRegistry;

/// Raw ledger rows, embedded at build time.
pub const LEDGER_JSON: &str = include_str!("parity/ledger.json");

/// Raw orchestration ledger rows, embedded at build time.
pub const ORCHESTRATION_JSON: &str = include_str!("parity/orchestration.json");

/// Presets the ledger reports on, keyed by the catalog column they mirror.
pub const PARITY_PRESETS: &[(&str, &str)] = &[("cc", "cc-parity"), ("cx", "cx-parity")];

/// Orchestration harnesses the orchestration ledger reports on. The preset
/// name IS the column name (there is no `*-parity` config preset behind
/// these: supercode does not emulate a gateway, it reports on one).
pub const ORCHESTRATION_PRESETS: &[&str] = &["hermes", "openclaw"];

/// ORC-7: supercode's OWN orchestrator, graded on the same 17 rows through
/// its own column.
///
/// It is not one of [`ORCHESTRATION_PRESETS`]: those are external harnesses
/// whose columns cite a verb their PINNED CLI advertises, checked against a
/// committed `--help` fixture. The orchestrator has no such CLI — it is a
/// package in this workspace — so its column is graded like a supercode
/// status, from `store` and `code` citations that resolve here.
///
/// Its denominator is the WHOLE ledger: every concept is one the
/// orchestrator's own model either has or deliberately does not
/// (`docs/ORCHESTRATOR-IR.md` §2), so a row it lacks is reported as
/// `not_applicable` rather than dropped from the count.
pub const ORCHESTRATOR_PRESET: &str = "orchestrator";

/// `hermes --help` capture for the pinned version (see the fixture header).
const HERMES_HELP_FIXTURE: &str = include_str!("parity/fixtures/hermes-help.txt");

/// `openclaw --help` capture for the pinned version (see the fixture header).
const OPENCLAW_HELP_FIXTURE: &str = include_str!("parity/fixtures/openclaw-help.txt");

/// Workspace directories searched for a loader that opens a harness store.
const STORE_SEARCH_ROOTS: &[&str] = &["crates/interchange/src", "crates/harness/src"];

/// Call forms that count as "a loader opens this": a SQL read, a file open,
/// or a path join. A bare mention (comment, doc-comment, error string) does
/// not resolve a [`Evidence::Store`] citation.
const STORE_OPEN_CALLS: &[&str] = &["SELECT", "open(", "open_with_flags(", ".join("];

/// Every preset name `report` accepts, in product order.
pub fn preset_names() -> Vec<&'static str> {
    PARITY_PRESETS
        .iter()
        .map(|(_, preset)| *preset)
        .chain(ORCHESTRATION_PRESETS.iter().copied())
        .chain(std::iter::once(ORCHESTRATOR_PRESET))
        .collect()
}

/// The committed `--help` fixture for a pinned orchestration harness CLI.
pub fn help_fixture(harness: &str) -> Option<&'static str> {
    match harness {
        "hermes" => Some(HERMES_HELP_FIXTURE),
        "openclaw" => Some(OPENCLAW_HELP_FIXTURE),
        _ => None,
    }
}

/// Whether a harness has a capability (the catalog's per-harness column).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Has {
    /// `✓` — has it as described.
    Yes,
    /// `✓*` — has it with a footnoted variant.
    Variant,
    /// `ext` — only through an extension, plugin, or example.
    Extension,
    /// `—` — lacks it.
    No,
}

impl Has {
    /// True for every column value except `—`.
    pub fn present(self) -> bool {
        !matches!(self, Has::No)
    }
}

/// supercode's audited status for a row.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Status {
    /// Behaves as the catalog row describes, under the applicable preset(s).
    Implemented,
    /// Some of the row's semantics exist; the note names what is missing.
    Partial,
    /// Nothing exists yet.
    Absent,
    /// Cannot be reproduced by design (the note cites the design-doc ledger).
    Irreducible,
    /// Neither Claude Code nor Codex has it; outside the parity program.
    NotApplicable,
    /// Seeded from the catalog and not yet audited against current code.
    Unaudited,
}

impl Status {
    /// Whether the row counts against the preset's gap headline.
    pub fn is_gap(self) -> bool {
        matches!(
            self,
            Status::Partial | Status::Absent | Status::Irreducible | Status::Unaudited
        )
    }

    /// Whether the row must cite at least one checkable evidence item.
    pub fn requires_evidence(self) -> bool {
        matches!(self, Status::Implemented | Status::Partial)
    }

    fn label(self) -> &'static str {
        match self {
            Status::Implemented => "implemented",
            Status::Partial => "partial",
            Status::Absent => "absent",
            Status::Irreducible => "irreducible",
            Status::NotApplicable => "not_applicable",
            Status::Unaudited => "unaudited",
        }
    }
}

/// Adoption cost class for an absent row (the catalog's §4 split).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Cost {
    /// Config knob, small tool, or prompt-assembly change; no new subsystem.
    Trivial,
    /// New subsystem or cross-cutting contract.
    Architectural,
}

/// A mechanically checkable citation. Every variant is resolved by
/// [`check_evidence`] against the applicable preset(s) or the source tree.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Evidence {
    /// A tool registered under the applicable preset's resolved config.
    Tool {
        /// Registered tool name (e.g. `read_file`).
        name: String,
    },
    /// A capability module enabled in the applicable preset(s).
    Module {
        /// Capability module name (a `MODULE_NAMES` entry).
        name: String,
    },
    /// A dotted key that the applicable preset TOML sets explicitly.
    Config {
        /// Dotted TOML key path (e.g. `core.tools.edit_file.require_read_before_edit`).
        key: String,
    },
    /// A live-runtime capability flag on the harness's own backend.
    Runtime {
        /// `RuntimeCapabilities` flag name (e.g. `steer`).
        capability: String,
    },
    /// A source file (workspace-relative) that must exist and, when
    /// `symbol` is given, contain that text. The weakest kind; for loop
    /// mechanics that no config key or tool name expresses.
    Code {
        /// Workspace-relative source path.
        path: String,
        /// Text the file must contain.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        symbol: Option<String>,
    },
    /// A subcommand the PINNED harness CLI advertises. Resolved against the
    /// committed capture `parity/fixtures/<harness>-help.txt`: the verb's
    /// leaf must appear as a subcommand entry inside the
    /// `$ <harness> <parents> --help` section. Backs a harness column, never
    /// a supercode status — that a harness has a verb says nothing about
    /// whether supercode calls it.
    CliVerb {
        /// One of [`ORCHESTRATION_PRESETS`].
        harness: String,
        /// Space-separated verb path (`cron list`, `agents bindings`, `acp`).
        verb: String,
    },
    /// A harness store (file path, table, or column) that a loader in THIS
    /// workspace actually opens. Resolved by a symbol search over
    /// [`STORE_SEARCH_ROOTS`]: every non-placeholder segment of `path` must
    /// appear in a [`STORE_OPEN_CALLS`] form on a non-comment line.
    /// `<...>` segments are placeholders and are skipped.
    Store {
        /// The store's owner, one of [`ORCHESTRATION_PRESETS`].
        harness: String,
        /// `/`-separated store path, e.g. `state.db/sessions/session_key`.
        path: String,
    },
}

/// One catalog row with its audited status.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Row {
    /// Stable slug derived from the capability name.
    pub id: String,
    /// Catalog domain number (1..=11).
    pub domain: u8,
    /// Catalog domain title.
    pub domain_name: String,
    /// Capability name as the catalog states it.
    pub capability: String,
    /// The catalog's one-line semantics.
    pub semantics: String,
    /// Claude Code column.
    pub cc: Has,
    /// Codex column.
    pub cx: Has,
    /// Claude Code cell text (variant footnotes live here).
    pub cc_detail: String,
    /// Codex cell text.
    pub cx_detail: String,
    /// The catalog's own "supercode today" cell at survey time (prior claim,
    /// never consulted for status).
    pub catalog_supercode_today: String,
    /// Catalog provenance citations.
    pub provenance: String,
    /// Audited status.
    pub status: Status,
    /// Checkable citations backing `status`.
    #[serde(default)]
    pub evidence: Vec<Evidence>,
    /// What is missing (partial), why (irreducible), or where (absent).
    #[serde(default)]
    pub note: String,
    /// Adoption cost class; required when `status` is absent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cost: Option<Cost>,
}

impl Row {
    /// Whether the harness behind `column` (`"cc"` / `"cx"`) has this row.
    pub fn has(&self, column: &str) -> bool {
        match column {
            "cc" => self.cc.present(),
            "cx" => self.cx.present(),
            _ => false,
        }
    }

    /// Preset names this row must hold under.
    pub fn applicable_presets(&self) -> Vec<&'static str> {
        PARITY_PRESETS
            .iter()
            .filter(|(column, _)| self.has(column))
            .map(|(_, preset)| *preset)
            .collect()
    }
}

/// Parse the embedded ledger.
pub fn ledger() -> Vec<Row> {
    serde_json::from_str(LEDGER_JSON).expect("embedded parity ledger is valid JSON")
}

/// Catalog domain the orchestration rows belong to (Domain 11,
/// "Orchestration & automation"). The orchestration ledger is the same
/// domain seen through the two orchestration-level harnesses' own doors.
pub const ORCHESTRATION_DOMAIN: u8 = 11;

/// One (orchestration concept × verb group) row with its audited status.
///
/// Same shape as [`Row`] with the harness columns swapped: `hermes` /
/// `openclaw` instead of `cc` / `cx`, and a per-column evidence list, since
/// what a harness advertises is checkable independently of what supercode
/// does with it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OrchestrationRow {
    /// Stable slug (`orch-` + concept + verb group).
    pub id: String,
    /// One of `crate::support::ORCHESTRATION_CONCEPTS`.
    pub concept: String,
    /// The verb group this row covers (`list/get`, `create/update/...`).
    pub verbs: String,
    /// Row name as the inventory states it (`Scheduled job: list/get`).
    pub capability: String,
    /// The inventory's one-line semantics.
    pub semantics: String,
    /// Hermes column.
    pub hermes: Has,
    /// OpenClaw column.
    pub openclaw: Has,
    /// The orchestrator's column: whether ITS model has this concept
    /// (ORC-7). `no` means the concept is deliberately outside
    /// `docs/ORCHESTRATOR-IR.md` §2.
    pub orchestrator: Has,
    /// Hermes cell text (variant footnotes live here).
    pub hermes_detail: String,
    /// OpenClaw cell text.
    pub openclaw_detail: String,
    /// The orchestrator cell text.
    pub orchestrator_detail: String,
    /// Citations backing the Hermes column (`cli_verb` against the pin).
    #[serde(default)]
    pub hermes_evidence: Vec<Evidence>,
    /// Citations backing the OpenClaw column.
    #[serde(default)]
    pub openclaw_evidence: Vec<Evidence>,
    /// Audited status of supercode's support for the ORCHESTRATOR on this
    /// row, which is a different question from [`OrchestrationRow::status`]
    /// (that one grades the Hermes and OpenClaw readers).
    pub orchestrator_status: Status,
    /// Citations backing `orchestrator_status` (`store` / `code`, resolved in
    /// this workspace exactly like a supercode status).
    #[serde(default)]
    pub orchestrator_evidence: Vec<Evidence>,
    /// What is missing (partial), why (not_applicable), or where (absent) for
    /// the orchestrator.
    pub orchestrator_note: String,
    /// Adoption cost class for an absent orchestrator row.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub orchestrator_cost: Option<Cost>,
    /// Inventory provenance.
    pub provenance: String,
    /// Audited status of SUPERCODE, not of the harnesses.
    pub status: Status,
    /// Checkable citations backing `status` (`store` / `code`).
    #[serde(default)]
    pub evidence: Vec<Evidence>,
    /// What is missing (partial), why (irreducible), or where (absent).
    #[serde(default)]
    pub note: String,
    /// Adoption cost class; required when `status` is absent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cost: Option<Cost>,
}

impl OrchestrationRow {
    /// Whether `harness` (`"hermes"` / `"openclaw"`) has this row.
    pub fn has(&self, harness: &str) -> bool {
        self.column(harness)
            .is_some_and(|(has, _, _)| has.present())
    }

    /// The `(has, detail, evidence)` triple for one harness column.
    pub fn column(&self, harness: &str) -> Option<(Has, &str, &[Evidence])> {
        match harness {
            "hermes" => Some((
                self.hermes,
                self.hermes_detail.as_str(),
                self.hermes_evidence.as_slice(),
            )),
            "openclaw" => Some((
                self.openclaw,
                self.openclaw_detail.as_str(),
                self.openclaw_evidence.as_slice(),
            )),
            _ => None,
        }
    }
}

/// Parse the embedded orchestration ledger.
pub fn orchestration_ledger() -> Vec<OrchestrationRow> {
    serde_json::from_str(ORCHESTRATION_JSON).expect("embedded orchestration ledger is valid JSON")
}

/// Per-status counts plus the headline gap number for one preset.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PresetSummary {
    /// Preset name.
    pub preset: String,
    /// Catalog column the preset mirrors (`cc` / `cx`).
    pub harness_column: String,
    /// Rows the harness has (the denominator).
    pub rows: usize,
    /// Row count per status label.
    pub counts: BTreeMap<String, usize>,
    /// The headline: rows that are not implemented.
    pub gaps: usize,
}

/// A gap row as printed: enough to act on without opening the ledger.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GapRow {
    /// Row id.
    pub id: String,
    /// Catalog domain.
    pub domain: u8,
    /// Capability name.
    pub capability: String,
    /// Audited status (never implemented here).
    pub status: Status,
    /// Adoption cost class when known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cost: Option<Cost>,
    /// Row note.
    pub note: String,
}

/// The parity report for one preset.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PresetReport {
    /// Headline counts.
    pub summary: PresetSummary,
    /// Every gap row, in catalog order.
    pub gaps: Vec<GapRow>,
}

/// Build the report for `preset`: a capability preset (`cc-parity` /
/// `cx-parity`) or an orchestration harness (`hermes` / `openclaw`).
pub fn report(preset: &str) -> Option<PresetReport> {
    if let Some((column, _)) = PARITY_PRESETS.iter().find(|(_, p)| *p == preset) {
        return Some(catalog_report(preset, column));
    }
    if preset == ORCHESTRATOR_PRESET {
        return Some(orchestrator_report());
    }
    if ORCHESTRATION_PRESETS.contains(&preset) {
        return Some(orchestration_report(preset));
    }
    None
}

fn catalog_report(preset: &str, column: &str) -> PresetReport {
    let rows: Vec<Row> = ledger().into_iter().filter(|r| r.has(column)).collect();
    let mut counts: BTreeMap<String, usize> = BTreeMap::new();
    let mut gaps = Vec::new();
    for row in &rows {
        *counts.entry(row.status.label().to_string()).or_default() += 1;
        if row.status.is_gap() {
            gaps.push(GapRow {
                id: row.id.clone(),
                domain: row.domain,
                capability: row.capability.clone(),
                status: row.status,
                cost: row.cost,
                note: row.note.clone(),
            });
        }
    }
    PresetReport {
        summary: PresetSummary {
            preset: preset.to_string(),
            harness_column: column.to_string(),
            rows: rows.len(),
            counts,
            gaps: gaps.len(),
        },
        gaps,
    }
}

fn orchestration_report(harness: &str) -> PresetReport {
    let rows: Vec<OrchestrationRow> = orchestration_ledger()
        .into_iter()
        .filter(|r| r.has(harness))
        .collect();
    let mut counts: BTreeMap<String, usize> = BTreeMap::new();
    let mut gaps = Vec::new();
    for row in &rows {
        *counts.entry(row.status.label().to_string()).or_default() += 1;
        if row.status.is_gap() {
            gaps.push(GapRow {
                id: row.id.clone(),
                domain: ORCHESTRATION_DOMAIN,
                capability: row.capability.clone(),
                status: row.status,
                cost: row.cost,
                note: row.note.clone(),
            });
        }
    }
    PresetReport {
        summary: PresetSummary {
            preset: harness.to_string(),
            harness_column: harness.to_string(),
            rows: rows.len(),
            counts,
            gaps: gaps.len(),
        },
        gaps,
    }
}

/// ORC-7: the same 17 rows, graded through the orchestrator's own column.
///
/// Every row counts: a concept the orchestrator's model does not have is
/// `not_applicable` (not a gap, but still in the denominator), so the
/// headline can never be improved by dropping a row.
fn orchestrator_report() -> PresetReport {
    let rows = orchestration_ledger();
    let mut counts: BTreeMap<String, usize> = BTreeMap::new();
    let mut gaps = Vec::new();
    for row in &rows {
        *counts
            .entry(row.orchestrator_status.label().to_string())
            .or_default() += 1;
        if row.orchestrator_status.is_gap() {
            gaps.push(GapRow {
                id: row.id.clone(),
                domain: ORCHESTRATION_DOMAIN,
                capability: row.capability.clone(),
                status: row.orchestrator_status,
                cost: row.orchestrator_cost,
                note: row.orchestrator_note.clone(),
            });
        }
    }
    PresetReport {
        summary: PresetSummary {
            preset: ORCHESTRATOR_PRESET.to_string(),
            harness_column: ORCHESTRATOR_PRESET.to_string(),
            rows: rows.len(),
            counts,
            gaps: gaps.len(),
        },
        gaps,
    }
}

/// Render the headline plus the gap list, grouped by domain.
pub fn render(report: &PresetReport) -> String {
    let s = &report.summary;
    let mut out = format!("{}: {} rows · {} gaps", s.preset, s.rows, s.gaps);
    for status in [
        Status::Implemented,
        Status::Partial,
        Status::Absent,
        Status::Irreducible,
        // ORC-7: a preset whose denominator is the WHOLE ledger reports rows
        // its subject deliberately lacks; leaving them out of the headline
        // would make the counts fail to add up to the row count.
        Status::NotApplicable,
        Status::Unaudited,
    ] {
        if let Some(n) = s.counts.get(status.label()) {
            out.push_str(&format!(" · {n} {}", status.label()));
        }
    }
    out.push('\n');
    let mut domain = 0u8;
    for gap in &report.gaps {
        if gap.domain != domain {
            domain = gap.domain;
            out.push_str(&format!("\nDomain {domain}\n"));
        }
        let cost = match gap.cost {
            Some(Cost::Trivial) => " [trivial]",
            Some(Cost::Architectural) => " [architectural]",
            None => "",
        };
        out.push_str(&format!(
            "  {:<12}{cost} {} ({})",
            gap.status.label(),
            gap.capability,
            gap.id
        ));
        if !gap.note.is_empty() {
            out.push_str(&format!("{}", gap.note));
        }
        out.push('\n');
    }
    out
}

/// Resolve a built-in preset through the real resolver (strict mode).
pub fn resolve_preset(preset: &str) -> Result<Resolved, String> {
    let toml = presets::lookup(preset).ok_or_else(|| format!("unknown preset `{preset}`"))?;
    resolve(toml, None, &ResolveOptions { strict: true }).map_err(|e| e.to_string())
}

fn runtime_flag(capabilities: &RuntimeCapabilities, flag: &str) -> Option<bool> {
    Some(match flag {
        "start_session" => capabilities.start_session,
        "resume_session" => capabilities.resume_session,
        "attach_existing_process" => capabilities.attach_existing_process,
        "send_input" => capabilities.send_input,
        "stream_events" => capabilities.stream_events,
        "interrupt" => capabilities.interrupt,
        "steer" => capabilities.steer,
        "respond_to_requests" => capabilities.respond_to_requests,
        _ => return None,
    })
}

fn backend_capabilities(column: &str) -> RuntimeCapabilities {
    match column {
        "cc" => crate::runtime::ClaudeCodeRuntimeBackend::default().capabilities(),
        "cx" => crate::runtime::CodexRuntimeBackend::default().capabilities(),
        other => panic!("no runtime backend for column `{other}`"),
    }
}

/// Resolve a [`Evidence::CliVerb`] against the committed help fixture.
///
/// A verb is advertised when its LEAF appears as a subcommand entry inside
/// the section headed `$ <harness> <parents> --help`. Subcommand entries are
/// shallow-indented lines whose first token names the command; both help
/// renderers' alias forms are accepted (`create (add)` from argparse,
/// `add|create` from Commander).
fn check_cli_verb(harness: &str, verb: &str) -> Result<(), String> {
    let fixture = help_fixture(harness)
        .ok_or_else(|| format!("no committed help fixture for harness `{harness}`"))?;
    let mut parts: Vec<&str> = verb.split_whitespace().collect();
    let leaf = parts.pop().ok_or_else(|| "empty cli verb".to_string())?;
    let header = if parts.is_empty() {
        format!("$ {harness} --help")
    } else {
        format!("$ {harness} {} --help", parts.join(" "))
    };
    let mut in_section = false;
    let mut saw_section = false;
    for line in fixture.lines() {
        if line.starts_with("$ ") {
            in_section = line.trim() == header;
            saw_section |= in_section;
            continue;
        }
        if !in_section || line.starts_with('#') {
            continue;
        }
        // Subcommand entries sit 2–6 columns in; description continuations
        // and usage wrapping sit far deeper, so they cannot false-positive.
        let indent = line.len() - line.trim_start().len();
        if !(2..=6).contains(&indent) {
            continue;
        }
        let Some(token) = line.split_whitespace().next() else {
            continue;
        };
        if token.starts_with('-') {
            continue;
        }
        if token.split('|').any(|alias| alias == leaf) {
            return Ok(());
        }
    }
    if !saw_section {
        return Err(format!(
            "`{header}` is not a section of the {harness} help fixture"
        ));
    }
    Err(format!(
        "`{harness} {verb}` is not advertised under `{header}`"
    ))
}

fn push_rust_sources(dir: &Path, out: &mut Vec<std::path::PathBuf>) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() {
            push_rust_sources(&path, out);
        } else if path.extension().is_some_and(|ext| ext == "rs") {
            out.push(path);
        }
    }
}

/// True when `segment` appears inside an opening call (SQL read, file open,
/// path join) on a non-comment line under [`STORE_SEARCH_ROOTS`]. The call
/// may be split across lines (multi-line SQL), so the three preceding lines
/// count as the same call context.
fn store_segment_is_opened(segment: &str, workspace_root: &Path) -> bool {
    let mut files = Vec::new();
    for root in STORE_SEARCH_ROOTS {
        push_rust_sources(&workspace_root.join(root), &mut files);
    }
    for file in files {
        let Ok(text) = std::fs::read_to_string(&file) else {
            continue;
        };
        let lines: Vec<&str> = text.lines().collect();
        for (index, line) in lines.iter().enumerate() {
            if !line.contains(segment) || line.trim_start().starts_with("//") {
                continue;
            }
            let start = index.saturating_sub(3);
            let context = lines[start..=index].join("\n");
            if STORE_OPEN_CALLS.iter().any(|call| context.contains(call)) {
                return true;
            }
        }
    }
    false
}

/// Resolve a [`Evidence::Store`]: every non-placeholder path segment must be
/// opened by a loader in this workspace.
fn check_store(harness: &str, path: &str, workspace_root: &Path) -> Result<(), String> {
    if !ORCHESTRATION_PRESETS.contains(&harness) && harness != ORCHESTRATOR_PRESET {
        return Err(format!(
            "`{harness}` is not an orchestration harness or the orchestrator"
        ));
    }
    let mut checked = 0usize;
    for segment in path.split('/') {
        if segment.is_empty() || (segment.starts_with('<') && segment.ends_with('>')) {
            continue;
        }
        if segment.len() < 3 {
            return Err(format!(
                "store segment `{segment}` is too short to identify a store"
            ));
        }
        if !store_segment_is_opened(segment, workspace_root) {
            return Err(format!(
                "no loader under {} opens `{segment}` (from {harness} store `{path}`)",
                STORE_SEARCH_ROOTS.join(", ")
            ));
        }
        checked += 1;
    }
    if checked == 0 {
        return Err(format!("store path `{path}` names no concrete segment"));
    }
    Ok(())
}

fn toml_has_key(doc: &toml::Value, key: &str) -> bool {
    let mut cur = doc;
    for part in key.split('.') {
        match cur.get(part) {
            Some(next) => cur = next,
            None => return false,
        }
    }
    true
}

/// Check one evidence item for one row. Returns `Err(reason)` when the
/// citation does not resolve under every applicable preset / harness.
pub fn check_evidence(
    row: &Row,
    evidence: &Evidence,
    workspace_root: &std::path::Path,
) -> Result<(), String> {
    let applicable: Vec<(&str, &str)> = PARITY_PRESETS
        .iter()
        .filter(|(column, _)| row.has(column))
        .map(|(c, p)| (*c, *p))
        .collect();
    if applicable.is_empty() {
        return Err("row has no applicable preset (neither cc nor cx has it)".into());
    }
    match evidence {
        Evidence::Tool { name } => {
            for (_, preset) in &applicable {
                let resolved = resolve_preset(preset)?;
                let registry = ToolRegistry::from_config(&resolved.config);
                if registry.get(name).is_none() {
                    return Err(format!("tool `{name}` is not registered under `{preset}`"));
                }
            }
            Ok(())
        }
        Evidence::Module { name } => {
            for (_, preset) in &applicable {
                let resolved = resolve_preset(preset)?;
                match resolved.modules.get(name) {
                    Some(true) => {}
                    Some(false) => {
                        return Err(format!("module `{name}` is disabled under `{preset}`"))
                    }
                    None => return Err(format!("module `{name}` is not a known module")),
                }
            }
            Ok(())
        }
        Evidence::Config { key } => {
            for (_, preset) in &applicable {
                let text =
                    presets::lookup(preset).ok_or_else(|| format!("unknown preset `{preset}`"))?;
                let doc: toml::Value = toml::from_str(text).map_err(|e| e.to_string())?;
                if !toml_has_key(&doc, key) {
                    return Err(format!("`{preset}` does not set `{key}`"));
                }
            }
            Ok(())
        }
        Evidence::Runtime { capability } => {
            for (column, _) in &applicable {
                let caps = backend_capabilities(column);
                match runtime_flag(&caps, capability) {
                    Some(true) => {}
                    Some(false) => {
                        return Err(format!(
                            "runtime capability `{capability}` is false for `{column}`"
                        ))
                    }
                    None => return Err(format!("`{capability}` is not a runtime capability flag")),
                }
            }
            Ok(())
        }
        Evidence::Code { .. } | Evidence::CliVerb { .. } | Evidence::Store { .. } => {
            check_source_evidence(evidence, workspace_root)
        }
    }
}

/// Check one evidence item whose resolution does not depend on a preset:
/// `code` against the source tree, `cli_verb` against the pinned help
/// fixture, `store` against the workspace's loaders.
pub fn check_source_evidence(
    evidence: &Evidence,
    workspace_root: &std::path::Path,
) -> Result<(), String> {
    match evidence {
        Evidence::Code { path, symbol } => {
            let full = workspace_root.join(path);
            let text =
                std::fs::read_to_string(&full).map_err(|e| format!("cannot read `{path}`: {e}"))?;
            if let Some(symbol) = symbol {
                if !text.contains(symbol.as_str()) {
                    return Err(format!("`{path}` does not contain `{symbol}`"));
                }
            }
            Ok(())
        }
        Evidence::CliVerb { harness, verb } => check_cli_verb(harness, verb),
        Evidence::Store { harness, path } => check_store(harness, path, workspace_root),
        other => Err(format!(
            "{other:?} needs a preset context; use `check_evidence`"
        )),
    }
}

/// Check one evidence item on an orchestration row.
///
/// The two evidence lanes are kept apart on purpose: a harness COLUMN may
/// only cite a `cli_verb` of that same harness (what the pinned CLI
/// advertises), and supercode's STATUS may only cite `store` / `code` (what
/// this workspace actually does). A `cli_verb` can never make supercode look
/// implemented, and a `code` citation can never make a harness look capable.
pub fn check_orchestration_evidence(
    lane: OrchestrationLane<'_>,
    evidence: &Evidence,
    workspace_root: &std::path::Path,
) -> Result<(), String> {
    match (lane, evidence) {
        (OrchestrationLane::Column(harness), Evidence::CliVerb { harness: cited, .. }) => {
            if cited != harness {
                return Err(format!(
                    "the {harness} column cites a `{cited}` verb ({evidence:?})"
                ));
            }
            check_source_evidence(evidence, workspace_root)
        }
        (OrchestrationLane::Column(harness), other) => Err(format!(
            "the {harness} column may only cite `cli_verb`, not {other:?}"
        )),
        (OrchestrationLane::Supercode, Evidence::Store { .. } | Evidence::Code { .. }) => {
            check_source_evidence(evidence, workspace_root)
        }
        (OrchestrationLane::Supercode, other) => Err(format!(
            "a supercode status may only cite `store` or `code`, not {other:?}"
        )),
    }
}

/// Which side of an orchestration row an evidence item backs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OrchestrationLane<'a> {
    /// One harness column: what the pinned harness CLI advertises.
    Column(&'a str),
    /// supercode's audited status: what this workspace does.
    Supercode,
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashSet;
    use std::path::PathBuf;

    fn workspace_root() -> PathBuf {
        PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("../..")
            .canonicalize()
            .unwrap()
    }

    #[test]
    fn ledger_parses_with_unique_ids_and_full_catalog() {
        let rows = ledger();
        assert_eq!(rows.len(), 263, "one row per catalog capability");
        let ids: HashSet<&str> = rows.iter().map(|r| r.id.as_str()).collect();
        assert_eq!(ids.len(), rows.len(), "row ids must be unique");
        for row in &rows {
            assert!(
                (1..=11).contains(&row.domain),
                "{}: domain out of range",
                row.id
            );
        }
    }

    #[test]
    fn not_applicable_rows_are_exactly_those_neither_harness_has() {
        for row in ledger() {
            let neither = !row.cc.present() && !row.cx.present();
            assert_eq!(
                row.status == Status::NotApplicable,
                neither,
                "{}: not_applicable must mean neither cc nor cx has it",
                row.id
            );
        }
    }

    /// The audit is complete: a row may never regress to `unaudited`, in
    /// EITHER ledger.
    #[test]
    fn no_row_remains_unaudited() {
        let mut stale: Vec<String> = ledger()
            .into_iter()
            .filter(|r| r.status == Status::Unaudited)
            .map(|r| r.id)
            .collect();
        stale.extend(
            orchestration_ledger()
                .into_iter()
                .filter(|r| r.status == Status::Unaudited)
                .map(|r| r.id),
        );
        assert!(stale.is_empty(), "unaudited rows: {stale:?}");
    }

    #[test]
    fn both_parity_presets_resolve_strictly() {
        for (_, preset) in PARITY_PRESETS {
            resolve_preset(preset).unwrap_or_else(|e| panic!("{preset}: {e}"));
        }
    }

    /// The honesty gate: every implemented/partial row must cite at least one
    /// evidence item, and EVERY cited item must resolve mechanically.
    #[test]
    fn every_audited_claim_is_backed_by_resolvable_evidence() {
        let root = workspace_root();
        let mut failures = Vec::new();
        for row in ledger() {
            if row.status.requires_evidence() && row.evidence.is_empty() {
                failures.push(format!(
                    "{}: `{}` cites no evidence",
                    row.id,
                    row.status.label()
                ));
            }
            if row.status == Status::Irreducible && row.note.is_empty() {
                failures.push(format!("{}: irreducible without a note", row.id));
            }
            if row.status == Status::Absent && row.cost.is_none() {
                failures.push(format!("{}: absent without a cost class", row.id));
            }
            for ev in &row.evidence {
                if let Err(reason) = check_evidence(&row, ev, &root) {
                    failures.push(format!("{}: {reason}", row.id));
                }
            }
        }
        assert!(
            failures.is_empty(),
            "ledger evidence failures:\n{}",
            failures.join("\n")
        );
    }

    /// The gate must bite: fabricated citations of every kind are rejected.
    #[test]
    fn evidence_gate_rejects_unresolvable_citations() {
        let root = workspace_root();
        let mut row = ledger().into_iter().find(|r| r.cc.present()).unwrap();
        row.cx = Has::No;
        let bad = [
            Evidence::Tool {
                name: "no_such_tool".into(),
            },
            Evidence::Module {
                name: "no_such_module".into(),
            },
            Evidence::Module {
                name: "model_oauth".into(),
            }, // present but disabled in cc-parity
            Evidence::Config {
                key: "capabilities.no_such.key".into(),
            },
            Evidence::Runtime {
                capability: "attach_existing_process".into(),
            }, // false on the claude door
            Evidence::Runtime {
                capability: "not_a_flag".into(),
            },
            Evidence::Code {
                path: "crates/harness/src/no_such_file.rs".into(),
                symbol: None,
            },
            Evidence::Code {
                path: "crates/harness/src/parity.rs".into(),
                // Built at runtime so the literal is not in this file.
                symbol: Some(["ZZZ_NOT", "_PRESENT_ZZZ"].concat()),
            },
        ];
        for ev in bad {
            assert!(
                check_evidence(&row, &ev, &root).is_err(),
                "{ev:?} must be rejected"
            );
        }
        let good = [
            Evidence::Tool {
                name: "read_file".into(),
            },
            Evidence::Module {
                name: "subagents".into(),
            },
            Evidence::Config {
                key: "capabilities.subagents".into(),
            },
            Evidence::Runtime {
                capability: "steer".into(),
            },
            Evidence::Code {
                path: "crates/harness/src/parity.rs".into(),
                symbol: Some("pub fn check_evidence".into()),
            },
        ];
        for ev in good {
            check_evidence(&row, &ev, &root).unwrap_or_else(|e| panic!("{ev:?}: {e}"));
        }
        // A row no harness has cannot cite anything.
        row.cc = Has::No;
        assert!(check_evidence(
            &row,
            &Evidence::Tool {
                name: "read_file".into()
            },
            &root
        )
        .is_err());
    }

    #[test]
    fn report_counts_add_up() {
        for preset in preset_names() {
            let r = report(preset).unwrap();
            let total: usize = r.summary.counts.values().sum();
            assert_eq!(total, r.summary.rows);
            assert_eq!(r.gaps.len(), r.summary.gaps);
            assert!(!render(&r).is_empty());
        }
        assert!(report("pi-core").is_none());
    }

    /// dev/01: the orchestration presets are reportable and named alongside
    /// the capability presets, so the CLI's `--preset` error lists all four.
    #[test]
    fn preset_names_cover_both_ledgers() {
        assert_eq!(
            preset_names(),
            vec![
                "cc-parity",
                "cx-parity",
                "hermes",
                "openclaw",
                "orchestrator"
            ]
        );
        for harness in ORCHESTRATION_PRESETS {
            let r = report(harness).unwrap();
            assert_eq!(&r.summary.preset, harness);
            assert_eq!(&r.summary.harness_column, harness);
            assert!(r.summary.rows > 0, "{harness}: empty denominator");
            let rendered = render(&r);
            assert!(
                rendered.starts_with(&format!("{harness}: {} rows · ", r.summary.rows)),
                "{harness}: unexpected headline: {rendered}"
            );
            assert!(rendered.contains("\nDomain 11\n"), "{harness}: {rendered}");
        }
    }

    /// ORC-7 dev/01: the orchestrator preset reports on the WHOLE ledger,
    /// every row is graded, and its column obeys the same honesty rules as
    /// the harness columns: a present column has detail, an
    /// implemented/partial status cites evidence that resolves here, an
    /// absent row names its cost, and a row the orchestrator's model does not
    /// have is `not_applicable` with no citation.
    #[test]
    fn the_orchestrator_column_is_graded_on_every_row_with_resolvable_evidence() {
        let root = workspace_root();
        let rows = orchestration_ledger();
        let report = report(ORCHESTRATOR_PRESET).unwrap();
        assert_eq!(
            report.summary.rows,
            rows.len(),
            "the orchestrator is graded on every row, never a filtered subset"
        );
        let mut failures = Vec::new();
        for row in &rows {
            if row.orchestrator.present() && row.orchestrator_detail.is_empty() {
                failures.push(format!("{}: orchestrator column has no detail", row.id));
            }
            if !row.orchestrator.present() && row.orchestrator_status != Status::NotApplicable {
                failures.push(format!(
                    "{}: the orchestrator lacks this row but is graded `{}`",
                    row.id,
                    row.orchestrator_status.label()
                ));
            }
            if !row.orchestrator.present() && !row.orchestrator_evidence.is_empty() {
                failures.push(format!("{}: a `no` column cites evidence", row.id));
            }
            if row.orchestrator_status.requires_evidence() && row.orchestrator_evidence.is_empty() {
                failures.push(format!(
                    "{}: orchestrator `{}` cites no evidence",
                    row.id,
                    row.orchestrator_status.label()
                ));
            }
            if row.orchestrator_status == Status::Absent && row.orchestrator_cost.is_none() {
                failures.push(format!(
                    "{}: orchestrator absent without a cost class",
                    row.id
                ));
            }
            if row.orchestrator_note.is_empty() {
                failures.push(format!("{}: no orchestrator note", row.id));
            }
            for ev in &row.orchestrator_evidence {
                if let Err(reason) =
                    check_orchestration_evidence(OrchestrationLane::Supercode, ev, &root)
                {
                    failures.push(format!("{}: {reason}", row.id));
                }
            }
        }
        assert!(
            failures.is_empty(),
            "orchestrator column failures:\n{}",
            failures.join("\n")
        );
        // The headline is honest about the gap count, and only zero is done.
        let rendered = render(&report);
        assert!(
            rendered.starts_with(&format!(
                "orchestrator: {} rows · {} gaps",
                report.summary.rows, report.summary.gaps
            )),
            "{rendered}"
        );
    }

    /// A `store` citation for the orchestrator resolves against this
    /// workspace's own loaders, and a fabricated one still does not.
    #[test]
    fn orchestrator_store_citations_resolve_like_every_other_supercode_status() {
        let root = workspace_root();
        check_orchestration_evidence(
            OrchestrationLane::Supercode,
            &Evidence::Store {
                harness: ORCHESTRATOR_PRESET.into(),
                path: "cron/jobs.json".into(),
            },
            &root,
        )
        .unwrap();
        assert!(check_orchestration_evidence(
            OrchestrationLane::Supercode,
            &Evidence::Store {
                harness: ORCHESTRATOR_PRESET.into(),
                path: "cron/no_such_store.json".into(),
            },
            &root,
        )
        .is_err());
    }

    #[test]
    fn orchestration_ledger_parses_with_unique_ids_and_every_concept() {
        let rows = orchestration_ledger();
        let ids: HashSet<&str> = rows.iter().map(|r| r.id.as_str()).collect();
        assert_eq!(ids.len(), rows.len(), "row ids must be unique");
        let concepts: HashSet<&str> = rows.iter().map(|r| r.concept.as_str()).collect();
        let expected: HashSet<&str> = crate::support::ORCHESTRATION_CONCEPTS
            .iter()
            .copied()
            .collect();
        assert_eq!(
            concepts, expected,
            "every ORCHESTRATION_CONCEPTS entry needs at least one row, and no others"
        );
        for row in &rows {
            assert!(!row.verbs.is_empty(), "{}: no verb group", row.id);
            assert!(!row.semantics.is_empty(), "{}: no semantics", row.id);
            assert!(!row.provenance.is_empty(), "{}: no provenance", row.id);
        }
    }

    #[test]
    fn orchestration_not_applicable_rows_are_exactly_those_neither_harness_has() {
        for row in orchestration_ledger() {
            let neither = !row.hermes.present() && !row.openclaw.present();
            assert_eq!(
                row.status == Status::NotApplicable,
                neither,
                "{}: not_applicable must mean neither hermes nor openclaw has it",
                row.id
            );
        }
    }

    /// The honesty gate for the orchestration ledger: a present harness
    /// column must cite a verb the PINNED CLI advertises, and an
    /// implemented/partial status must cite a store or symbol that resolves
    /// in this workspace.
    #[test]
    fn every_orchestration_claim_is_backed_by_resolvable_evidence() {
        let root = workspace_root();
        let mut failures = Vec::new();
        for row in orchestration_ledger() {
            for harness in ORCHESTRATION_PRESETS {
                let (has, detail, evidence) = row.column(harness).unwrap();
                if has.present() {
                    if detail.is_empty() {
                        failures.push(format!("{}: {harness} column has no detail", row.id));
                    }
                    if evidence.is_empty() {
                        failures.push(format!("{}: {harness} column cites no verb", row.id));
                    }
                } else if !evidence.is_empty() {
                    failures.push(format!(
                        "{}: {harness} lacks the row but cites {evidence:?}",
                        row.id
                    ));
                }
                for ev in evidence {
                    if let Err(reason) =
                        check_orchestration_evidence(OrchestrationLane::Column(harness), ev, &root)
                    {
                        failures.push(format!("{}: {reason}", row.id));
                    }
                }
            }
            if row.status.requires_evidence() && row.evidence.is_empty() {
                failures.push(format!(
                    "{}: `{}` cites no evidence",
                    row.id,
                    row.status.label()
                ));
            }
            if row.status == Status::Absent && row.cost.is_none() {
                failures.push(format!("{}: absent without a cost class", row.id));
            }
            if row.note.is_empty() {
                failures.push(format!("{}: no note", row.id));
            }
            for ev in &row.evidence {
                if let Err(reason) =
                    check_orchestration_evidence(OrchestrationLane::Supercode, ev, &root)
                {
                    failures.push(format!("{}: {reason}", row.id));
                }
            }
        }
        assert!(
            failures.is_empty(),
            "orchestration ledger evidence failures:\n{}",
            failures.join("\n")
        );
    }

    /// dev/02: the new evidence kinds must bite. Fabricated `cli_verb` and
    /// `store` citations are rejected, and neither lane accepts the other's
    /// kind.
    #[test]
    fn orchestration_evidence_gate_rejects_unresolvable_citations() {
        let root = workspace_root();
        let bad = [
            // Verbs the pinned CLIs do not advertise (the inventory claims
            // three of these; the pin does not have them).
            Evidence::CliVerb {
                harness: "hermes".into(),
                verb: "cron teleport".into(),
            },
            Evidence::CliVerb {
                harness: "hermes".into(),
                verb: "approvals list".into(),
            },
            Evidence::CliVerb {
                harness: "openclaw".into(),
                verb: "sessions archive".into(),
            },
            Evidence::CliVerb {
                harness: "openclaw".into(),
                verb: "approvals resolve".into(),
            },
            // A section the fixture never captured.
            Evidence::CliVerb {
                harness: "hermes".into(),
                verb: "kanban list".into(),
            },
            // A harness with no committed fixture at all.
            Evidence::CliVerb {
                harness: "claude-code".into(),
                verb: "cron list".into(),
            },
            // Stores no loader in this workspace opens. `state/openclaw.sqlite`
            // IS opened, so this case proves the check is per-SEGMENT: the
            // outbound delivery QUEUE inside it still resolves to nothing —
            // ORCH-13 reads the run log's delivery columns, never the queue.
            Evidence::Store {
                harness: "openclaw".into(),
                path: "state/openclaw.sqlite/delivery_queue_entries".into(),
            },
            // The table name upstream `main` uses. The PINNED 2026.7.1-2 run
            // store is `cron_run_logs`, so this spelling must not resolve.
            Evidence::Store {
                harness: "openclaw".into(),
                path: "cron_run_receipts".into(),
            },
            Evidence::Store {
                harness: "grok".into(),
                path: "state.db".into(),
            },
            Evidence::Store {
                harness: "hermes".into(),
                path: "<agentId>".into(),
            },
        ];
        for ev in &bad {
            let lane = match ev {
                Evidence::CliVerb { harness, .. } => OrchestrationLane::Column(harness),
                _ => OrchestrationLane::Supercode,
            };
            assert!(
                check_orchestration_evidence(lane, ev, &root).is_err(),
                "{ev:?} must be rejected"
            );
        }
        let good = [
            Evidence::CliVerb {
                harness: "hermes".into(),
                verb: "cron list".into(),
            },
            Evidence::CliVerb {
                harness: "openclaw".into(),
                verb: "agents bindings".into(),
            },
            Evidence::Store {
                harness: "hermes".into(),
                path: "state.db/sessions/session_key".into(),
            },
            // ORCH-7: the job stores both harnesses keep, now opened by
            // `crates/harness/src/jobs.rs`.
            Evidence::Store {
                harness: "hermes".into(),
                path: "profiles/<name>/cron/jobs.json".into(),
            },
            Evidence::Store {
                harness: "openclaw".into(),
                path: "cron/jobs.json".into(),
            },
            // ORCH-8: the fire stores, now opened by
            // `crates/harness/src/runs.rs`.
            Evidence::Store {
                harness: "hermes".into(),
                path: "cron/executions.db".into(),
            },
            Evidence::Store {
                harness: "openclaw".into(),
                path: "state/openclaw.sqlite/cron_run_logs".into(),
            },
            // ORCH-13: the delivery ledger, now opened by
            // `crates/harness/src/runs.rs`.
            Evidence::Store {
                harness: "hermes".into(),
                path: "state.db/delivery_obligations".into(),
            },
        ];
        for ev in &good {
            let lane = match ev {
                Evidence::CliVerb { harness, .. } => OrchestrationLane::Column(harness),
                _ => OrchestrationLane::Supercode,
            };
            check_orchestration_evidence(lane, ev, &root).unwrap_or_else(|e| panic!("{ev:?}: {e}"));
        }
        // The lanes do not accept each other's kinds, and a column may not
        // cite the OTHER harness's CLI.
        assert!(
            check_orchestration_evidence(OrchestrationLane::Supercode, &good[0], &root).is_err()
        );
        assert!(
            check_orchestration_evidence(OrchestrationLane::Column("hermes"), &good[2], &root)
                .is_err()
        );
        assert!(check_orchestration_evidence(
            OrchestrationLane::Column("openclaw"),
            &good[0],
            &root
        )
        .is_err());
    }

    /// dev/03: a fixture without its recapture header is unfalsifiable — a
    /// reader could not reproduce it against the pin.
    #[test]
    fn help_fixtures_record_the_pin_and_how_to_recapture() {
        for harness in ORCHESTRATION_PRESETS {
            let fixture = help_fixture(harness).expect("committed fixture");
            let mut lines = fixture.lines();
            let first = lines.next().unwrap_or_default();
            assert!(
                first.starts_with(&format!("# fixture: {harness} CLI help @ ")),
                "{harness}: first line must name the harness and the pinned version: {first}"
            );
            assert!(
                first.trim_end().len() > format!("# fixture: {harness} CLI help @ ").len(),
                "{harness}: no pinned version in `{first}`"
            );
            let recapture = fixture
                .lines()
                .find(|line| line.starts_with("# recapture:"))
                .unwrap_or_else(|| panic!("{harness}: no `# recapture:` header line"));
            assert!(
                recapture.contains("--help"),
                "{harness}: recapture line names no command: {recapture}"
            );
            assert!(
                fixture
                    .lines()
                    .any(|line| line.starts_with("# provenance:")),
                "{harness}: no `# provenance:` header line"
            );
            assert!(
                fixture
                    .lines()
                    .any(|line| line.starts_with(&format!("$ {harness} "))),
                "{harness}: fixture captures no `$ {harness} ... --help` section"
            );
        }
        assert!(help_fixture("claude-code").is_none());
    }
}