car-verify 0.50.0

Static plan verification for Agent IR
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
//! Pluggable verifier protocol — evidence from checks this crate does not own.
//!
//! [`VerificationEvidence`](crate::VerificationEvidence) already answers "what
//! did the verifier establish, and what did it not?" for the checks
//! [`verify`](crate::verify) runs. Its limitation is that the bundle is
//! **closed**: every [`CheckRecord`] in it is produced by a check compiled into
//! this crate. A proposal whose real correctness argument is "the unit tests
//! pass", "the type checker accepts it", "a human approved it", or "the browser
//! actually showed that page" has no way to say so in the same vocabulary.
//! Those verdicts live outside the runtime, so today they either travel as
//! prose or not at all.
//!
//! This module opens the bundle without weakening it. An external check
//! describes itself with a [`VerifierDescriptor`], reports a
//! [`VerifierVerdict`], and [`admit`] folds those verdicts against a set of
//! [`EvidenceRequirement`]s into one [`AdmissionDecision`]. Verdicts convert to
//! [`CheckRecord`]s via [`VerifierVerdict::to_check_record`], so external
//! evidence lands in the *same* bundle as the built-in checks and is read the
//! same way.
//!
//! # Three axes, deliberately not one
//!
//! The crate already refuses to collapse "how strong is this check?" into "does
//! this describe runtime?" (see [`EvidenceTier`]'s docs). This module keeps
//! that discipline and adds a third axis rather than extending either:
//!
//! - **[`EvidenceTier`]** — the check's relationship to the property it
//!   reports. Reused unchanged; an external verifier declares its tier exactly
//!   as a built-in check does.
//! - **[`VerifierAuthority`]** — *whose word this is*. Whether a verdict may
//!   satisfy a requirement on its own, or is reporting for the record.
//! - **[`VerifierCost`]** — what running it costs the caller, so a scheduler
//!   can order cheap checks first. Carries no weight in [`admit`].
//!
//! Authority is emphatically **not** a strength ranking. A high-authority
//! verdict is not better evidence than a low-authority one; it is a different
//! kind of claim. That distinction is load-bearing in one specific place: an
//! operator approving an action is *not* a substitute for the test suite
//! passing, and [`admit`] will not treat it as one unless the requirement
//! explicitly opts in via [`EvidenceRequirement::operator_override`]. A runtime
//! whose human approval silently satisfies "tests must pass" has re-introduced
//! the failure it was built to prevent.
//!
//! # What this module is not
//!
//! It does not run anything. There is no registry, no dispatch, no I/O — the
//! crate depends on `car-ir` and serde and this module adds nothing to that.
//! It defines the vocabulary and the fold; *invoking* verifiers belongs to the
//! caller that owns the process boundary (`car-engine`'s `AdmissionGate`, the
//! `supervision.*` surface, a CI harness). Slice 1 is the decision procedure so
//! that call sites agree on what a verdict means before any of them ship one.

use crate::{CheckRecord, EvidenceTier};
use serde::{Deserialize, Serialize};
use std::collections::BTreeSet;

/// Whose word a verdict is — and therefore whether it can satisfy a
/// requirement by itself.
///
/// Not an ordering. See the module docs: this axis says what *kind* of claim a
/// verifier makes, not how strong the claim is. `Operator` is last in
/// declaration order because it is the escape hatch, not because it is the
/// best evidence.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum VerifierAuthority {
    /// Reports for the record. An `Advisory` verdict is folded into the
    /// evidence bundle and is visible to a reviewer, but it can never satisfy
    /// an [`EvidenceRequirement`], and an `Advisory` failure does not by itself
    /// reject.
    ///
    /// This is the right authority for anything whose verdict is a signal
    /// rather than a decision: a linter, a model-judge, a similarity score.
    Advisory,
    /// Speaks for the property it checks. A `Binding` pass satisfies a
    /// requirement for its class; a `Binding` failure rejects.
    ///
    /// A verifier earns this when its verdict *is* the answer for its class —
    /// the test suite for `"tests"`, the type checker for `"types"`, a schema
    /// validator for `"schema"`.
    Binding,
    /// A human decision. Satisfies requirements exactly as `Binding` does, and
    /// additionally may stand in for a requirement that sets
    /// [`EvidenceRequirement::operator_override`].
    ///
    /// A failing `Operator` verdict is a refusal and rejects, the same as
    /// `Binding`.
    Operator,
}

