agentnative 0.1.3

The agent-native CLI linter — check whether your CLI follows agent-readiness principles
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
//! Flat `&'static [Requirement]` registry covering every MUST, SHOULD, and
//! MAY across P1–P7. The registry is the single source of truth linking
//! spec requirements to the checks that verify them via `Check::covers()`.
//!
//! IDs follow the pattern `p{N}-{level}-{key}`. They are stable and must
//! not change once published — scorecards and the coverage matrix pin
//! against them.

use serde::Serialize;

/// Severity level of a spec requirement.
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Level {
    Must,
    Should,
    May,
}

/// Whether a requirement applies to every CLI or only when a condition holds.
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
#[serde(tag = "kind", content = "condition", rename_all = "lowercase")]
pub enum Applicability {
    Universal,
    Conditional(&'static str),
}

/// Categories under which a tool may be exempt from specific requirements.
/// Referenced by scorecard `audit_profile`.
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum ExceptionCategory {
    /// TUI-by-design tools (lazygit, k9s, btop). Interactive-prompt MUSTs
    /// suppressed; TTY-driving-agent access is out-of-scope for verification.
    HumanTui,
    /// File-traversal utilities (fd, find). Subcommand-structure SHOULDs
    /// relaxed; these tools have no subcommands by design.
    FileTraversal,
    /// POSIX utilities (cat, sed, awk). Stdin-as-primary-input is their
    /// contract; P1 interactive-prompt MUSTs satisfied vacuously.
    PosixUtility,
    /// Diagnostic tools (nvidia-smi, vmstat). No write operations, so P5
    /// MUSTs do not apply.
    DiagnosticOnly,
}

impl ExceptionCategory {
    /// Kebab-case identifier that matches the serde representation used by
    /// both the CLI (`--audit-profile human-tui`) and the scorecard JSON
    /// (`"audit_profile": "human-tui"`). Kept as a dedicated method so
    /// callers don't have to round-trip through `serde_json` to stringify.
    pub fn as_kebab_case(&self) -> &'static str {
        match self {
            ExceptionCategory::HumanTui => "human-tui",
            ExceptionCategory::FileTraversal => "file-traversal",
            ExceptionCategory::PosixUtility => "posix-utility",
            ExceptionCategory::DiagnosticOnly => "diagnostic-only",
        }
    }

    /// One-line human description. Surfaces in `coverage/matrix.json`
    /// under the `audit_profiles` section so agents + site renderers can
    /// explain each category without re-deriving semantics from the
    /// kebab-case name.
    pub fn description(&self) -> &'static str {
        match self {
            ExceptionCategory::HumanTui => {
                "TUI-by-design tools (lazygit, k9s, btop). Interactive-prompt MUSTs \
                 suppressed; the TTY-driving contract is out of scope for verification."
            }
            ExceptionCategory::FileTraversal => {
                "File-traversal utilities (fd, find). Subcommand-structure SHOULDs \
                 relaxed; these tools have no subcommands by design."
            }
            ExceptionCategory::PosixUtility => {
                "POSIX utilities (cat, sed, awk). Stdin-as-primary-input is their \
                 contract; P1 interactive-prompt MUSTs satisfied vacuously."
            }
            ExceptionCategory::DiagnosticOnly => {
                "Diagnostic tools (nvidia-smi, vmstat). No write operations, so the \
                 P5 mutation-boundary MUSTs do not apply."
            }
        }
    }
}

/// Every `ExceptionCategory` variant in order. Anchor for parity drift
/// tests (CLI `AuditProfile` must stay isomorphic) and for callers that
/// need to iterate the full set (suppression-table drift check,
/// `coverage/matrix.json` audit_profile section).
///
/// A new variant on the enum is a breaking plan change — land it in
/// `docs/plans/`, update this slice, update `SUPPRESSION_TABLE`, update
/// `AuditProfile`, and regenerate completions. The drift tests below and
/// in `src/cli.rs` tie all four sites together.
pub const ALL_EXCEPTION_CATEGORIES: &[ExceptionCategory] = &[
    ExceptionCategory::HumanTui,
    ExceptionCategory::FileTraversal,
    ExceptionCategory::PosixUtility,
    ExceptionCategory::DiagnosticOnly,
];

