consortium-cli 0.3.1

CLI tools for consortium — claw, molt, pinch
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
//! CLI grammar: one introspected source of truth for the command surface.
//!
//! Ports the lazaret `nu/grammar.nu` idea (INTERFACE / dump / violations /
//! check) onto clap: every signature fact comes from each bin's
//! `Args::command()` via `clap::CommandFactory` — never a hand-maintained
//! list. `check` fails on any new violation and on any baseline entry that
//! no longer reproduces, so the baseline can only shrink.
//!
//! Rules enforced by [`violations`]:
//!
//! - `global-flags` — introspected bins expose exactly the pinned root
//!   long-option vocabulary ([`PINNED_ROOT_LONGS`]); missing and
//!   unexpected spellings both violate.
//! - `selector` — selector (node/set-selection) options match
//!   [`PINNED_SELECTORS`] exactly per `(bin, subcommand)`; missing and
//!   unexpected selectors both violate. molt pins an empty set; cast
//!   subcommands are strict whitelists.
//! - `registry` — every bin maps to an existing source file and ships a
//!   `tests/<bin>_tests.rs`.
//! - `compat` — claw/molt/pinch short flags equal the frozen upstream
//!   ClusterShell sets (parity is pinned by the `consortium-tests` oracle).
//! - `typed` — every introspected argument carries help text.

use std::borrow::Cow;
use std::collections::BTreeSet;
use std::path::Path;

// Build-time `[[bin]]` registry facts (name, declared path, source/test
// presence) generated by build.rs from Cargo.toml, so runtime checks
// never stat the build source tree.
include!(concat!(env!("OUT_DIR"), "/grammar_registry.rs"));

/// One build-time `[[bin]]` fact generated into the included file.
pub(crate) struct RegistryFact {
    pub name: &'static str,
    pub path: &'static str,
    pub source_exists: bool,
    pub tests_exist: bool,
}

use anyhow::Context;
use clap::{Arg, Command, CommandFactory};
use serde::{Deserialize, Serialize};

/// Module kinds. `legacy`: upstream ClusterShell parity surface (frozen);
/// `orchestration`: new surface, free to evolve. cascade-copy is
/// registry-checked but not introspected (its `Args` stay private in
/// `src/bin/`); the cascade CLI surface lives in `cast` and is
/// introspected through it.
pub const KINDS: &[(&str, &[&str])] = &[
    ("legacy", &["claw", "molt", "pinch"]),
    ("orchestration", &["cast", "cascade_copy"]),
    ("tooling", &["consortium_grammar"]),
];

/// Shared output vocabulary every introspected bin must expose at its root
/// (from `output::OutputArgs`).
pub const SHARED_FLAGS: &[&str] = &["verbose", "color", "format"];

/// Exact selector (node/set-selection) long-option vocabulary per
/// `(bin, subcommand)`; `""` denotes the root command. Both directions
/// are enforced: a pinned selector missing from the live grammar and a
/// selector-like option outside the pinned set both violate. molt (stdin
/// aggregator) pins an empty set. `cast` subcommands are strict: any
/// non-shared long option outside the pinned set violates, so arbitrary
/// unknown selectors (e.g. `cast eval --zone`) are rejected even though
/// they are absent from the cross-bin vocabulary.
pub const PINNED_SELECTORS: &[(&str, &str, &[&str])] = &[
    (
        "claw",
        "",
        &[
            "nodes",
            "exclude",
            "all",
            "group",
            "exclude-group",
            "pick",
            "hostfile",
        ],
    ),
    (
        "pinch",
        "",
        &[
            "exclude",
            "intersection",
            "xor",
            "all",
            "group",
            "pick",
            "slice",
            "index",
        ],
    ),
    ("molt", "", &[]),
    ("cast", "eval", &["on", "tag"]),
    ("cast", "status", &["on", "tag"]),
    ("cast", "build", &["on", "tag", "builders", "fanout"]),
    (
        "cast",
        "deploy",
        &[
            "on",
            "tag",
            "builders",
            "fanout",
            "cascade",
            "cascade-fanout",
            "activate-timeout",
        ],
    ),
    ("cast", "health", &[]),
    ("cast", "tree", &["max-depth", "no-color"]),
    ("cast", "verify", &["fanout", "nodes"]),
    (
        "cast",
        "live",
        &[
            "nodes",
            "strategy",
            "order",
            "fanout",
            "seeds",
            "seed-fraction",
            "closure-mb",
            "bandwidth",
            "uplinks",
            "seed",
            "failure-rate",
            "failure-seed",
            "no-watch",
            "per-round-delay",
            "max-depth",
            "no-color",
        ],
    ),
];