impl VerifierAuthority {
    /// Stable lowercase label, matching the serde representation — for logs and
    /// for the FFI/JSON-RPC surfaces, which carry this as a string.
    ///
    /// Matched exhaustively on purpose (project convention #2): a new authority
    /// must fail to compile here rather than silently acquire a label.
    pub const fn as_str(&self) -> &'static str {
        match self {
            VerifierAuthority::Advisory => "advisory",
            VerifierAuthority::Binding => "binding",
            VerifierAuthority::Operator => "operator",
        }
    }

    /// Whether a passing verdict from this authority can satisfy a requirement
    /// for its class. False for [`VerifierAuthority::Advisory`] only.
    pub const fn can_satisfy(&self) -> bool {
        match self {
            VerifierAuthority::Advisory => false,
            VerifierAuthority::Binding | VerifierAuthority::Operator => true,
        }
    }
}

/// Roughly what running a verifier costs, so a caller can order cheap checks
/// before expensive ones and stop early on a rejection.
///
/// Advisory to schedulers; [`admit`] ignores it entirely. Deliberately coarse —
/// a numeric estimate would imply a precision no caller can supply.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum VerifierCost {
    /// Pure computation over data already in hand. Microseconds; no I/O.
    Free,
    /// Local I/O or a short subprocess — a type check, a schema fetch from disk.
    Cheap,
    /// A full test run, a network round trip, a model call, a browser session.
    Expensive,
    /// Blocks on a human. Unbounded in wall-clock time, and the only cost class
    /// a caller must never sit in a hot loop on.
    Human,
}

impl VerifierCost {
    /// Stable lowercase label, matching the serde representation.
    pub const fn as_str(&self) -> &'static str {
        match self {
            VerifierCost::Free => "free",
            VerifierCost::Cheap => "cheap",
            VerifierCost::Expensive => "expensive",
            VerifierCost::Human => "human",
        }
    }
}

/// A verifier's self-description: identity, what kind of check it is, whose
/// word it speaks with, and what it costs.
///
/// `class` is the join key with [`EvidenceRequirement::class`] and is where the
/// vocabulary is agreed. Callers should treat it as a stable, lowercase,
/// snake-case identifier for the *kind* of evidence produced (`"tests"`,
/// `"types"`, `"schema"`, `"browser_evidence"`, `"human_review"`) — not for the
/// particular tool that produced it, which is `id`. Two verifiers of the same
/// class are interchangeable for admission; that is the whole point of the
/// field.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VerifierDescriptor {
    /// Stable identity of this specific verifier, e.g. `"cargo_test"`,
    /// `"tsc"`, `"operator_console"`. Appears on the [`CheckRecord`] so a
    /// verdict is attributable.
    pub id: String,
    /// The kind of evidence produced, e.g. `"tests"`. Joins with
    /// [`EvidenceRequirement::class`].
    pub class: String,
    /// What kind of check this is, in the crate's existing taxonomy. An
    /// external verifier declares this exactly as a built-in check does.
    pub tier: EvidenceTier,
    /// Whose word this verifier's verdict is.
    pub authority: VerifierAuthority,
    /// What running it costs.
    pub cost: VerifierCost,
    /// Whether repeating the verifier on identical inputs yields an identical
    /// verdict.
    ///
    /// Distinct from `tier`: a decision procedure is deterministic, but a
    /// [`EvidenceTier::Sampled`] check may or may not be (a fixed-seed sampler
    /// is; a model judge is not), and a flaky test suite is a
    /// [`EvidenceTier::DecisionProcedure`] that is *not*. Callers that cache or
    /// replay verdicts must consult this and not infer it from the tier.
    pub deterministic: bool,
}

impl VerifierDescriptor {
    /// A deterministic, free, binding decision procedure — the common shape for
    /// an in-process structural check. Adjust the fields that differ.
    pub fn binding(id: impl Into<String>, class: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            class: class.into(),
            tier: EvidenceTier::DecisionProcedure,
            authority: VerifierAuthority::Binding,
            cost: VerifierCost::Free,
            deterministic: true,
        }
    }
}

/// What a verifier found.
///
/// The two non-committal variants are separate on purpose: `Skipped` means the
/// verifier never ran, `Inconclusive` means it ran and could not decide. Both
/// fail to satisfy a requirement, but they call for different responses — a
/// skip is usually a configuration gap the caller can close, an inconclusive
/// result usually is not.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum VerifierOutcome {
    /// The verifier ran and the property holds.
    Pass,
    /// The verifier ran and the property does not hold.
    Fail,
    /// The verifier ran and could not decide — a timeout, a partial result, a
    /// judge below its confidence floor.
    Inconclusive,
    /// The verifier did not run — not configured, not applicable, budget
    /// exhausted.
    Skipped,
}

