car-verify 0.54.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
//! Verification-gated admission into durable state — evidence *and* an
//! authorised committer.
//!
//! # This is not `car_engine::admission`
//!
//! Say the distinction first, because the two names collide and the objects do
//! not. [`car_engine::AdmissionGate`] runs **before execution** and decides
//! *may these actions run*. This module runs **after** work completes and
//! decides *what from it becomes durable reusable state* — a memory, a skill, a
//! routing rule, a retained failure. Nothing here permits or forbids
//! execution, and nothing in `car-engine` gates a write to the memory graph.
//!
//! Conflating them is easy and was in fact the mistake that produced this
//! module: an earlier draft of `docs/proposals/argus-control-layer.md` treated
//! CAR's execution gate as though it were half of a state gate, concluded CAR
//! only needed "the post-execution half", and deprioritised the write path
//! accordingly. CAR has a mature execution gate and, before this, no state gate
//! at all — `car_memgine`'s `gate_skill_candidates` is the single exception,
//! and it covers skills only.
//!
//! # Two conditions, not one
//!
//! A candidate becomes durable state only when **both** hold:
//!
//! 1. **Evidence.** Its [`EvidenceRequirement`]s are satisfied by the attached
//!    [`VerifierVerdict`]s — delegated wholesale to [`crate::verifier::admit`],
//!    so the evidence rules live in exactly one place.
//! 2. **Authority.** The commit is made by the role that *owns* that state
//!    surface, per a [`SurfaceRule`].
//!
//! Either alone is insufficient, and the failure modes differ. Evidence without
//! authority is a candidate nobody accountable ever accepted. Authority without
//! evidence is a rubber stamp — precisely the thing
//! [`EvidenceRequirement::operator_override`] exists to make deliberate rather
//! than accidental.
//!
//! # Self-commit is a rule, not an accident
//!
//! The producer of a candidate committing its own work is the central hazard.
//! But a blanket ban is the wrong target: requiring an independent reviewer for
//! every low-risk update makes review a bottleneck, and a bottleneck gets
//! disabled. [`SelfCommit`] makes it an explicit per-surface policy —
//! [`SelfCommit::Forbidden`] where independence is mandatory,
//! [`SelfCommit::WithPassingEvidence`] where a producer may self-commit but
//! *only* once every evidence requirement is met. A surface with no
//! requirements and `WithPassingEvidence` is an ungated surface, and
//! [`SurfaceRule::is_ungated`] says so rather than letting it look governed.
//!
//! # What this module is not
//!
//! It stores nothing, commits nothing, and knows nothing about the memory
//! graph. It is the decision procedure a caller consults *before* writing.
//!
//! Its first caller is `car_memgine::MemgineEngine::try_ingest_fact`, which
//! backs the `memory.add_fact` daemon surface. Two properties of that wiring
//! are worth knowing here, because they constrain what this module can assume:
//!
//! - **The gate is off unless a table is installed.** `try_ingest_fact` holds
//!   an `Option<OwnershipTable>` and `None` means "admit everything". That is
//!   not laziness — because [`admit_state`] is fail-closed on an unruled
//!   surface, engaging it implicitly would refuse every memory write on every
//!   existing deployment. It also removed the need for a migration: facts
//!   written before a table existed are never re-examined.
//! - **Only the externally-authored path is gated.** The engine's own derived
//!   writes (consolidation, reflection, distillation) go through the ungated
//!   `ingest_fact`, because they are not the threat model and would deadlock
//!   the runtime against its own rules.
//!
//! Composition with `gate_skill_candidates` is intended to be additive — its
//! Wilson-score bound is *statistical evidence*, one legitimate
//! [`VerifierVerdict`] among others, not a competing mechanism to be replaced.
//! That composition has not shipped: `skills` is one of the surfaces a table
//! can describe but nothing consults yet.
//!
//! [`car_engine::AdmissionGate`]: https://docs.rs/car-engine

use crate::verifier::{
    admit, AdmissionOutcome, EvidenceRequirement, UnmetRequirement, VerifierVerdict,
};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