/// Frozen upstream short flags (clush/clubak/cluset compat). The shared
/// `OutputArgs` shorts (`-v`, `-F`) are consortium additions and are
/// excluded from this comparison; long-only upstream flags are unaffected.
pub const PINNED_SHORT_FLAGS: &[(&str, &str)] = &[
    ("claw", "wxagXfltuRobLNqS"),
    ("molt", "bLSTG"),
    ("pinch", "ceflrxiXagSRIO"),
];

/// `[[bin]]` entries parsed from a Cargo.toml manifest, in declaration
/// order: `(name, path)` with `path` relative to the manifest directory
/// (Cargo's default `src/bin/<name>.rs` when `path` is omitted).
pub fn manifest_bins(manifest: &Path) -> anyhow::Result<Vec<(String, String)>> {
    let raw = std::fs::read_to_string(manifest)?;
    let value: toml::Value = toml::from_str(&raw)?;
    let bins = value
        .get("bin")
        .and_then(|b| b.as_array())
        .map(|a| a.as_slice())
        .unwrap_or(&[]);
    Ok(bins
        .iter()
        .filter_map(|b| {
            let name = b.get("name")?.as_str()?.to_string();
            let path = b
                .get("path")
                .and_then(|p| p.as_str())
                .map(|p| p.to_string())
                .unwrap_or_else(|| format!("src/bin/{name}.rs"));
            Some((name, path))
        })
        .collect())
}

/// Every classified bin across [`KINDS`].
fn kind_bins() -> impl Iterator<Item = &'static str> {
    KINDS.iter().flat_map(|(_, bins)| bins.iter().copied())
}

/// Borrowed bin facts; installed checks inspect build-time constants
/// without copying each name or source path.
struct DeclaredBin<'a> {
    name: &'a str,
    path: &'a str,
    source_exists: bool,
    tests_exist: bool,
}

fn embedded_registry() -> impl Iterator<Item = DeclaredBin<'static>> {
    REGISTRY_FACTS.iter().map(|f| DeclaredBin {
        name: f.name,
        path: f.path,
        source_exists: f.source_exists,
        tests_exist: f.tests_exist,
    })
}

/// Shared registry validator fed either by embedded build facts
/// (production, no filesystem access) or by live `manifest_bins` + fs
/// checks (temporary-manifest tests): every declared bin must be
/// classified in [`KINDS`] (hyphenated names fold to underscores) and
/// ship its declared source plus `tests/<bin>_tests.rs`; every [`KINDS`]
/// bin must have a matching declaration.
fn registry_findings<'a>(
    declared: anyhow::Result<impl IntoIterator<Item = DeclaredBin<'a>>>,
) -> Vec<Violation> {
    let mut v = Vec::new();
    let declared = match declared {
        Ok(d) => d,
        Err(e) => {
            v.push(Violation {
                rule: "registry".to_string(),
                subcommand: String::new(),
                bin: String::new(),
                arg: "manifest".to_string(),
                detail: format!("unreadable Cargo.toml: {e}"),
            });
            return v;
        }
    };
    let mut declared_underscored: BTreeSet<Cow<'a, str>> = BTreeSet::new();
    for b in declared {
        let us = if b.name.contains('-') {
            Cow::Owned(b.name.replace('-', "_"))
        } else {
            Cow::Borrowed(b.name)
        };
        if !kind_bins().any(|bin| bin == us.as_ref()) {
            v.push(Violation {
                rule: "registry".to_string(),
                subcommand: String::new(),
                bin: b.name.to_string(),
                arg: "kind".to_string(),
                detail: format!("bin '{}' is not classified in KINDS", b.name),
            });
        }
        if !b.source_exists {
            v.push(Violation {
                rule: "registry".to_string(),
                subcommand: String::new(),
                bin: b.name.to_string(),
                arg: "source".to_string(),
                detail: format!("missing declared source {}", b.path),
            });
        }
        if !b.tests_exist {
            v.push(Violation {
                rule: "registry".to_string(),
                subcommand: String::new(),
                bin: b.name.to_string(),
                arg: "tests".to_string(),
                detail: format!("missing tests/{us}_tests.rs"),
            });
        }
        declared_underscored.insert(us);
    }
    for bin in kind_bins() {
        if !declared_underscored.contains(bin) {
            v.push(Violation {
                rule: "registry".to_string(),
                subcommand: String::new(),
                bin: bin.to_string(),
                arg: "manifest".to_string(),
                detail: format!("KINDS bin '{bin}' has no [[bin]] in Cargo.toml"),
            });
        }
    }
    v
}