impl VerifierOutcome {
    /// Stable lowercase label, matching the serde representation.
    pub const fn as_str(&self) -> &'static str {
        match self {
            VerifierOutcome::Pass => "pass",
            VerifierOutcome::Fail => "fail",
            VerifierOutcome::Inconclusive => "inconclusive",
            VerifierOutcome::Skipped => "skipped",
        }
    }
}

/// One verifier's report on one proposal.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VerifierVerdict {
    /// Who reported.
    pub verifier: VerifierDescriptor,
    /// What they found.
    pub outcome: VerifierOutcome,
    /// Human-readable summary — the failing test name, the type error, the
    /// operator's stated reason.
    #[serde(default)]
    pub detail: String,
    /// What a pass of this verifier establishes. Becomes
    /// [`CheckRecord::verifies`].
    #[serde(default)]
    pub verifies: String,
    /// The scope boundary — what a pass does *not* establish. Becomes
    /// [`CheckRecord::cannot_verify`], the crate's anti-overconfidence signal.
    ///
    /// An external verifier that leaves this empty is claiming its pass has no
    /// blind spots, which is almost never true. [`admit`] does not enforce a
    /// value here, but reviewers should read an empty one as unstated rather
    /// than as none.
    #[serde(default)]
    pub cannot_verify: String,
    /// References to supporting material — a log path, an artifact URL, a
    /// commit SHA, a screenshot id. Opaque to this crate.
    #[serde(default)]
    pub artifacts: Vec<String>,
}

impl VerifierVerdict {
    /// A passing verdict with no detail — for the common case and for tests.
    pub fn pass(verifier: VerifierDescriptor) -> Self {
        Self {
            verifier,
            outcome: VerifierOutcome::Pass,
            detail: String::new(),
            verifies: String::new(),
            cannot_verify: String::new(),
            artifacts: Vec::new(),
        }
    }

    /// A failing verdict carrying its reason.
    pub fn fail(verifier: VerifierDescriptor, detail: impl Into<String>) -> Self {
        Self {
            verifier,
            outcome: VerifierOutcome::Fail,
            detail: detail.into(),
            verifies: String::new(),
            cannot_verify: String::new(),
            artifacts: Vec::new(),
        }
    }

    /// Fold this verdict into the crate's existing evidence vocabulary, so
    /// external checks appear in [`VerificationEvidence::checks`] beside the
    /// built-in ones.
    ///
    /// [`CheckRecord::ran`] is false exactly for [`VerifierOutcome::Skipped`].
    /// [`CheckRecord::findings`] is 1 for a failure and 0 otherwise — a
    /// verifier reports one property, so a failure is one finding.
    ///
    /// [`VerificationEvidence`]: crate::VerificationEvidence
    /// [`VerificationEvidence::checks`]: crate::VerificationEvidence::checks
    pub fn to_check_record(&self) -> CheckRecord {
        CheckRecord {
            name: self.verifier.id.clone(),
            ran: self.outcome != VerifierOutcome::Skipped,
            verifies: self.verifies.clone(),
            cannot_verify: self.cannot_verify.clone(),
            findings: usize::from(self.outcome == VerifierOutcome::Fail),
            tier: self.verifier.tier,
        }
    }
}

/// A class of evidence a proposal must carry before it may be admitted.
///
/// Requirements are *conjunctive*: every one must be met. A proposal with no
/// requirements is admitted on the absence of failures alone, which is the
/// pre-existing behaviour and keeps this purely additive.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EvidenceRequirement {
    /// The verifier class that must report a pass. Joins with
    /// [`VerifierDescriptor::class`].
    pub class: String,
    /// Tiers accepted as satisfying this requirement. Empty ⇒ any tier.
    ///
    /// This is how a caller says "a model judge does not count as the test
    /// suite": require `class = "tests"` and
    /// `accepts_tiers = [DecisionProcedure]`, and a
    /// [`EvidenceTier::Heuristic`] verdict of the same class will not satisfy
    /// it. Because [`EvidenceTier`] carries no ordering, this is an explicit
    /// membership set rather than a minimum.
    #[serde(default)]
    pub accepts_tiers: Vec<EvidenceTier>,
    /// Whether a passing [`VerifierAuthority::Operator`] verdict — of *any*
    /// class — satisfies this requirement in place of a class verdict.
    ///
    /// Defaults to false, and the default is the point. A human clicking
    /// approve is a decision to proceed, not a demonstration that the tests
    /// pass; letting it silently satisfy a `"tests"` requirement converts the
    /// requirement into a formality. Set it true only where a human genuinely
    /// *is* the intended authority for the class.
    #[serde(default)]
    pub operator_override: bool,
}