/// A durable state surface that a mission can update.
///
/// Mirrors the component split CAR already has — the memory graph, the skill
/// library, the tool/procedure registry, verification criteria, routing policy,
/// and task definitions — so a rule table maps onto real subsystems rather than
/// an abstract taxonomy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StateSurface {
    /// Facts, conclusions, and conversation summaries in the memory graph.
    Memory,
    /// Learned procedures in the skill library.
    Skills,
    /// Registered tools and procedures.
    Tools,
    /// Verification criteria — what counts as done for a class of work.
    Verification,
    /// Routing and role policy.
    Routing,
    /// Task and evaluation definitions.
    Tasks,
}

impl StateSurface {
    /// Stable lowercase label, matching the serde representation.
    ///
    /// Matched exhaustively on purpose (project convention #2): a new surface
    /// must fail to compile here rather than silently acquire a label.
    pub const fn as_str(&self) -> &'static str {
        match self {
            StateSurface::Memory => "memory",
            StateSurface::Skills => "skills",
            StateSurface::Tools => "tools",
            StateSurface::Verification => "verification",
            StateSurface::Routing => "routing",
            StateSurface::Tasks => "tasks",
        }
    }
}

/// The authority a role carries when producing or committing a state update.
///
/// Deliberately named for the *function* rather than for any agent job title.
/// CAR has no Manager/Planner/Engineer/Reviewer agents, and importing those
/// names would imply a role system it does not have. What CAR does have is
/// distinguishable call sites — an execution path, a review path, a coordinator
/// that owns the objective, a scheduler, and out-of-band configuration — and
/// those are what this enumerates.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CommitAuthority {
    /// The execution path that produced the candidate — the agent loop, a tool
    /// run, a distillation pass.
    Execution,
    /// Independent inspection of the artifacts and the execution record, by
    /// something that did not produce them.
    Review,
    /// Whatever owns the objective and campaign-level policy.
    Coordination,
    /// Whatever owns the task backlog.
    Scheduling,
    /// Out-of-band configuration — an operator editing config, a signed
    /// package, a deployment.
    SystemConfig,
}

impl CommitAuthority {
    /// Stable lowercase label, matching the serde representation.
    pub const fn as_str(&self) -> &'static str {
        match self {
            CommitAuthority::Execution => "execution",
            CommitAuthority::Review => "review",
            CommitAuthority::Coordination => "coordination",
            CommitAuthority::Scheduling => "scheduling",
            CommitAuthority::SystemConfig => "system_config",
        }
    }
}

/// Whether the producer of a candidate may also commit it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SelfCommit {
    /// Never. An independent committer is mandatory regardless of evidence.
    ///
    /// The right setting where a bad admission is expensive or hard to reverse,
    /// and where "the thing that did the work also declared it good" is the
    /// specific failure being defended against.
    Forbidden,
    /// Permitted, but only when every evidence requirement for the surface is
    /// satisfied.
    ///
    /// This is the escape valve that keeps review from becoming a bottleneck on
    /// routine updates. Note what it is *not*: with an empty requirement list
    /// it degenerates to "anyone may commit anything", which
    /// [`SurfaceRule::is_ungated`] reports rather than hides.
    WithPassingEvidence,
}

/// Who may produce and who may commit updates to one state surface, and what
/// evidence a commit requires.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SurfaceRule {
    /// The surface this rule governs.
    pub surface: StateSurface,
    /// The authority expected to *produce* candidates. A candidate from a
    /// different producer is refused — not because the work is necessarily
    /// wrong, but because a rule table that silently accepts unexpected
    /// producers is not describing the system.
    pub produced_by: CommitAuthority,
    /// The authority required to *commit*.
    pub committed_by: CommitAuthority,
    /// Whether the producer may commit its own candidate.
    pub self_commit: SelfCommit,
    /// Evidence a commit must carry. Empty means none — see
    /// [`SurfaceRule::is_ungated`].
    #[serde(default)]
    pub requires: Vec<EvidenceRequirement>,
}