// Compile-time guard that the slice above covers every variant. If a
// new variant is added without updating ALL_EXCEPTION_CATEGORIES the
// match is non-exhaustive and the build breaks — making this drift
// impossible to merge rather than "test should catch it."
#[allow(dead_code)]
const fn _all_categories_covers_every_variant(c: ExceptionCategory) -> bool {
    match c {
        ExceptionCategory::HumanTui
        | ExceptionCategory::FileTraversal
        | ExceptionCategory::PosixUtility
        | ExceptionCategory::DiagnosticOnly => true,
    }
}

/// Prefix of the structured evidence string emitted for any check suppressed
/// by `--audit-profile`. The full evidence takes the shape
/// `"suppressed by audit_profile: <kebab-case-category>"`. This is the single
/// source of truth — `main.rs` (producer), `scorecard::audience` (consumer
/// sniffer), and the `scorecard::build_coverage_summary` filter all reference
/// this constant so a rename can't silently desync the three sites.
///
/// Consumers outside this crate (the integration test asserting the literal,
/// downstream site renderers) pin against the stable string shape — treat any
/// edit here as a consumer-contract change.
pub const SUPPRESSION_EVIDENCE_PREFIX: &str = "suppressed by audit_profile: ";

/// Which check IDs each exception category suppresses. When a category
/// applies, the listed checks emit `CheckStatus::Skip` with structured
/// evidence (`"suppressed by audit_profile: <category>"`) instead of
/// running — they appear in `results[]` so readers see what was excluded.
///
/// Entries map to *check* IDs, not requirement IDs, because the runtime
/// suppression point has `check.id()` in hand. The conceptual exemption is
/// a requirement — e.g., TUI apps are exempt from
/// `p1-must-no-interactive` — but because each requirement may be covered
/// by multiple checks across layers, the table enumerates every covering
/// check explicitly so the suppression behavior is deterministic.
///
/// **Every `ExceptionCategory` variant appears here**, even with an empty
/// slice. A missing category would silently no-op at the call site and
/// degrade to running every check — the drift test below catches the gap.
///
/// Every listed check ID is validated against the behavioral/source/project
/// catalog at test time; a typo or rename breaks the build.
///
/// # Trust boundary
///
/// The CLI accepts `--audit-profile <category>` from the caller without
/// validating that the target tool actually fits the declared category.
/// A broken CLI can self-declare `--audit-profile human-tui` and silently
/// mask the P1 interactive-prompt MUSTs + `p6-sigpipe` that would
/// otherwise Fail. This is intentional: the CLI only knows what it was
/// told, and hard-coding per-tool category detection would entangle the
/// repo-agnostic CLI with a tool registry it deliberately doesn't own.
/// Guarding against caller-chosen miscategorization is an upstream
/// concern (site's regen script looks up each tool's declared profile;
/// CI policy gates reviewer attention on registry changes). See also the
/// drift test in `src/cli.rs` pinning `AuditProfile` ↔ `ExceptionCategory`
/// parity and the `audit_profiles` section of `coverage/matrix.json`
/// publishing the full mapping.
///
/// # Drift test scope
///
/// The `suppression_table_check_ids_exist_in_catalog` test below verifies
/// that every listed check ID resolves to a real catalog entry — typos
/// surface at build time. It does *not* assert that each ID is
/// *semantically appropriate* for its category (e.g., a typo that
/// accidentally moves `p2-json-output` into `HumanTui` would still pass
/// because `p2-json-output` exists). At v0.1.3's 4 committed categories
/// the per-category slice is short enough for eyeball review; revisit a
/// per-category snapshot assertion if the table grows.
pub static SUPPRESSION_TABLE: &[(ExceptionCategory, &[&str])] = &[
    (
        ExceptionCategory::HumanTui,
        &[
            // p1-must-no-interactive — TUI apps intercept the TTY by design;
            // their whole contract is interactive. All three covering checks
            // suppress together for consistency.
            "p1-non-interactive",
            "p1-flag-existence",
            "p1-non-interactive-source",
            // p1-should-tty-detection — satisfied vacuously by the TUI
            // contract (the app's event loop is its TTY handler).
            "p1-tty-detection-source",
            // p6-must-sigpipe — TUIs routinely install their own signal
            // handlers to redraw or exit cleanly; the default-disposition
            // check doesn't match the category's execution model.
            "p6-sigpipe",
        ],
    ),
    (
        ExceptionCategory::FileTraversal,
        &[
            // No current check verifies subcommand-examples or
            // subcommand-operations for tools-without-subcommands. The
            // `If: CLI uses subcommands` applicability on existing checks
            // already produces the right Skip outcome for fd/find-style
            // tools. Kept as a table entry so future checks can be added
            // without a schema change.
        ],
    ),
    (
        ExceptionCategory::PosixUtility,
        &[
            // p1-must-no-interactive — POSIX utilities use stdin as the
            // primary input, so the interactive-prompt MUST is satisfied
            // vacuously rather than needing a --no-interactive flag.
            "p1-non-interactive",
            "p1-flag-existence",
            "p1-non-interactive-source",
        ],
    ),
    (
        ExceptionCategory::DiagnosticOnly,
        &[
            // p5-must-dry-run — diagnostic tools perform no writes, so the
            // write-safety MUSTs do not apply. Dry-run is the only P5 check
            // currently covered; read-write-distinction and force-yes are
            // still uncovered in v0.1.3.
            "p5-dry-run",
        ],
    ),
];