impl EvidenceRequirement {
    /// Require a passing verdict of `class` from any tier, with no operator
    /// override.
    pub fn new(class: impl Into<String>) -> Self {
        Self {
            class: class.into(),
            accepts_tiers: Vec::new(),
            operator_override: false,
        }
    }

    /// Restrict which tiers satisfy this requirement.
    pub fn accepting(mut self, tiers: impl IntoIterator<Item = EvidenceTier>) -> Self {
        self.accepts_tiers = tiers.into_iter().collect();
        self
    }

    /// Allow a passing operator verdict to stand in for a class verdict. See
    /// the field docs before reaching for this.
    pub fn with_operator_override(mut self) -> Self {
        self.operator_override = true;
        self
    }

    /// Whether this requirement accepts `tier`.
    fn accepts(&self, tier: EvidenceTier) -> bool {
        self.accepts_tiers.is_empty() || self.accepts_tiers.contains(&tier)
    }
}

/// Why a requirement was not met — the actionable half of a
/// [`AdmissionOutcome::NeedsMoreEvidence`] decision.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub enum UnmetReason {
    /// No verdict of this class was supplied at all.
    NoVerdict,
    /// A verdict of this class exists but did not pass, or came from a verifier
    /// whose authority cannot satisfy a requirement, or carried a tier the
    /// requirement does not accept. `detail` names which.
    NotSatisfying {
        /// Human-readable account of the closest verdicts and why each fell
        /// short.
        detail: String,
    },
}

/// One unmet [`EvidenceRequirement`], paired with why.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct UnmetRequirement {
    /// The class that went unsatisfied.
    pub class: String,
    /// Why.
    pub reason: UnmetReason,
}

/// The verdict of the fold.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum AdmissionOutcome {
    /// Every requirement is met and nothing with authority failed.
    Admit,
    /// A verifier with authority reported a failure. Terminal for this
    /// proposal: gathering more evidence does not clear a failure.
    Reject,
    /// Nothing failed, but at least one requirement is unmet. Running the
    /// missing verifiers may change this to [`AdmissionOutcome::Admit`].
    NeedsMoreEvidence,
}

impl AdmissionOutcome {
    /// Stable lowercase label, matching the serde representation.
    pub const fn as_str(&self) -> &'static str {
        match self {
            AdmissionOutcome::Admit => "admit",
            AdmissionOutcome::Reject => "reject",
            AdmissionOutcome::NeedsMoreEvidence => "needs_more_evidence",
        }
    }
}

/// The result of folding verdicts against requirements.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct AdmissionDecision {
    /// What to do.
    pub outcome: AdmissionOutcome,
    /// Requirements that were not met, in the order the requirements were
    /// given. Empty unless `outcome` is [`AdmissionOutcome::NeedsMoreEvidence`].
    pub unmet: Vec<UnmetRequirement>,
    /// Ids of verifiers that reported [`VerifierOutcome::Fail`] with an
    /// authority that can reject, in the order the verdicts were given.
    pub failures: Vec<String>,
    /// Ids of verifiers that failed with [`VerifierAuthority::Advisory`] — did
    /// not reject, but a reviewer should see them.
    pub advisories: Vec<String>,
    /// Every verdict rendered as a [`CheckRecord`], ready to append to
    /// [`VerificationEvidence::checks`].
    ///
    /// [`VerificationEvidence::checks`]: crate::VerificationEvidence::checks
    pub records: Vec<CheckRecord>,
}