impl SurfaceRule {
    /// Whether this rule imposes no real constraint: the producer may commit
    /// its own work and no evidence is required.
    ///
    /// Exposed so an operator auditing a rule table can find the surfaces that
    /// only *look* governed. A rule that reaches this state is almost always a
    /// configuration mistake, but it is a legitimate one to hold deliberately —
    /// so this reports rather than forbids.
    pub fn is_ungated(&self) -> bool {
        self.self_commit == SelfCommit::WithPassingEvidence && self.requires.is_empty()
    }
}

/// A candidate update to durable state, awaiting admission.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StateCandidate {
    /// Which surface it would update.
    pub surface: StateSurface,
    /// Stable identity — a fact key, a skill name, a routing rule id. Carried
    /// through to refusals so a rejection names its subject.
    pub id: String,
    /// What produced it.
    pub produced_by: CommitAuthority,
    /// Who is committing it. `None` means nobody has — which is a refusal, not
    /// a pending state: this module answers about a commit that is being
    /// attempted now.
    #[serde(default)]
    pub committed_by: Option<CommitAuthority>,
    /// Evidence attached to the candidate.
    #[serde(default)]
    pub verdicts: Vec<VerifierVerdict>,
}

impl StateCandidate {
    /// A candidate with no evidence and no committer yet.
    pub fn new(surface: StateSurface, id: impl Into<String>, produced_by: CommitAuthority) -> Self {
        Self {
            surface,
            id: id.into(),
            produced_by,
            committed_by: None,
            verdicts: Vec::new(),
        }
    }

    /// Attach evidence.
    pub fn with_verdicts(mut self, verdicts: impl IntoIterator<Item = VerifierVerdict>) -> Self {
        self.verdicts = verdicts.into_iter().collect();
        self
    }

    /// Name the committing authority.
    pub fn committed_by(mut self, who: CommitAuthority) -> Self {
        self.committed_by = Some(who);
        self
    }
}

/// One reason a candidate was refused.
///
/// Refusals accumulate rather than short-circuit: a caller fixing an admission
/// wants every problem at once, not a sequence of single complaints across
/// repeated attempts.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "refusal", rename_all = "snake_case")]
pub enum AdmissionRefusal {
    /// No rule governs this surface. Fail-closed: an ungoverned surface is
    /// refused, never waved through.
    NoRule {
        /// The surface with no rule.
        surface: StateSurface,
    },
    /// Nobody is committing this candidate.
    NotCommitted,
    /// The committer is not the surface's owner.
    WrongCommitter {
        /// Who the rule requires.
        expected: CommitAuthority,
        /// Who attempted it.
        actual: CommitAuthority,
    },
    /// The producer tried to commit its own work where that is forbidden.
    SelfCommitForbidden {
        /// The role that both produced and attempted to commit.
        role: CommitAuthority,
    },
    /// The candidate came from an unexpected producer.
    UnexpectedProducer {
        /// Who the rule expects.
        expected: CommitAuthority,
        /// Who produced it.
        actual: CommitAuthority,
    },
    /// A verifier with authority to decide reported a failure.
    EvidenceRejected {
        /// The failing verifier ids.
        failures: Vec<String>,
    },
    /// Evidence requirements were not met.
    InsufficientEvidence {
        /// Which requirements, and why.
        unmet: Vec<UnmetRequirement>,
    },
}

/// The verdict on a candidate.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct StateAdmission {
    /// Whether the candidate may be written to durable state.
    pub admitted: bool,
    /// The candidate's id, echoed so a decision is attributable without the
    /// caller holding the candidate.
    pub id: String,
    /// The surface it targeted.
    pub surface: StateSurface,
    /// Every reason it was refused. Empty when `admitted`.
    pub refusals: Vec<AdmissionRefusal>,
}

/// A rule table: at most one [`SurfaceRule`] per [`StateSurface`].
///
/// Keyed rather than a list so a surface cannot acquire two contradictory
/// rules — a failure mode that is invisible in a `Vec` until the wrong one
/// wins.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct OwnershipTable {
    rules: BTreeMap<StateSurface, SurfaceRule>,
}