/// Whether `check_id` should be suppressed under the given `category`.
/// Returns `false` for unknown check IDs and for categories whose table
/// entry is empty. O(n) in the per-category slice — the table is small
/// and the call site runs once per check per invocation.
pub fn suppresses(check_id: &str, category: ExceptionCategory) -> bool {
    SUPPRESSION_TABLE
        .iter()
        .find(|(cat, _)| *cat == category)
        .is_some_and(|(_, ids)| ids.contains(&check_id))
}

/// A single spec requirement. The flat registry below is iterated by the
/// matrix generator and cross-referenced against `Check::covers()`.
#[derive(Debug, Clone, Serialize)]
pub struct Requirement {
    pub id: &'static str,
    pub principle: u8,
    pub level: Level,
    pub summary: &'static str,
    pub applicability: Applicability,
}

/// Every MUST/SHOULD/MAY in the spec. Order groups by principle, then level
/// (MUST → SHOULD → MAY) so readers can scan down a principle cleanly.
pub static REQUIREMENTS: &[Requirement] = &[
    // --- P1: Non-Interactive by Default ---
    Requirement {
        id: "p1-must-env-var",
        principle: 1,
        level: Level::Must,
        summary: "Every flag settable via environment variable (falsey-value parser for booleans).",
        applicability: Applicability::Universal,
    },
    Requirement {
        id: "p1-must-no-interactive",
        principle: 1,
        level: Level::Must,
        summary: "`--no-interactive` flag gates every prompt library call; when set or stdin is not a TTY, use defaults/stdin or exit with an actionable error.",
        applicability: Applicability::Universal,
    },
    Requirement {
        id: "p1-must-no-browser",
        principle: 1,
        level: Level::Must,
        summary: "Headless authentication path (`--no-browser` / OAuth Device Authorization Grant).",
        applicability: Applicability::Conditional("CLI authenticates against a remote service"),
    },
    Requirement {
        id: "p1-should-tty-detection",
        principle: 1,
        level: Level::Should,
        summary: "Auto-detect non-interactive context via TTY detection; suppress prompts when stderr is not a terminal.",
        applicability: Applicability::Universal,
    },
    Requirement {
        id: "p1-should-defaults-in-help",
        principle: 1,
        level: Level::Should,
        summary: "Document default values for prompted inputs in `--help` output.",
        applicability: Applicability::Universal,
    },
    Requirement {
        id: "p1-may-rich-tui",
        principle: 1,
        level: Level::May,
        summary: "Rich interactive experiences (spinners, progress bars, menus) when TTY is detected and `--no-interactive` is not set.",
        applicability: Applicability::Universal,
    },
    // --- P2: Structured Output ---
    Requirement {
        id: "p2-must-output-flag",
        principle: 2,
        level: Level::Must,
        summary: "`--output text|json|jsonl` flag selects output format; `OutputFormat` enum threaded through output paths.",
        applicability: Applicability::Universal,
    },
    Requirement {
        id: "p2-must-stdout-stderr-split",
        principle: 2,
        level: Level::Must,
        summary: "Data goes to stdout; diagnostics/progress/warnings go to stderr — never interleaved.",
        applicability: Applicability::Universal,
    },
    Requirement {
        id: "p2-must-exit-codes",
        principle: 2,
        level: Level::Must,
        summary: "Exit codes are structured and documented (0 success, 1 general, 2 usage, 77 auth, 78 config).",
        applicability: Applicability::Universal,
    },
    Requirement {
        id: "p2-must-json-errors",
        principle: 2,
        level: Level::Must,
        summary: "When `--output json` is active, errors are emitted as JSON (to stderr) with at least `error`, `kind`, and `message` fields.",
        applicability: Applicability::Universal,
    },
    Requirement {
        id: "p2-should-consistent-envelope",
        principle: 2,
        level: Level::Should,
        summary: "JSON output uses a consistent envelope — a top-level object with predictable keys — across every command.",
        applicability: Applicability::Universal,
    },
    Requirement {
        id: "p2-may-more-formats",
        principle: 2,
        level: Level::May,
        summary: "Additional output formats (CSV, TSV, YAML) beyond the core three.",
        applicability: Applicability::Universal,
    },
    Requirement {
        id: "p2-may-raw-flag",
        principle: 2,
        level: Level::May,
        summary: "`--raw` flag for unformatted output suitable for piping to other tools.",
        applicability: Applicability::Universal,
    },
    // --- P3: Progressive Help Discovery ---
    Requirement {
        id: "p3-must-subcommand-examples",
        principle: 3,
        level: Level::Must,
        summary: "Every subcommand ships at least one concrete invocation example (`after_help` in clap).",
        applicability: Applicability::Conditional("CLI uses subcommands"),
    },
    Requirement {
        id: "p3-must-top-level-examples",
        principle: 3,
        level: Level::Must,
        summary: "The top-level command ships 2–3 examples covering the primary use cases.",
        applicability: Applicability::Universal,
    },
    Requirement {
        id: "p3-should-paired-examples",
        principle: 3,
        level: Level::Should,
        summary: "Examples show human and agent invocations side by side (text then `--output json` equivalent).",
        applicability: Applicability::Universal,
    },
    Requirement {
        id: "p3-should-about-long-about",
        principle: 3,
        level: Level::Should,
        summary: "Short `about` for command-list summaries; `long_about` reserved for detailed descriptions visible with `--help`.",
        applicability: Applicability::Universal,
    },
    Requirement {
        id: "p3-may-examples-subcommand",
        principle: 3,
        level: Level::May,
        summary: "Dedicated `examples` subcommand or `--examples` flag for curated usage patterns.",
        applicability: Applicability::Universal,
    },
    // --- P4: Fail Fast, Actionable Errors ---
    Requirement {
        id: "p4-must-try-parse",
        principle: 4,
        level: Level::Must,
        summary: "Parse arguments with `try_parse()` instead of `parse()` so `--output json` can emit JSON parse errors.",
        applicability: Applicability::Universal,
    },
    Requirement {
        id: "p4-must-exit-code-mapping",
        principle: 4,
        level: Level::Must,
        summary: "Error types map to distinct exit codes (0, 1, 2, 77, 78).",
        applicability: Applicability::Universal,
    },
    Requirement {
        id: "p4-must-actionable-errors",
        principle: 4,
        level: Level::Must,
        summary: "Every error message contains what failed, why, and what to do next.",
        applicability: Applicability::Universal,
    },
    Requirement {
        id: "p4-should-structured-enum",
        principle: 4,
        level: Level::Should,
        summary: "Error types use a structured enum (via `thiserror` in Rust) with variant-to-kind mapping for JSON serialization.",
        applicability: Applicability::Universal,
    },
    Requirement {
        id: "p4-should-gating-before-network",
        principle: 4,
        level: Level::Should,
        summary: "Config and auth validation happen before any network call (three-tier dependency gating).",
        applicability: Applicability::Conditional("CLI makes network calls"),
    },
    Requirement {
        id: "p4-should-json-error-output",
        principle: 4,
        level: Level::Should,
        summary: "Error output respects `--output json`: JSON-formatted errors go to stderr when JSON output is selected.",
        applicability: Applicability::Universal,
    },
    // --- P5: Safe Retries, Mutation Boundaries ---
    Requirement {
        id: "p5-must-force-yes",
        principle: 5,
        level: Level::Must,
        summary: "Destructive operations (delete, overwrite, bulk modify) require an explicit `--force` or `--yes` flag.",
        applicability: Applicability::Conditional("CLI has destructive operations"),
    },
    Requirement {
        id: "p5-must-read-write-distinction",
        principle: 5,
        level: Level::Must,
        summary: "The distinction between read and write commands is clear from the command name and help text alone.",
        applicability: Applicability::Conditional("CLI has both read and write operations"),
    },
    Requirement {
        id: "p5-must-dry-run",
        principle: 5,
        level: Level::Must,
        summary: "A `--dry-run` flag is present on every write command; dry-run output respects `--output json`.",
        applicability: Applicability::Conditional("CLI has write operations"),
    },
    Requirement {
        id: "p5-should-idempotency",
        principle: 5,
        level: Level::Should,
        summary: "Write operations are idempotent where the domain allows it — running the same command twice produces the same result.",
        applicability: Applicability::Conditional("CLI has write operations"),
    },
    // --- P6: Composable, Predictable Command Structure ---
    Requirement {
        id: "p6-must-sigpipe",
        principle: 6,
        level: Level::Must,
        summary: "SIGPIPE fix is the first executable statement in `main()` — piping output to `head`/`tail` must not panic.",
        applicability: Applicability::Universal,
    },
    Requirement {
        id: "p6-must-no-color",
        principle: 6,
        level: Level::Must,
        summary: "TTY detection plus support for `NO_COLOR` and `TERM=dumb` — color codes suppressed when stdout/stderr is not a terminal.",
        applicability: Applicability::Universal,
    },
    Requirement {
        id: "p6-must-completions",
        principle: 6,
        level: Level::Must,
        summary: "Shell completions available via a `completions` subcommand (Tier 1 meta-command — needs no config/auth/network).",
        applicability: Applicability::Universal,
    },
    Requirement {
        id: "p6-must-timeout-network",
        principle: 6,
        level: Level::Must,
        summary: "Network CLIs ship a `--timeout` flag with a sensible default (e.g., 30 seconds).",
        applicability: Applicability::Conditional("CLI makes network calls"),
    },
    Requirement {
        id: "p6-must-no-pager",
        principle: 6,
        level: Level::Must,
        summary: "If the CLI uses a pager (`less`, `more`, `$PAGER`), it supports `--no-pager` or respects `PAGER=\"\"`.",
        applicability: Applicability::Conditional("CLI invokes a pager for output"),
    },
    Requirement {
        id: "p6-must-global-flags",
        principle: 6,
        level: Level::Must,
        summary: "Agentic flags (`--output`, `--quiet`, `--no-interactive`, `--timeout`) are `global = true` so they propagate to every subcommand.",
        applicability: Applicability::Conditional("CLI uses subcommands"),
    },
    Requirement {
        id: "p6-should-stdin-input",
        principle: 6,
        level: Level::Should,
        summary: "Commands that accept input read from stdin when no file argument is provided.",
        applicability: Applicability::Conditional("CLI has commands that accept input data"),
    },
    Requirement {
        id: "p6-should-consistent-naming",
        principle: 6,
        level: Level::Should,
        summary: "Subcommand naming follows a consistent `noun verb` or `verb noun` convention throughout the tool.",
        applicability: Applicability::Conditional("CLI uses subcommands"),
    },
    Requirement {
        id: "p6-should-tier-gating",
        principle: 6,
        level: Level::Should,
        summary: "Three-tier dependency gating: Tier 1 (meta) needs nothing, Tier 2 (local) needs config, Tier 3 (network) needs config + auth.",
        applicability: Applicability::Universal,
    },
    Requirement {
        id: "p6-should-subcommand-operations",
        principle: 6,
        level: Level::Should,
        summary: "Operations are modeled as subcommands, not flags (`tool search \"q\"`, not `tool --search \"q\"`).",
        applicability: Applicability::Conditional("CLI performs multiple distinct operations"),
    },
    Requirement {
        id: "p6-may-color-flag",
        principle: 6,
        level: Level::May,
        summary: "`--color auto|always|never` flag for explicit color control beyond TTY auto-detection.",
        applicability: Applicability::Universal,
    },
    // --- P7: Bounded, High-Signal Responses ---
    Requirement {
        id: "p7-must-quiet",
        principle: 7,
        level: Level::Must,
        summary: "A `--quiet` flag suppresses non-essential output; only requested data and errors appear.",
        applicability: Applicability::Universal,
    },
    Requirement {
        id: "p7-must-list-clamping",
        principle: 7,
        level: Level::Must,
        summary: "List operations clamp to a sensible default maximum; when truncated, indicate it (`\"truncated\": true` in JSON, stderr note in text).",
        applicability: Applicability::Conditional("CLI has list-style commands"),
    },
    Requirement {
        id: "p7-should-verbose",
        principle: 7,
        level: Level::Should,
        summary: "A `--verbose` flag (or `-v` / `-vv`) escalates diagnostic detail when agents need to debug failures.",
        applicability: Applicability::Universal,
    },
    Requirement {
        id: "p7-should-limit",
        principle: 7,
        level: Level::Should,
        summary: "A `--limit` or `--max-results` flag lets callers request exactly the number of items they want.",
        applicability: Applicability::Conditional("CLI has list-style commands"),
    },
    Requirement {
        id: "p7-should-timeout",
        principle: 7,
        level: Level::Should,
        summary: "A `--timeout` flag bounds execution time so agents are not blocked indefinitely.",
        applicability: Applicability::Universal,
    },
    Requirement {
        id: "p7-may-cursor-pagination",
        principle: 7,
        level: Level::May,
        summary: "Cursor-based pagination flags (`--after`, `--before`) for efficient traversal of large result sets.",
        applicability: Applicability::Conditional("CLI returns paginated results"),
    },
    Requirement {
        id: "p7-may-auto-verbosity",
        principle: 7,
        level: Level::May,
        summary: "Automatic verbosity reduction in non-TTY contexts (same behavior `--quiet` explicitly requests).",
        applicability: Applicability::Universal,
    },
];

