agentnative 0.5.0

The agent-native CLI linter — audit 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
//! 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 audits that verify them via `Audit::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,
}

impl Level {
    /// Lowercase RFC-2119 token (`must` / `should` / `may`). Single source
    /// of truth for the scorecard `tier` field and the text-mode tier
    /// suffix, kept in lock-step with the `serde(rename_all = "lowercase")`
    /// spelling so the JSON and text surfaces never disagree on the token.
    pub fn as_str(self) -> &'static str {
        match self {
            Level::Must => "must",
            Level::Should => "should",
            Level::May => "may",
        }
    }
}

/// Whether a requirement applies to every CLI or only when a condition holds.
///
/// `Conditional` carries an optional prose `condition` (legacy `{ if: "<prose>"
/// }` shape) and an optional machine-readable `antecedent` (new `{ kind:
/// conditional, antecedent: { audit_id: ... } }` shape). The antecedent's audit
/// status drives the propagation table documented in
/// `docs/plans/2026-05-21-001-feat-scorecard-fairness-taxonomy-plan.md`
/// Decision 2a: when the antecedent resolves to `opt_out` / `n_a`, this
/// requirement's row in the scorecard collapses to `n_a`; `skip` / `error`
/// inherit; `pass` / `warn` / `fail` let the consequent verifier's own status
/// stand.
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum Applicability {
    Universal,
    Conditional {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        condition: Option<&'static str>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        antecedent: Option<Antecedent>,
    },
}

/// Machine-readable antecedent for a conditional requirement. The
/// `audit_id` names the verifier whose status decides whether the consequent
/// row applies (see `Applicability` for the propagation rules).
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
pub struct Antecedent {
    pub audit_id: &'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 audit 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 audit IDs each exception category suppresses. When a category
/// applies, the listed audits emit `AuditStatus::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 *audit* IDs, not requirement IDs, because the runtime
/// suppression point has `audit.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 audits across layers, the table enumerates every covering
/// audit 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 audit — the drift test below catches the gap.
///
/// Every listed audit 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_audit_ids_exist_in_catalog` test below verifies
/// that every listed audit 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 audits
            // 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
            // audit doesn't match the category's execution model.
            "p6-sigpipe",
            // p6-must-sigterm — same rationale as p6-sigpipe. TUIs install
            // their own SIGTERM handlers to render exit dialogs and save
            // state; the default-disposition audit doesn't match the
            // category's execution model.
            "p6-sigterm",
        ],
    ),
    (
        ExceptionCategory::FileTraversal,
        &[
            // No current audit verifies subcommand-examples or
            // subcommand-operations for tools-without-subcommands. The
            // `If: CLI uses subcommands` applicability on existing audits
            // already produces the right Skip outcome for fd/find-style
            // tools. Kept as a table entry so future audits 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 audit
            // currently covered; read-write-distinction and force-yes are
            // still uncovered in v0.1.3.
            "p5-dry-run",
        ],
    ),
];

/// Whether `audit_id` should be suppressed under the given `category`.
/// Returns `false` for unknown audit 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 audit per invocation.
pub fn suppresses(audit_id: &str, category: ExceptionCategory) -> bool {
    SUPPRESSION_TABLE
        .iter()
        .find(|(cat, _)| *cat == category)
        .is_some_and(|(_, ids)| ids.contains(&audit_id))
}

/// A single spec requirement. The flat registry below is iterated by the
/// matrix generator and cross-referenced against `Audit::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,
}

// REQUIREMENTS and SPEC_VERSION are generated at build time from vendored
// frontmatter under `src/principles/spec/principles/`. See `build.rs` and
// `build_support/parser.rs` for the pipeline; the generated file carries
// its own doc comments for the sort contract and version source.
include!(concat!(env!("OUT_DIR"), "/generated_requirements.rs"));

/// 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..=8).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-05-21: 59 requirements across P1-P8.
        // Bumping this counter is a deliberate act; it means the spec grew.
        assert_eq!(REQUIREMENTS.len(), 59);
    }

    #[test]
    fn level_counts_match_spec() {
        assert_eq!(count_at_level(Level::Must), 28);
        assert_eq!(count_at_level(Level::Should), 21);
        assert_eq!(count_at_level(Level::May), 10);
    }

    #[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() {
        // Audits 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 audit ID is never suppressed.
        assert!(!suppresses(
            "totally-fake-audit-id",
            ExceptionCategory::HumanTui
        ));
        assert!(!suppresses(
            "totally-fake-audit-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_audit_ids_exist_in_catalog() {
        use crate::audit::Audit;
        use crate::audits::all_audits_catalog;

        let catalog: Vec<Box<dyn Audit>> = all_audits_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 \
                     audit ID `{id}` — either the audit was renamed/removed \
                     or the table has a typo. Fix the table, not the \
                     catalog.",
                );
            }
        }
    }

    // ──────────────────────────────────────────────────────────────────
    // U2 (schema 0.6): conditional applicability red-team guards.
    // Each conditional row in the registry names an antecedent `audit_id`
    // that drives propagation. A typo or rename in the antecedent would
    // silently mute propagation in production — the consequent row would
    // forever look up `None` and pass through with its own probe status.
    // The asserts below pin the contract loudly.
    // ──────────────────────────────────────────────────────────────────

    #[test]
    fn every_conditional_antecedent_resolves_to_a_real_audit() {
        use crate::audit::Audit;
        use crate::audits::all_audits_catalog;

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

        let mut dangling: Vec<(&str, &str)> = Vec::new();
        for req in REQUIREMENTS {
            if let Applicability::Conditional {
                antecedent: Some(ante),
                ..
            } = req.applicability
                && !catalog_ids.contains(&ante.audit_id)
            {
                dangling.push((req.id, ante.audit_id));
            }
        }
        assert!(
            dangling.is_empty(),
            "conditional requirements with dangling antecedent audit_ids:\n{}\n\
             Fix the spec's `antecedent.audit_id` or add the missing audit to the catalog.",
            dangling
                .iter()
                .map(|(req, ante)| format!(
                    "  - row `{req}` → antecedent `{ante}` (not in catalog)"
                ))
                .collect::<Vec<_>>()
                .join("\n"),
        );
    }

    #[test]
    fn no_conditional_row_names_itself_as_antecedent() {
        // Edge case: a conditional row's covering audit is the same as its
        // antecedent. The propagation table would then read the row's own
        // probe status and could collapse the row to n_a based on itself —
        // a logic loop that's never the right model. The spec should never
        // produce this shape; this test catches it if it does.
        use crate::audit::Audit;
        use crate::audits::all_audits_catalog;

        let catalog: Vec<Box<dyn Audit>> = all_audits_catalog();
        let mut covers_by_audit: std::collections::HashMap<&'static str, &'static [&'static str]> =
            std::collections::HashMap::new();
        for c in &catalog {
            covers_by_audit.insert(Box::leak(c.id().to_string().into_boxed_str()), c.covers());
        }

        for req in REQUIREMENTS {
            let Applicability::Conditional {
                antecedent: Some(ante),
                ..
            } = req.applicability
            else {
                continue;
            };
            if let Some(covers) = covers_by_audit.get(ante.audit_id) {
                assert!(
                    !covers.contains(&req.id),
                    "conditional row `{}` declares antecedent `{}`, but that \
                     audit already covers `{}` directly — the row would gate \
                     its own status against itself.",
                    req.id,
                    ante.audit_id,
                    req.id,
                );
            }
        }
    }
}