impl OwnershipTable {
    /// An empty table. Every surface is ungoverned, and therefore every
    /// candidate is refused — fail-closed by construction.
    pub fn new() -> Self {
        Self::default()
    }

    /// Insert or replace the rule for a surface.
    pub fn set(&mut self, rule: SurfaceRule) {
        self.rules.insert(rule.surface, rule);
    }

    /// Builder form of [`OwnershipTable::set`].
    pub fn with(mut self, rule: SurfaceRule) -> Self {
        self.set(rule);
        self
    }

    /// The rule governing a surface, if any.
    pub fn rule(&self, surface: StateSurface) -> Option<&SurfaceRule> {
        self.rules.get(&surface)
    }

    /// Every rule, ordered by surface.
    pub fn rules(&self) -> impl Iterator<Item = &SurfaceRule> {
        self.rules.values()
    }

    /// Surfaces whose rule imposes no real constraint — see
    /// [`SurfaceRule::is_ungated`]. For auditing a table before trusting it.
    pub fn ungated_surfaces(&self) -> Vec<StateSurface> {
        self.rules
            .values()
            .filter(|r| r.is_ungated())
            .map(|r| r.surface)
            .collect()
    }
}

/// Decide whether a candidate may enter durable state.
///
/// A decision procedure over its inputs: total, deterministic, order-stable,
/// and free of I/O. It decides *whether this commit satisfies the stated rule*
/// — not whether the candidate is true, useful, or worth keeping. No amount of
/// admission machinery makes a wrong fact right; what it does is ensure a wrong
/// fact arrived with evidence attached and someone accountable attached to it.
///
/// Checks, all evaluated so refusals accumulate:
///
/// 1. **A rule must exist** for the surface. Fail-closed — an ungoverned
///    surface refuses everything rather than admitting everything.
/// 2. **A committer must be named.**
/// 3. **The committer must own the surface**, unless the producer is
///    self-committing under [`SelfCommit::WithPassingEvidence`].
/// 4. **Self-commit must be permitted** when producer and committer coincide.
/// 5. **The producer must be the expected one.**
/// 6. **Evidence must satisfy the rule's requirements**, delegated to
///    [`crate::verifier::admit`] so evidence semantics live in one place. A
///    rejection there (an authoritative verifier failed) and an unmet
///    requirement are reported as distinct refusals, because they call for
///    different responses: more evidence can satisfy a requirement, but it
///    cannot un-fail a check.
pub fn admit_state(table: &OwnershipTable, candidate: &StateCandidate) -> StateAdmission {
    let mut refusals = Vec::new();

    let Some(rule) = table.rule(candidate.surface) else {
        return StateAdmission {
            admitted: false,
            id: candidate.id.clone(),
            surface: candidate.surface,
            refusals: vec![AdmissionRefusal::NoRule {
                surface: candidate.surface,
            }],
        };
    };

    if candidate.produced_by != rule.produced_by {
        refusals.push(AdmissionRefusal::UnexpectedProducer {
            expected: rule.produced_by,
            actual: candidate.produced_by,
        });
    }

    // Evidence first, since the self-commit rule depends on the result.
    let evidence = admit(&rule.requires, &candidate.verdicts);
    match evidence.outcome {
        AdmissionOutcome::Admit => {}
        AdmissionOutcome::Reject => refusals.push(AdmissionRefusal::EvidenceRejected {
            failures: evidence.failures.clone(),
        }),
        AdmissionOutcome::NeedsMoreEvidence => {
            refusals.push(AdmissionRefusal::InsufficientEvidence {
                unmet: evidence.unmet.clone(),
            })
        }
    }
    let evidence_passed = evidence.outcome == AdmissionOutcome::Admit;

    match candidate.committed_by {
        None => refusals.push(AdmissionRefusal::NotCommitted),
        Some(committer) if committer == candidate.produced_by => match rule.self_commit {
            SelfCommit::Forbidden => {
                refusals.push(AdmissionRefusal::SelfCommitForbidden { role: committer })
            }
            SelfCommit::WithPassingEvidence => {
                // Permitted only on passing evidence. When evidence failed, the
                // evidence refusal above already says so — adding a second
                // refusal here would report one problem twice.
                if !evidence_passed && committer != rule.committed_by {
                    refusals.push(AdmissionRefusal::WrongCommitter {
                        expected: rule.committed_by,
                        actual: committer,
                    });
                }
            }
        },
        Some(committer) if committer != rule.committed_by => {
            refusals.push(AdmissionRefusal::WrongCommitter {
                expected: rule.committed_by,
                actual: committer,
            })
        }
        Some(_) => {}
    }

    StateAdmission {
        admitted: refusals.is_empty(),
        id: candidate.id.clone(),
        surface: candidate.surface,
        refusals,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{EvidenceTier, VerifierDescriptor, VerifierOutcome, VerifierVerdict};

    fn tests_pass() -> VerifierVerdict {
        VerifierVerdict::pass(VerifierDescriptor::binding("cargo_test", "tests"))
    }

    fn tests_fail() -> VerifierVerdict {
        VerifierVerdict::fail(
            VerifierDescriptor::binding("cargo_test", "tests"),
            "2 failed",
        )
    }

    /// Memory: produced by execution, committed by review, no self-commit,
    /// requires a passing test verdict.
    fn memory_rule() -> SurfaceRule {
        SurfaceRule {
            surface: StateSurface::Memory,
            produced_by: CommitAuthority::Execution,
            committed_by: CommitAuthority::Review,
            self_commit: SelfCommit::Forbidden,
            requires: vec![EvidenceRequirement::new("tests")],
        }
    }

    /// Tasks: produced by planning-ish execution, committed by the scheduler,
    /// self-commit allowed on passing evidence.
    fn tasks_rule() -> SurfaceRule {
        SurfaceRule {
            surface: StateSurface::Tasks,
            produced_by: CommitAuthority::Execution,
            committed_by: CommitAuthority::Scheduling,
            self_commit: SelfCommit::WithPassingEvidence,
            requires: vec![EvidenceRequirement::new("tests")],
        }
    }

    fn table() -> OwnershipTable {
        OwnershipTable::new().with(memory_rule()).with(tasks_rule())
    }

    #[test]
    fn an_ungoverned_surface_refuses_rather_than_admits() {
        let c = StateCandidate::new(StateSurface::Routing, "r1", CommitAuthority::Coordination)
            .committed_by(CommitAuthority::Coordination);
        let d = admit_state(&table(), &c);
        assert!(!d.admitted);
        assert_eq!(
            d.refusals,
            vec![AdmissionRefusal::NoRule {
                surface: StateSurface::Routing
            }]
        );
    }

    #[test]
    fn an_empty_table_refuses_everything() {
        let c = StateCandidate::new(StateSurface::Memory, "m1", CommitAuthority::Execution)
            .committed_by(CommitAuthority::Review)
            .with_verdicts([tests_pass()]);
        assert!(!admit_state(&OwnershipTable::new(), &c).admitted);
    }

    #[test]
    fn evidence_plus_the_owning_committer_admits() {
        let c = StateCandidate::new(StateSurface::Memory, "m1", CommitAuthority::Execution)
            .committed_by(CommitAuthority::Review)
            .with_verdicts([tests_pass()]);
        let d = admit_state(&table(), &c);
        assert!(d.admitted, "{:?}", d.refusals);
        assert_eq!(d.id, "m1");
        assert_eq!(d.surface, StateSurface::Memory);
    }

    #[test]
    fn authority_without_evidence_is_refused() {
        // The rubber-stamp case: the right committer, nothing to stamp.
        let c = StateCandidate::new(StateSurface::Memory, "m1", CommitAuthority::Execution)
            .committed_by(CommitAuthority::Review);
        let d = admit_state(&table(), &c);
        assert!(!d.admitted);
        assert!(matches!(
            d.refusals.as_slice(),
            [AdmissionRefusal::InsufficientEvidence { .. }]
        ));
    }

    #[test]
    fn evidence_without_a_committer_is_refused() {
        let c = StateCandidate::new(StateSurface::Memory, "m1", CommitAuthority::Execution)
            .with_verdicts([tests_pass()]);
        let d = admit_state(&table(), &c);
        assert!(!d.admitted);
        assert_eq!(d.refusals, vec![AdmissionRefusal::NotCommitted]);
    }

    #[test]
    fn the_wrong_committer_is_refused_even_with_good_evidence() {
        let c = StateCandidate::new(StateSurface::Memory, "m1", CommitAuthority::Execution)
            .committed_by(CommitAuthority::Coordination)
            .with_verdicts([tests_pass()]);
        let d = admit_state(&table(), &c);
        assert!(!d.admitted);
        assert_eq!(
            d.refusals,
            vec![AdmissionRefusal::WrongCommitter {
                expected: CommitAuthority::Review,
                actual: CommitAuthority::Coordination,
            }]
        );
    }

    #[test]
    fn self_commit_is_refused_where_forbidden_however_good_the_evidence() {
        // The central hazard: the thing that did the work declaring it good.
        let c = StateCandidate::new(StateSurface::Memory, "m1", CommitAuthority::Execution)
            .committed_by(CommitAuthority::Execution)
            .with_verdicts([tests_pass()]);
        let d = admit_state(&table(), &c);
        assert!(!d.admitted);
        assert_eq!(
            d.refusals,
            vec![AdmissionRefusal::SelfCommitForbidden {
                role: CommitAuthority::Execution
            }]
        );
    }

    #[test]
    fn self_commit_is_allowed_where_permitted_and_evidence_passes() {
        let c = StateCandidate::new(StateSurface::Tasks, "t1", CommitAuthority::Execution)
            .committed_by(CommitAuthority::Execution)
            .with_verdicts([tests_pass()]);
        let d = admit_state(&table(), &c);
        assert!(d.admitted, "{:?}", d.refusals);
    }

    #[test]
    fn self_commit_without_passing_evidence_is_refused() {
        let c = StateCandidate::new(StateSurface::Tasks, "t1", CommitAuthority::Execution)
            .committed_by(CommitAuthority::Execution);
        let d = admit_state(&table(), &c);
        assert!(!d.admitted);
        // The evidence refusal carries the reason; the committer refusal names
        // who should have committed instead.
        assert!(d.refusals.contains(&AdmissionRefusal::WrongCommitter {
            expected: CommitAuthority::Scheduling,
            actual: CommitAuthority::Execution,
        }));
        assert!(d
            .refusals
            .iter()
            .any(|r| matches!(r, AdmissionRefusal::InsufficientEvidence { .. })));
    }

    #[test]
    fn a_failing_authoritative_verdict_is_reported_as_rejection_not_a_gap() {
        // More evidence can satisfy a requirement; it cannot un-fail a check.
        let c = StateCandidate::new(StateSurface::Memory, "m1", CommitAuthority::Execution)
            .committed_by(CommitAuthority::Review)
            .with_verdicts([tests_fail()]);
        let d = admit_state(&table(), &c);
        assert!(!d.admitted);
        assert_eq!(
            d.refusals,
            vec![AdmissionRefusal::EvidenceRejected {
                failures: vec!["cargo_test".to_string()]
            }]
        );
    }

    #[test]
    fn an_unexpected_producer_is_refused() {
        let c = StateCandidate::new(StateSurface::Memory, "m1", CommitAuthority::SystemConfig)
            .committed_by(CommitAuthority::Review)
            .with_verdicts([tests_pass()]);
        let d = admit_state(&table(), &c);
        assert!(!d.admitted);
        assert!(d.refusals.contains(&AdmissionRefusal::UnexpectedProducer {
            expected: CommitAuthority::Execution,
            actual: CommitAuthority::SystemConfig,
        }));
    }

    #[test]
    fn refusals_accumulate_rather_than_short_circuit() {
        // Wrong producer, wrong committer, no evidence — all three at once.
        let c = StateCandidate::new(StateSurface::Memory, "m1", CommitAuthority::SystemConfig)
            .committed_by(CommitAuthority::Coordination);
        let d = admit_state(&table(), &c);
        assert_eq!(d.refusals.len(), 3, "{:?}", d.refusals);
    }

    #[test]
    fn an_advisory_verdict_cannot_satisfy_a_requirement() {
        // Delegated to `verifier::admit`; asserted here so the delegation is
        // not quietly weakened later.
        let mut judge = VerifierDescriptor::binding("model_judge", "tests");
        judge.authority = crate::VerifierAuthority::Advisory;
        judge.tier = EvidenceTier::Heuristic;
        let c = StateCandidate::new(StateSurface::Memory, "m1", CommitAuthority::Execution)
            .committed_by(CommitAuthority::Review)
            .with_verdicts([VerifierVerdict::pass(judge)]);
        let d = admit_state(&table(), &c);
        assert!(!d.admitted);
        assert!(d
            .refusals
            .iter()
            .any(|r| matches!(r, AdmissionRefusal::InsufficientEvidence { .. })));
    }

    #[test]
    fn a_skipped_verdict_never_satisfies() {
        let mut v = tests_pass();
        v.outcome = VerifierOutcome::Skipped;
        let c = StateCandidate::new(StateSurface::Memory, "m1", CommitAuthority::Execution)
            .committed_by(CommitAuthority::Review)
            .with_verdicts([v]);
        assert!(!admit_state(&table(), &c).admitted);
    }

    #[test]
    fn is_ungated_finds_the_surfaces_that_only_look_governed() {
        let sloppy = SurfaceRule {
            surface: StateSurface::Tools,
            produced_by: CommitAuthority::SystemConfig,
            committed_by: CommitAuthority::SystemConfig,
            self_commit: SelfCommit::WithPassingEvidence,
            requires: Vec::new(),
        };
        assert!(sloppy.is_ungated());
        assert!(!memory_rule().is_ungated());

        let t = table().with(sloppy);
        assert_eq!(t.ungated_surfaces(), vec![StateSurface::Tools]);
    }

    #[test]
    fn an_ungated_rule_does_admit_a_self_commit_with_nothing_attached() {
        // Documents the degenerate case `is_ungated` warns about: it is a real
        // admission, not a refusal, which is exactly why the audit helper
        // exists.
        let t = OwnershipTable::new().with(SurfaceRule {
            surface: StateSurface::Tools,
            produced_by: CommitAuthority::SystemConfig,
            committed_by: CommitAuthority::SystemConfig,
            self_commit: SelfCommit::WithPassingEvidence,
            requires: Vec::new(),
        });
        let c = StateCandidate::new(StateSurface::Tools, "t1", CommitAuthority::SystemConfig)
            .committed_by(CommitAuthority::SystemConfig);
        assert!(admit_state(&t, &c).admitted);
    }

    #[test]
    fn one_surface_cannot_hold_two_contradictory_rules() {
        let mut t = OwnershipTable::new().with(memory_rule());
        let mut replacement = memory_rule();
        replacement.committed_by = CommitAuthority::Coordination;
        t.set(replacement.clone());

        assert_eq!(t.rules().count(), 1);
        assert_eq!(t.rule(StateSurface::Memory), Some(&replacement));
    }

    #[test]
    fn admit_state_is_deterministic() {
        let c = StateCandidate::new(StateSurface::Memory, "m1", CommitAuthority::SystemConfig)
            .committed_by(CommitAuthority::Coordination);
        assert_eq!(admit_state(&table(), &c), admit_state(&table(), &c));
    }

    #[test]
    fn labels_match_serde_representation() {
        assert_eq!(
            serde_json::to_value(StateSurface::Verification).unwrap(),
            serde_json::json!(StateSurface::Verification.as_str())
        );
        assert_eq!(
            serde_json::to_value(CommitAuthority::SystemConfig).unwrap(),
            serde_json::json!(CommitAuthority::SystemConfig.as_str())
        );
    }

    #[test]
    fn a_table_round_trips_through_serde() {
        let t = table();
        let back: OwnershipTable =
            serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
        assert_eq!(back, t);
    }
}