/// Registry rule evaluated live against a Cargo.toml manifest (whose
/// directory is the crate root holding `src/` and `tests/`). Used by
/// temporary-manifest tests; production uses the embedded build facts.
pub fn registry_violations(manifest: &Path) -> Vec<Violation> {
    let root = manifest.parent().unwrap_or_else(|| Path::new("."));
    let bins = match manifest_bins(manifest) {
        Ok(bins) => bins,
        Err(error) => {
            return registry_findings(Err::<std::iter::Empty<DeclaredBin<'static>>, _>(error));
        }
    };
    registry_findings(Ok(bins.iter().map(|(name, path)| {
        let us = name.replace('-', "_");
        let tests = format!("{us}_tests.rs");
        DeclaredBin {
            source_exists: root.join(path).exists(),
            tests_exist: root.join("tests").join(&tests).exists(),
            name: name.as_str(),
            path: path.as_str(),
        }
    })))
}

/// One introspected argument (or a `registry` placeholder row for the
/// non-introspected cascade bins).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Row {
    pub bin: String,
    pub subcommand: String,
    pub arg: String,
    /// `positional` | `flag` | `switch` | `registry`
    pub kind: String,
    pub short: Option<char>,
    /// Root long-option spelling as clap renders it (`get_long()`); None
    /// for positionals and registry placeholders.
    pub long: Option<String>,
    pub r#type: String,
    pub default: String,
    pub help: String,
}

/// One rule violation, addressable by `rule bin subcommand arg`. The
/// `subcommand` distinguishes the same argument ID on different
/// subcommands (e.g. `cast build --tag` vs `cast deploy --tag`);
/// root-level violations use the explicit [`ROOT`] marker.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Violation {
    pub rule: String,
    pub bin: String,
    pub subcommand: String,
    pub arg: String,
    pub detail: String,
}

/// Unambiguous root marker in baseline keys; no subcommand may be named
/// this, so `rule bin (root) arg` can never collide with a subcommand key.
pub const ROOT: &str = "(root)";

/// Stable join key for baseline comparison.
pub fn key_of(v: &Violation) -> String {
    let sub = if v.subcommand.is_empty() {
        ROOT
    } else {
        &v.subcommand
    };
    format!("{} {} {} {}", v.rule, v.bin, sub, v.arg)
}

fn arg_kind(a: &Arg) -> &'static str {
    if a.is_positional() {
        "positional"
    } else if a.get_num_args().map(|n| n.takes_values()).unwrap_or(false) {
        "flag"
    } else {
        "switch"
    }
}