/// Fold verifier verdicts against evidence requirements into one decision.
///
/// A decision procedure over its fragment: total, deterministic, order-stable,
/// and free of I/O. It decides *whether the supplied evidence meets the stated
/// requirements* — not whether the proposal is correct. The gap between those
/// two is exactly what each verdict's [`VerifierVerdict::cannot_verify`]
/// describes, which is why the fold carries those strings through to
/// `records` rather than discarding them once a requirement is satisfied.
///
/// The rules, in precedence order:
///
/// 1. **A failure with authority rejects.** Any [`VerifierOutcome::Fail`] from
///    a [`VerifierAuthority::Binding`] or [`VerifierAuthority::Operator`]
///    verifier yields [`AdmissionOutcome::Reject`], regardless of requirements.
///    Rejection wins over unmet requirements because it is terminal: more
///    evidence can satisfy a requirement, but it cannot un-fail a check.
/// 2. **An advisory failure records but does not reject** — collected into
///    [`AdmissionDecision::advisories`].
/// 3. **A requirement is met** by at least one verdict that passed, whose
///    verifier's authority [`VerifierAuthority::can_satisfy`], and whose tier
///    the requirement accepts — matched on `class`; or, when the requirement
///    sets [`EvidenceRequirement::operator_override`], by any passing
///    [`VerifierAuthority::Operator`] verdict whose tier is accepted.
/// 4. **Anything unmet** yields [`AdmissionOutcome::NeedsMoreEvidence`].
/// 5. **Otherwise admit.**
///
/// Fail-closed throughout, matching `car-engine`'s admission posture:
/// [`VerifierOutcome::Inconclusive`] and [`VerifierOutcome::Skipped`] never
/// satisfy anything, and a requirement with no matching verdict is unmet rather
/// than vacuously true.
///
/// # Examples
///
/// ```
/// use car_verify::{admit, AdmissionOutcome, EvidenceRequirement, EvidenceTier,
///                  VerifierDescriptor, VerifierVerdict};
///
/// // "The test suite must pass, and a model judge's opinion does not count."
/// let req = EvidenceRequirement::new("tests").accepting([EvidenceTier::DecisionProcedure]);
/// let verdict = VerifierVerdict::pass(VerifierDescriptor::binding("cargo_test", "tests"));
///
/// let decision = admit(&[req], &[verdict]);
/// assert_eq!(decision.outcome, AdmissionOutcome::Admit);
/// // `decision.records` folds straight into `VerificationEvidence.checks`.
/// assert_eq!(decision.records.len(), 1);
/// ```
///
/// A human approving is not the suite passing:
///
/// ```
/// use car_verify::{admit, AdmissionOutcome, EvidenceRequirement, VerifierAuthority,
///                  VerifierCost, VerifierDescriptor, VerifierOutcome, VerifierVerdict,
///                  EvidenceTier};
///
/// let operator = VerifierDescriptor {
///     id: "operator_console".into(),
///     class: "human_review".into(),
///     tier: EvidenceTier::DecisionProcedure,
///     authority: VerifierAuthority::Operator,
///     cost: VerifierCost::Human,
///     deterministic: false,
/// };
///
/// let decision = admit(
///     &[EvidenceRequirement::new("tests")],
///     &[VerifierVerdict::pass(operator.clone())],
/// );
/// assert_eq!(decision.outcome, AdmissionOutcome::NeedsMoreEvidence);
///
/// // ...unless the requirement explicitly opts in.
/// let decision = admit(
///     &[EvidenceRequirement::new("tests").with_operator_override()],
///     &[VerifierVerdict::pass(operator)],
/// );
/// assert_eq!(decision.outcome, AdmissionOutcome::Admit);
/// # let _ = VerifierOutcome::Pass;
/// ```
pub fn admit(
    requirements: &[EvidenceRequirement],
    verdicts: &[VerifierVerdict],
) -> AdmissionDecision {
    let records: Vec<CheckRecord> = verdicts.iter().map(|v| v.to_check_record()).collect();

    let mut failures = Vec::new();
    let mut advisories = Vec::new();
    for v in verdicts {
        if v.outcome != VerifierOutcome::Fail {
            continue;
        }
        if v.verifier.authority.can_satisfy() {
            failures.push(v.verifier.id.clone());
        } else {
            advisories.push(v.verifier.id.clone());
        }
    }

    if !failures.is_empty() {
        return AdmissionDecision {
            outcome: AdmissionOutcome::Reject,
            unmet: Vec::new(),
            failures,
            advisories,
            records,
        };
    }

    let mut unmet = Vec::new();
    for req in requirements {
        if requirement_met(req, verdicts) {
            continue;
        }
        unmet.push(UnmetRequirement {
            class: req.class.clone(),
            reason: unmet_reason(req, verdicts),
        });
    }

    let outcome = if unmet.is_empty() {
        AdmissionOutcome::Admit
    } else {
        AdmissionOutcome::NeedsMoreEvidence
    };

    AdmissionDecision {
        outcome,
        unmet,
        failures,
        advisories,
        records,
    }
}

