supercode-harness 0.5.45

The optional native Volter Harness 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
//! 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,
}