fn walk(cmd: &Command, bin: &str, subcommand: &str, rows: &mut Vec<Row>) {
    for a in cmd.get_arguments() {
        let r#type = a
            .get_value_names()
            .and_then(|n| n.first())
            .map(|n| n.to_string())
            .unwrap_or_default();
        let default = a
            .get_default_values()
            .iter()
            .map(|v| v.to_string_lossy().to_string())
            .collect::<Vec<_>>()
            .join(" ");
        rows.push(Row {
            bin: bin.to_string(),
            subcommand: subcommand.to_string(),
            arg: a.get_id().to_string(),
            kind: arg_kind(a).to_string(),
            short: a.get_short(),
            long: a.get_long().map(|l| l.to_string()),
            r#type,
            default,
            help: a.get_help().map(|h| h.to_string()).unwrap_or_default(),
        });
    }
    for sc in cmd.get_subcommands() {
        walk(sc, bin, sc.get_name(), rows);
    }
}

/// One row per exported argument across all bins, straight from clap —
/// the same data a human reads off `--help`, as a table.
pub fn dump() -> Vec<Row> {
    let mut rows = Vec::new();
    let commands = [
        ("claw", crate::claw::Args::command()),
        ("molt", crate::molt::Args::command()),
        ("pinch", crate::pinch::Args::command()),
        ("cast", crate::cast::Args::command()),
    ];
    for (bin, cmd) in &commands {
        walk(cmd, bin, "", &mut rows);
    }
    // Registry placeholders for classified bins without clap Args.
    for bin in kind_bins().filter(|b| !commands.iter().any(|(name, _)| name == b)) {
        rows.push(Row {
            bin: (*bin).to_string(),
            subcommand: String::new(),
            arg: String::new(),
            kind: "registry".to_string(),
            short: None,
            long: None,
            r#type: String::new(),
            default: String::new(),
            help: "registered bin (not introspected)".to_string(),
        });
    }
    rows
}

/// Exact reviewed root long-option vocabulary per introspected bin.
/// `global-flags` rejects both missing and unexpected spellings; clap's
/// autogenerated `help`/`version` are excluded.
pub const PINNED_ROOT_LONGS: &[(&str, &[&str])] = &[
    (
        "claw",
        &[
            "nodes",
            "exclude",
            "all",
            "group",
            "exclude-group",
            "pick",
            "hostfile",
            "fanout",
            "user",
            "connect-timeout",
            "command-timeout",
            "worker",
            "options",
            "remote",
            "topology",
            "dshbak",
            "line",
            "label",
            "quiet",
            "maxrc",
            "axis",
            "verbose",
            "color",
            "format",
            "copy",
            "rcopy",
            "dest",
        ],
    ),
    (
        "molt",
        &[
            "dshbak",
            "line",
            "separator",
            "tree",
            "groupbase",
            "axis",
            "interpret-keys",
            "verbose",
            "color",
            "format",
        ],
    ),
    (
        "pinch",
        &[
            "count",
            "expand",
            "fold",
            "list",
            "regroup",
            "groupsources",
            "exclude",
            "intersection",
            "xor",
            "all",
            "group",
            "separator",
            "rangeset",
            "autostep",
            "split",
            "contiguous",
            "pick",
            "slice",
            "index",
            "output-format",
            "verbose",
            "color",
            "format",
        ],
    ),
    (
        "cast",
        &[
            "config",
            "flake",
            "user",
            "nix-args",
            "darwin-nix-args",
            "nixos-nix-args",
            "verbose",
            "color",
            "format",
        ],
    ),
];

/// `global-flags` rule against exact root long spellings: every pinned
/// long must be present and no unexpected long may appear. Compares
/// `Row.long` (not arg IDs), so a renamed spelling for an existing
/// argument ID violates both as missing and as unexpected.
fn global_flags(rows: &[Row], out: &mut Vec<Violation>) {
    for (bin, pinned) in PINNED_ROOT_LONGS {
        let want: BTreeSet<&str> = pinned.iter().copied().collect();
        let got: BTreeSet<&str> = rows
            .iter()
            .filter(|r| {
                r.bin == *bin
                    && r.subcommand.is_empty()
                    && r.kind != "registry"
                    && r.arg != "help"
                    && r.arg != "version"
            })
            .filter_map(|r| r.long.as_deref())
            .collect();
        for missing in want.difference(&got) {
            out.push(Violation {
                rule: "global-flags".to_string(),
                subcommand: String::new(),
                bin: (*bin).to_string(),
                arg: (*missing).to_string(),
                detail: "pinned root long option missing".to_string(),
            });
        }
        for unexpected in got.difference(&want) {
            out.push(Violation {
                rule: "global-flags".to_string(),
                subcommand: String::new(),
                bin: (*bin).to_string(),
                arg: (*unexpected).to_string(),
                detail: "unexpected root long option".to_string(),
            });
        }
    }
}