/// Whether any verdict satisfies `req`. See [`admit`] rule 3.
fn requirement_met(req: &EvidenceRequirement, verdicts: &[VerifierVerdict]) -> bool {
    verdicts.iter().any(|v| {
        if v.outcome != VerifierOutcome::Pass || !req.accepts(v.verifier.tier) {
            return false;
        }
        let class_match = v.verifier.class == req.class && v.verifier.authority.can_satisfy();
        let operator_stand_in =
            req.operator_override && v.verifier.authority == VerifierAuthority::Operator;
        class_match || operator_stand_in
    })
}

/// Explain why `req` went unmet, naming the near misses. Pure formatting over
/// the same inputs [`requirement_met`] rejected.
fn unmet_reason(req: &EvidenceRequirement, verdicts: &[VerifierVerdict]) -> UnmetReason {
    let near: Vec<&VerifierVerdict> = verdicts
        .iter()
        .filter(|v| v.verifier.class == req.class)
        .collect();
    if near.is_empty() {
        return UnmetReason::NoVerdict;
    }
    let detail = near
        .iter()
        .map(|v| {
            let why = if v.outcome != VerifierOutcome::Pass {
                format!("outcome {}", v.outcome.as_str())
            } else if !v.verifier.authority.can_satisfy() {
                format!("authority {} cannot satisfy", v.verifier.authority.as_str())
            } else {
                format!("tier {} not accepted", v.verifier.tier.as_str())
            };
            format!("{} ({})", v.verifier.id, why)
        })
        .collect::<Vec<_>>()
        .join("; ");
    UnmetReason::NotSatisfying { detail }
}