/// Look up a requirement by ID. Returns `None` if the ID is not registered.
pub fn find(id: &str) -> Option<&'static Requirement> {
    REQUIREMENTS.iter().find(|r| r.id == id)
}

/// Count requirements at a given level. Test helper + doc convenience.
#[allow(dead_code)]
pub fn count_at_level(level: Level) -> usize {
    REQUIREMENTS.iter().filter(|r| r.level == level).count()
}

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

    #[test]
    fn ids_are_unique() {
        let mut seen = HashSet::new();
        for r in REQUIREMENTS {
            assert!(seen.insert(r.id), "duplicate requirement ID: {}", r.id);
        }
    }

    #[test]
    fn ids_follow_naming_convention() {
        for r in REQUIREMENTS {
            let prefix = format!("p{}-", r.principle);
            assert!(
                r.id.starts_with(&prefix),
                "requirement {} does not start with {}",
                r.id,
                prefix
            );
            let level_token = match r.level {
                Level::Must => "-must-",
                Level::Should => "-should-",
                Level::May => "-may-",
            };
            assert!(
                r.id.contains(level_token),
                "requirement {} level token {} missing",
                r.id,
                level_token
            );
        }
    }

    #[test]
    fn principle_range_is_valid() {
        for r in REQUIREMENTS {
            assert!(
                (1..=7).contains(&r.principle),
                "requirement {} has invalid principle {}",
                r.id,
                r.principle
            );
        }
    }

    #[test]
    fn summary_is_non_empty() {
        for r in REQUIREMENTS {
            assert!(
                !r.summary.trim().is_empty(),
                "requirement {} has empty summary",
                r.id
            );
        }
    }

    #[test]
    fn find_returns_registered_ids() {
        assert!(find("p1-must-no-interactive").is_some());
        assert!(find("p6-must-sigpipe").is_some());
        assert!(find("nonexistent-id").is_none());
    }

    #[test]
    fn registry_size_matches_spec() {
        // Spec snapshot 2026-04-20: 46 requirements across P1-P7.
        // Bumping this counter is a deliberate act; it means the spec grew.
        assert_eq!(REQUIREMENTS.len(), 46);
    }

    #[test]
    fn level_counts_match_spec() {
        assert_eq!(count_at_level(Level::Must), 23);
        assert_eq!(count_at_level(Level::Should), 16);
        assert_eq!(count_at_level(Level::May), 7);
    }

    #[test]
    fn exception_category_as_kebab_case_matches_serde() {
        // as_kebab_case must agree with serde_json's rendering — the two
        // are both user-visible surfaces and drifting between them would
        // produce inconsistent scorecard JSON.
        for cat in [
            ExceptionCategory::HumanTui,
            ExceptionCategory::FileTraversal,
            ExceptionCategory::PosixUtility,
            ExceptionCategory::DiagnosticOnly,
        ] {
            let via_serde = serde_json::to_value(cat)
                .ok()
                .and_then(|v| v.as_str().map(|s| s.to_string()))
                .expect("serde renders category as string");
            assert_eq!(via_serde, cat.as_kebab_case(), "mismatch for {cat:?}");
        }
    }

    #[test]
    fn suppresses_positive_cases() {
        assert!(suppresses(
            "p1-non-interactive",
            ExceptionCategory::HumanTui
        ));
        assert!(suppresses("p6-sigpipe", ExceptionCategory::HumanTui));
        assert!(suppresses(
            "p1-non-interactive",
            ExceptionCategory::PosixUtility
        ));
        assert!(suppresses("p5-dry-run", ExceptionCategory::DiagnosticOnly));
    }

    #[test]
    fn suppresses_negative_cases() {
        // Checks not in the HumanTui list must not be suppressed by it.
        assert!(!suppresses("p2-json-output", ExceptionCategory::HumanTui));
        // p6-sigpipe is only suppressed under HumanTui, not the others.
        assert!(!suppresses("p6-sigpipe", ExceptionCategory::PosixUtility));
        assert!(!suppresses("p6-sigpipe", ExceptionCategory::DiagnosticOnly));
        // Unknown check ID is never suppressed.
        assert!(!suppresses(
            "totally-fake-check-id",
            ExceptionCategory::HumanTui
        ));
        assert!(!suppresses(
            "totally-fake-check-id",
            ExceptionCategory::DiagnosticOnly
        ));
    }

    #[test]
    fn suppression_table_covers_every_category() {
        // Every `ExceptionCategory` variant must have a row in the table
        // (even if empty) — otherwise a category silently becomes a no-op
        // at the call site and the `suppresses()` helper always returns
        // false for it, which is never what the operator intended.
        for cat in [
            ExceptionCategory::HumanTui,
            ExceptionCategory::FileTraversal,
            ExceptionCategory::PosixUtility,
            ExceptionCategory::DiagnosticOnly,
        ] {
            assert!(
                SUPPRESSION_TABLE.iter().any(|(c, _)| *c == cat),
                "SUPPRESSION_TABLE missing category {cat:?} — a variant was \
                 added to ExceptionCategory without a corresponding table \
                 entry. Add a row (empty slice is fine) and document why.",
            );
        }
    }

    #[test]
    fn suppression_table_check_ids_exist_in_catalog() {
        use crate::check::Check;
        use crate::checks::all_checks_catalog;

        let catalog: Vec<Box<dyn Check>> = all_checks_catalog();
        let catalog_ids: Vec<&str> = catalog.iter().map(|c| c.id()).collect();

        for (cat, ids) in SUPPRESSION_TABLE {
            for id in *ids {
                assert!(
                    catalog_ids.contains(id),
                    "SUPPRESSION_TABLE entry for {cat:?} references unknown \
                     check ID `{id}` — either the check was renamed/removed \
                     or the table has a typo. Fix the table, not the \
                     catalog.",
                );
            }
        }
    }
}