/// Long options that are shared OutputArgs or clap built-ins, never
/// selectors.
const NON_SELECTOR_LONGS: &[&str] = &["verbose", "color", "format", "help", "version"];

/// `selector` rule over exact `(bin, subcommand)` sets. A candidate is
/// any root/subcommand row with a long spelling outside
/// [`NON_SELECTOR_LONGS`]. Candidates in the cross-bin vocabulary but not
/// pinned at their location violate as unexpected; on `cast` (strict)
/// any unpinned candidate violates. Pinned selectors absent from the
/// live grammar violate as missing. Rows are keyed per subcommand, so
/// `cast build --on` and `cast deploy --on` are distinct.
fn selectors(rows: &[Row], out: &mut Vec<Violation>) {
    // Cross-bin "selector-like" vocabulary: selection names from every
    // pinned set, minus execution options shared across commands
    // (fanout, builders, cascade...). molt --on must violate even though
    // `on` is pinned only on cast; claw --fanout must not, because
    // fanout is delivery, not node selection. `cast` subcommands are
    // pinned exactly by their own strict whitelists.
    let exec_options: [&str; 5] = [
        "fanout",
        "builders",
        "cascade",
        "cascade-fanout",
        "activate-timeout",
    ];
    let vocab: BTreeSet<&str> = PINNED_SELECTORS
        .iter()
        .flat_map(|(_, _, longs)| longs.iter().copied())
        .filter(|l| !exec_options.contains(l))
        .collect();
    for (bin, sub, pinned) in PINNED_SELECTORS {
        let want: BTreeSet<&str> = pinned.iter().copied().collect();
        let candidates: BTreeSet<&str> = rows
            .iter()
            .filter(|r| {
                r.bin == *bin
                    && r.subcommand == *sub
                    && r.kind != "registry"
                    && r.kind != "positional"
            })
            .filter_map(|r| r.long.as_deref())
            .filter(|l| !NON_SELECTOR_LONGS.contains(l))
            .collect();
        for missing in want.difference(&candidates) {
            out.push(Violation {
                rule: "selector".to_string(),
                subcommand: (*sub).to_string(),
                bin: (*bin).to_string(),
                arg: (*missing).to_string(),
                detail: "pinned selector missing from the live grammar".to_string(),
            });
        }
        let strict = *bin == "cast";
        for unexpected in candidates.difference(&want) {
            if vocab.contains(unexpected) || strict {
                out.push(Violation {
                    rule: "selector".to_string(),
                    subcommand: (*sub).to_string(),
                    bin: (*bin).to_string(),
                    arg: (*unexpected).to_string(),
                    detail: if strict {
                        "cast subcommand selector outside the pinned whitelist".to_string()
                    } else {
                        "selector-like option not allowed on this command".to_string()
                    },
                });
            }
        }
    }
}

/// Interface rules evaluated against the live grammar.
pub fn violations() -> Vec<Violation> {
    let rows = dump();
    let mut v = Vec::new();

    global_flags(&rows, &mut v);

    selectors(&rows, &mut v);

    // Embedded build-time facts: no stat of the build source tree.
    v.extend(registry_findings(Ok::<_, anyhow::Error>(
        embedded_registry(),
    )));

    for (bin, pinned) in PINNED_SHORT_FLAGS {
        let got: BTreeSet<char> = rows
            .iter()
            .filter(|r| r.bin == *bin && !SHARED_FLAGS.contains(&r.arg.as_str()))
            .filter_map(|r| r.short)
            .collect();
        let want: BTreeSet<char> = pinned.chars().collect();
        if got != want {
            v.push(Violation {
                rule: "compat".to_string(),
                subcommand: String::new(),
                bin: (*bin).to_string(),
                arg: "short-flags".to_string(),
                detail: format!("frozen upstream set drift: got {got:?} want {want:?}"),
            });
        }
    }

    typed_missing_help(&rows, &mut v);

    v
}