/// The distinct verifier classes named by a requirement set, deduplicated and
/// sorted — what a caller must arrange to run.
///
/// Sorted rather than insertion-ordered so that a caller can compare two
/// requirement sets, or key a cache on the result, without depending on how the
/// requirements happened to be assembled.
pub fn required_classes(requirements: &[EvidenceRequirement]) -> Vec<String> {
    requirements
        .iter()
        .map(|r| r.class.clone())
        .collect::<BTreeSet<_>>()
        .into_iter()
        .collect()
}

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

    fn tests_verifier() -> VerifierDescriptor {
        VerifierDescriptor {
            id: "cargo_test".into(),
            class: "tests".into(),
            tier: EvidenceTier::DecisionProcedure,
            authority: VerifierAuthority::Binding,
            cost: VerifierCost::Expensive,
            deterministic: true,
        }
    }

    fn judge_verifier() -> VerifierDescriptor {
        VerifierDescriptor {
            id: "model_judge".into(),
            class: "tests".into(),
            tier: EvidenceTier::Heuristic,
            authority: VerifierAuthority::Advisory,
            cost: VerifierCost::Expensive,
            deterministic: false,
        }
    }

    fn operator() -> VerifierDescriptor {
        VerifierDescriptor {
            id: "operator_console".into(),
            class: "human_review".into(),
            tier: EvidenceTier::DecisionProcedure,
            authority: VerifierAuthority::Operator,
            cost: VerifierCost::Human,
            deterministic: false,
        }
    }

    #[test]
    fn no_requirements_and_no_failures_admits() {
        let d = admit(&[], &[]);
        assert_eq!(d.outcome, AdmissionOutcome::Admit);
        assert!(d.unmet.is_empty());
        assert!(d.records.is_empty());
    }

    #[test]
    fn missing_verdict_needs_more_evidence_not_admit() {
        let d = admit(&[EvidenceRequirement::new("tests")], &[]);
        assert_eq!(d.outcome, AdmissionOutcome::NeedsMoreEvidence);
        assert_eq!(d.unmet.len(), 1);
        assert_eq!(d.unmet[0].class, "tests");
        assert_eq!(d.unmet[0].reason, UnmetReason::NoVerdict);
    }

    #[test]
    fn binding_pass_satisfies_its_class() {
        let d = admit(
            &[EvidenceRequirement::new("tests")],
            &[VerifierVerdict::pass(tests_verifier())],
        );
        assert_eq!(d.outcome, AdmissionOutcome::Admit);
    }

    #[test]
    fn binding_failure_rejects() {
        let d = admit(
            &[],
            &[VerifierVerdict::fail(tests_verifier(), "3 tests failed")],
        );
        assert_eq!(d.outcome, AdmissionOutcome::Reject);
        assert_eq!(d.failures, vec!["cargo_test".to_string()]);
    }

    #[test]
    fn rejection_wins_over_unmet_requirements() {
        // A failure is terminal; more evidence cannot un-fail it. The unmet
        // list is suppressed so a caller cannot read a Reject as "keep going".
        let d = admit(
            &[EvidenceRequirement::new("types")],
            &[VerifierVerdict::fail(tests_verifier(), "boom")],
        );
        assert_eq!(d.outcome, AdmissionOutcome::Reject);
        assert!(d.unmet.is_empty());
    }

    #[test]
    fn advisory_failure_records_but_does_not_reject() {
        let d = admit(
            &[],
            &[VerifierVerdict::fail(judge_verifier(), "looks wrong to me")],
        );
        assert_eq!(d.outcome, AdmissionOutcome::Admit);
        assert!(d.failures.is_empty());
        assert_eq!(d.advisories, vec!["model_judge".to_string()]);
    }

    #[test]
    fn advisory_pass_cannot_satisfy_a_requirement() {
        let d = admit(
            &[EvidenceRequirement::new("tests")],
            &[VerifierVerdict::pass(judge_verifier())],
        );
        assert_eq!(d.outcome, AdmissionOutcome::NeedsMoreEvidence);
        match &d.unmet[0].reason {
            UnmetReason::NotSatisfying { detail } => {
                assert!(detail.contains("model_judge"), "{detail}");
                assert!(detail.contains("cannot satisfy"), "{detail}");
            }
            other => panic!("expected NotSatisfying, got {other:?}"),
        }
    }

    #[test]
    fn tier_restriction_excludes_a_same_class_pass() {
        // "A model judge does not count as the test suite" — same class, wrong
        // tier. Requires a Binding heuristic so the rejection is attributable
        // to the tier and not to the authority.
        let mut heuristic_but_binding = judge_verifier();
        heuristic_but_binding.authority = VerifierAuthority::Binding;
        let req = EvidenceRequirement::new("tests").accepting([EvidenceTier::DecisionProcedure]);
        let d = admit(&[req], &[VerifierVerdict::pass(heuristic_but_binding)]);
        assert_eq!(d.outcome, AdmissionOutcome::NeedsMoreEvidence);
        match &d.unmet[0].reason {
            UnmetReason::NotSatisfying { detail } => {
                assert!(detail.contains("tier heuristic not accepted"), "{detail}")
            }
            other => panic!("expected NotSatisfying, got {other:?}"),
        }
    }

    #[test]
    fn operator_approval_does_not_silently_satisfy_a_test_requirement() {
        // The load-bearing default: a human approving is not the suite passing.
        let d = admit(
            &[EvidenceRequirement::new("tests")],
            &[VerifierVerdict::pass(operator())],
        );
        assert_eq!(d.outcome, AdmissionOutcome::NeedsMoreEvidence);
        assert_eq!(d.unmet[0].reason, UnmetReason::NoVerdict);
    }

    #[test]
    fn operator_override_is_opt_in_and_then_works() {
        let req = EvidenceRequirement::new("tests").with_operator_override();
        let d = admit(&[req], &[VerifierVerdict::pass(operator())]);
        assert_eq!(d.outcome, AdmissionOutcome::Admit);
    }

    #[test]
    fn operator_override_still_respects_the_tier_filter() {
        let mut sampled_operator = operator();
        sampled_operator.tier = EvidenceTier::Sampled;
        let req = EvidenceRequirement::new("tests")
            .with_operator_override()
            .accepting([EvidenceTier::DecisionProcedure]);
        let d = admit(&[req], &[VerifierVerdict::pass(sampled_operator)]);
        assert_eq!(d.outcome, AdmissionOutcome::NeedsMoreEvidence);
    }

    #[test]
    fn operator_failure_rejects() {
        let d = admit(&[], &[VerifierVerdict::fail(operator(), "not authorized")]);
        assert_eq!(d.outcome, AdmissionOutcome::Reject);
        assert_eq!(d.failures, vec!["operator_console".to_string()]);
    }

    #[test]
    fn inconclusive_and_skipped_never_satisfy() {
        for outcome in [VerifierOutcome::Inconclusive, VerifierOutcome::Skipped] {
            let mut v = VerifierVerdict::pass(tests_verifier());
            v.outcome = outcome;
            let d = admit(&[EvidenceRequirement::new("tests")], &[v]);
            assert_eq!(
                d.outcome,
                AdmissionOutcome::NeedsMoreEvidence,
                "{} satisfied a requirement",
                outcome.as_str()
            );
        }
    }

    #[test]
    fn requirements_are_conjunctive() {
        let reqs = [
            EvidenceRequirement::new("tests"),
            EvidenceRequirement::new("types"),
        ];
        let d = admit(&reqs, &[VerifierVerdict::pass(tests_verifier())]);
        assert_eq!(d.outcome, AdmissionOutcome::NeedsMoreEvidence);
        assert_eq!(d.unmet.len(), 1);
        assert_eq!(d.unmet[0].class, "types");

        let types = VerifierDescriptor::binding("tsc", "types");
        let d = admit(
            &reqs,
            &[
                VerifierVerdict::pass(tests_verifier()),
                VerifierVerdict::pass(types),
            ],
        );
        assert_eq!(d.outcome, AdmissionOutcome::Admit);
    }

    #[test]
    fn verdicts_become_check_records_carrying_their_scope() {
        let mut v = VerifierVerdict::pass(tests_verifier());
        v.verifies = "the suite passes on this revision".into();
        v.cannot_verify = "behaviour on inputs the suite does not cover".into();
        let d = admit(&[], &[v]);

        assert_eq!(d.records.len(), 1);
        let r = &d.records[0];
        assert_eq!(r.name, "cargo_test");
        assert!(r.ran);
        assert_eq!(r.findings, 0);
        assert_eq!(r.tier, EvidenceTier::DecisionProcedure);
        assert_eq!(
            r.cannot_verify,
            "behaviour on inputs the suite does not cover"
        );
    }

    #[test]
    fn skipped_verdict_records_as_not_run_and_a_failure_counts_one_finding() {
        let mut skipped = VerifierVerdict::pass(tests_verifier());
        skipped.outcome = VerifierOutcome::Skipped;
        assert!(!skipped.to_check_record().ran);
        assert_eq!(skipped.to_check_record().findings, 0);

        let failed = VerifierVerdict::fail(tests_verifier(), "boom");
        assert!(failed.to_check_record().ran);
        assert_eq!(failed.to_check_record().findings, 1);
    }

    #[test]
    fn records_are_emitted_even_on_rejection() {
        // The bundle is the audit trail; a rejected proposal needs it most.
        let d = admit(
            &[],
            &[
                VerifierVerdict::fail(tests_verifier(), "boom"),
                VerifierVerdict::pass(VerifierDescriptor::binding("tsc", "types")),
            ],
        );
        assert_eq!(d.outcome, AdmissionOutcome::Reject);
        assert_eq!(d.records.len(), 2);
    }

    #[test]
    fn required_classes_dedupes_and_sorts() {
        let reqs = [
            EvidenceRequirement::new("types"),
            EvidenceRequirement::new("tests"),
            EvidenceRequirement::new("types"),
        ];
        assert_eq!(required_classes(&reqs), vec!["tests", "types"]);
    }

    #[test]
    fn admit_is_deterministic_and_order_stable() {
        let reqs = [EvidenceRequirement::new("tests")];
        let verdicts = [
            VerifierVerdict::fail(judge_verifier(), "a"),
            VerifierVerdict::pass(tests_verifier()),
        ];
        let first = admit(&reqs, &verdicts);
        let second = admit(&reqs, &verdicts);
        assert_eq!(first, second);
        assert_eq!(first.outcome, AdmissionOutcome::Admit);
        assert_eq!(first.advisories, vec!["model_judge".to_string()]);
    }

    #[test]
    fn labels_match_serde_representation() {
        assert_eq!(
            serde_json::to_value(VerifierAuthority::Operator).unwrap(),
            serde_json::json!(VerifierAuthority::Operator.as_str())
        );
        assert_eq!(
            serde_json::to_value(VerifierCost::Human).unwrap(),
            serde_json::json!(VerifierCost::Human.as_str())
        );
        assert_eq!(
            serde_json::to_value(VerifierOutcome::Inconclusive).unwrap(),
            serde_json::json!(VerifierOutcome::Inconclusive.as_str())
        );
        assert_eq!(
            serde_json::to_value(AdmissionOutcome::NeedsMoreEvidence).unwrap(),
            serde_json::json!(AdmissionOutcome::NeedsMoreEvidence.as_str())
        );
    }
}