/// `typed` rule: every introspected argument (excluding `help`/`version`
/// and non-introspected registry rows) must carry help text. Keyed per
/// `bin subcommand arg`, so the same argument ID on distinct subcommands
/// yields distinct violations.
fn typed_missing_help(rows: &[Row], out: &mut Vec<Violation>) {
    out.extend(
        rows.iter()
            .filter(|r| {
                r.kind != "registry" && r.help.is_empty() && r.arg != "help" && r.arg != "version"
            })
            .map(|r| Violation {
                rule: "typed".to_string(),
                subcommand: r.subcommand.clone(),
                bin: r.bin.clone(),
                arg: r.arg.clone(),
                detail: "argument has no help text".to_string(),
            }),
    );
}

/// Pure new-vs-stale comparison over baseline keys: errors when the live
/// set has keys the baseline lacks (new violations) or the baseline has
/// keys that no longer reproduce (stale entries — the baseline can only
/// shrink). Returns the live violation count on success.
pub fn check_keys(live: &[String], baseline: &[String]) -> anyhow::Result<usize> {
    let live_set: BTreeSet<&String> = live.iter().collect();
    let baseline_set: BTreeSet<&String> = baseline.iter().collect();
    if live_set.len() != live.len() {
        return Err(anyhow::anyhow!(
            "grammar check failed: duplicate keys in live set: {live:?}"
        ));
    }
    if baseline_set.len() != baseline.len() {
        return Err(anyhow::anyhow!(
            "grammar check failed: duplicate keys in baseline: {baseline:?}"
        ));
    }
    let new: Vec<&String> = live_set.difference(&baseline_set).copied().collect();
    let stale: Vec<&String> = baseline_set.difference(&live_set).copied().collect();
    if !new.is_empty() || !stale.is_empty() {
        return Err(anyhow::anyhow!(
            "grammar check failed: {new_count} new, {stale_count} stale\nnew: {new:?}\nstale: {stale:?}",
            new_count = new.len(),
            stale_count = stale.len()
        ));
    }
    Ok(live.len())
}

/// Result of comparing the live grammar against a baseline.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct CheckReport {
    pub ok: bool,
    pub baseline: usize,
    pub violations: usize,
}

/// Compare live violations with the baseline file (JSON array of
/// `rule bin subcommand arg` keys, root level marked [`ROOT`]). Errors on
/// new, stale, or duplicate entries.
pub fn check(baseline: &Path) -> anyhow::Result<CheckReport> {
    let source = std::fs::read_to_string(baseline).with_context(|| {
        format!(
            "grammar check failed: cannot read baseline {}",
            baseline.display()
        )
    })?;
    let base: Vec<String> = serde_json::from_str(&source)?;
    let live = violations();
    let keys: Vec<String> = live.iter().map(key_of).collect();
    let count = check_keys(&keys, &base)?;
    Ok(CheckReport {
        ok: true,
        baseline: base.len(),
        violations: count,
    })
}

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

    /// The same argument ID (`on`) on `cast build` vs `cast deploy` with
    /// missing help must yield two distinct typed violation keys.
    #[test]
    fn typed_keys_distinguish_same_arg_across_subcommands() {
        let mk = |sub: &str| Row {
            bin: "cast".to_string(),
            subcommand: sub.to_string(),
            arg: "on".to_string(),
            kind: "flag".to_string(),
            short: None,
            long: None,
            r#type: String::new(),
            default: String::new(),
            help: String::new(),
        };
        let mut v = Vec::new();
        typed_missing_help(&[mk("build"), mk("deploy")], &mut v);
        let keys: BTreeSet<String> = v.iter().map(key_of).collect();
        assert_eq!(
            keys,
            BTreeSet::from([
                "typed cast build on".to_string(),
                "typed cast deploy on".to_string(),
            ]),
            "same arg ID on distinct subcommands must produce two distinct typed keys"
        );
    }

    /// The exact-root-long `global-flags` rule: a synthetic new long-only
    /// flag and a changed spelling for an existing arg ID must violate;
    /// the current dump must not.
    #[test]
    fn global_flags_rejects_missing_and_unexpected_root_longs() {
        let mut rows = dump();
        assert!(
            {
                let mut v = Vec::new();
                global_flags(&rows, &mut v);
                v
            }
            .is_empty(),
            "current tree must satisfy the pinned root long sets"
        );

        rows.push(Row {
            bin: "cast".to_string(),
            subcommand: String::new(),
            arg: "prefix".to_string(),
            kind: "switch".to_string(),
            short: None,
            long: Some("prefix".to_string()),
            r#type: String::new(),
            default: String::new(),
            help: "synthetic".to_string(),
        });
        let keys: BTreeSet<String> = {
            let mut v = Vec::new();
            global_flags(&rows, &mut v);
            v.iter().map(key_of).collect()
        };
        assert_eq!(
            keys,
            BTreeSet::from(["global-flags cast (root) prefix".to_string()]),
            "synthetic long-only flag must be rejected as unexpected"
        );

        // Changed spelling for an existing arg ID: --format becomes
        // --output-format on cast; both missing and unexpected fire.
        for r in rows.iter_mut() {
            if r.bin == "cast" && r.arg == "format" {
                r.long = Some("output-format".to_string());
            }
        }
        let keys: BTreeSet<String> = {
            let mut v = Vec::new();
            global_flags(&rows, &mut v);
            v.iter().map(key_of).collect()
        };
        assert!(
            keys.contains("global-flags cast (root) format"),
            "renamed spelling must violate as missing: {keys:?}"
        );
        assert!(
            keys.contains("global-flags cast (root) output-format"),
            "renamed spelling must violate as unexpected: {keys:?}"
        );
    }

    /// Selector rule negatives on synthetic rows: molt --on, cast
    /// health --on, unknown cast eval --zone; and missing pinned
    /// selectors for removed cast deploy --tag / claw --nodes. The live
    /// dump must stay clean.
    #[test]
    fn selector_rule_rejects_unknown_and_missing_selectors() {
        let mut rows = dump();
        assert!(
            {
                let mut v = Vec::new();
                selectors(&rows, &mut v);
                v
            }
            .is_empty(),
            "live dump must satisfy the pinned selector sets"
        );

        let mut push = |bin: &str, sub: &str, arg: &str| {
            rows.push(Row {
                bin: bin.to_string(),
                subcommand: sub.to_string(),
                arg: arg.to_string(),
                kind: "flag".to_string(),
                short: None,
                long: Some(arg.to_string()),
                r#type: String::new(),
                default: String::new(),
                help: "synthetic".to_string(),
            })
        };
        push("molt", "", "on");
        push("cast", "health", "on");
        push("cast", "eval", "zone");
        let keys: BTreeSet<String> = {
            let mut v = Vec::new();
            selectors(&rows, &mut v);
            v.iter().map(key_of).collect()
        };
        assert_eq!(
            keys,
            BTreeSet::from([
                "selector molt (root) on".to_string(),
                "selector cast health on".to_string(),
                "selector cast eval zone".to_string(),
            ]),
            "unknown selectors must violate: {keys:?}"
        );

        rows.retain(|r| !(r.bin == "cast" && r.subcommand == "deploy" && r.arg == "tag"));
        rows.retain(|r| !(r.bin == "claw" && r.subcommand.is_empty() && r.arg == "nodes"));
        let keys: BTreeSet<String> = {
            let mut v = Vec::new();
            selectors(&rows, &mut v);
            v.iter().map(key_of).collect()
        };
        assert!(
            keys.contains("selector cast deploy tag"),
            "removed cast deploy --tag must violate as missing: {keys:?}"
        );
        assert!(
            keys.contains("selector claw (root) nodes"),
            "removed claw --nodes must violate as missing: {keys:?}"
        );
    }
}