boundgraph-check 0.1.0

Layer 5 of BoundGraph: the checker engine and the ed25519 signing that makes a verdict evidence.
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
//! The contract every checker meets, and the machinery that makes it hold.
//!
//! # What a checker is for
//!
//! Law III: model output is a proposal, never ground truth. Something has to
//! decide whether the proposal may commit, and that something must not itself
//! be a model — otherwise the guarantee is circular and the whole engine is an
//! elaborate way of asking a language model twice.
//!
//! A [`Checker`] is that decider. It takes the proposal ([`WorkOrder`]) and what
//! actually happened ([`Condensate`]), and returns a verdict. It is the only
//! thing in BoundGraph whose answer can cause a state change.
//!
//! # Why `check` is a provided method
//!
//! An implementation writes [`judge`](Checker::judge) and never touches the
//! rest. [`check`](Checker::check) wraps it and does three things the
//! implementation is not trusted to do for itself:
//!
//! 1. **Refuses a checker that holds too much authority**, before it runs.
//! 2. **Binds the verdict to what was checked**, by putting the digests of the
//!    work order and the condensate into the evidence itself.
//! 3. **Signs**, or fails.
//!
//! Every one of those is a property the system relies on across *all* checkers,
//! and a guarantee spread across implementations is a guarantee that the sixth
//! implementation breaks. This is the same reason `Slicer::condense` is a
//! provided method in feature 07.
//!
//! # A checker cannot call a reasoner
//!
//! Not by convention, and not by code review. By its capability set.
//!
//! [`Checker::grants`] declares what the checker needs, and `check` refuses to
//! run one whose declaration is not within [`checker_ceiling`]. The ceiling
//! omits `net` and `secret`, which are the only two ways to reach a model
//! provider: no egress, no API key, no inference. It also omits `time` and
//! `rand`, which is the same mechanism enforcing the determinism requirement,
//! and `fs:write`, so a checker cannot alter the thing it is judging.
//!
//! An undecidable comparison is a refusal, not a pass — [`Tri::Unknown`] is
//! treated exactly as feature 02 treats it everywhere else.
//!
//! # A checker has no failure channel except its verdict
//!
//! [`judge`](Checker::judge) returns a [`Judgement`], not a `Result`. That is
//! deliberate and it is the point of the three-valued [`Verdict`]: a checker
//! whose compiler crashed, whose test run timed out, or whose input was not
//! what it expected returns [`Verdict::Inconclusive`], which never commits.
//!
//! Had `judge` been fallible there would be two ways to say "no answer" — an
//! `Err` and an `Inconclusive` — and somewhere a caller would handle the `Err`
//! by logging it and carrying on. There is no such caller here because there is
//! no such `Err`.
//!
//! [`CheckError`] exists for the two things that are *not* a checker's opinion:
//! a checker that declared authority it may not hold, and a signature that
//! could not be produced. Neither yields evidence, so neither commits.
//!
//! # Determinism
//!
//! A checker is a pure function of `(work order, condensate)`. No clock, no
//! randomness, no iteration over a hashed collection, no network. Replay
//! (US-1006) re-runs a recorded check and compares the evidence byte for byte,
//! and ed25519 signatures are themselves deterministic, so the whole pipeline
//! from inputs to signature reproduces — which is what makes a cassette test
//! (US-1008) able to assert that a verdict did not change.
//!
//! [`Tri::Unknown`]: boundgraph_grant::Tri

use std::fmt;

use async_trait::async_trait;
use boundgraph_core::{
    Canonical, CheckerId, Condensate, Digest, Evidence, EvidenceKind, GrantSet, Verdict, WorkOrder,
};
use boundgraph_grant::{Tri, set_leq};

use crate::sign::{Sign, SignError, sign_evidence};

/// The widest authority any checker may hold.
///
/// | Included | Why |
/// |---|---|
/// | `fs:read:**`, `fs:list:**`, `fs:stat:**` | A checker has to see what it is judging. |
/// | `proc:exec:**` | The useful checkers shell out — a compiler, a type checker, a test runner. |
///
/// What is left out matters more than what is in:
///
/// - **No `net`.** A checker cannot reach an inference API, so it cannot ask a
///   model what it thinks. This is the mechanism behind "model-free", and it is
///   why the claim survives a checker author who did not read the docs.
/// - **No `secret`.** No API key, so no credential to reach one with even if
///   egress were somehow available.
/// - **No `time`, no `rand`.** The two ordinary sources of a verdict that
///   differs between two runs over identical inputs.
/// - **No `fs:write`.** A checker that could edit the workspace could make its
///   own verdict true.
///
/// `proc:exec` is the one wide grant, and it is wide honestly: a subprocess can
/// do whatever the sandbox lets it. Confining the child is feature 09's job,
/// which is exactly the division `ARCHITECTURE.md` §3 draws — this crate
/// decides *what authority is legitimate*, the sandbox decides *what is
/// actually possible*.
pub fn checker_ceiling() -> GrantSet {
    GrantSet::parse(["fs:read:**", "fs:list:**", "fs:stat:**", "proc:exec:**"])
        .expect("the checker ceiling is a compile-time constant and must parse")
}

/// The engine refused to produce evidence.
///
/// Note what is *not* here: a checker's own inability to decide. That is
/// [`Verdict::Inconclusive`], which is an answer. These are failures to reach
/// the point of having an answer at all.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum CheckError {
    /// The checker declared authority a checker may not hold.
    ///
    /// Refused before [`Checker::judge`] runs, so the offending checker never
    /// executes with it.
    #[error("checker {checker} declares `{atom}`, which is outside what a checker may hold")]
    Overreach {
        /// Which checker.
        checker: CheckerId,
        /// The first atom that escaped the ceiling.
        atom: String,
    },

    /// The checker's declared authority could not be proved to be within the
    /// ceiling.
    ///
    /// A refusal rather than a pass. Goal G5: what cannot be proved is not
    /// assumed, and a permission granted on a guess is the one failure this
    /// whole layer exists to prevent.
    #[error("cannot prove checker {checker}'s grants are within what a checker may hold")]
    UndecidableGrants {
        /// Which checker.
        checker: CheckerId,
    },

    /// The work order or condensate could not be canonically encoded, so the
    /// evidence cannot name what it covers.
    #[error("checker {checker} could not address its inputs: {detail}")]
    Address {
        /// Which checker.
        checker: CheckerId,
        /// Why.
        detail: String,
    },

    /// The verdict could not be signed, so there is no evidence and nothing
    /// commits.
    #[error("the verdict from {checker} could not be signed: {source}")]
    Sign {
        /// Which checker.
        checker: CheckerId,
        /// What went wrong.
        #[source]
        source: SignError,
    },
}

/// What a checker decided, before it becomes signed [`Evidence`].
///
/// Carries the verdict and, optionally, further digests the checker looked at.
/// It does *not* carry the work order or the condensate digests — those are
/// added by [`Checker::check`], so that a checker cannot produce a verdict that
/// fails to name what it judged.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Judgement {
    /// The outcome.
    pub verdict: Verdict,
    /// Anything else this verdict speaks about: a schema, a raw patch fetched
    /// from the content store, a tool manifest.
    pub also: Vec<Digest>,
}

impl Judgement {
    /// The check succeeded.
    pub fn pass() -> Self {
        Self {
            verdict: Verdict::Pass,
            also: Vec::new(),
        }
    }

    /// The check failed, with a reason a repair loop can act on.
    ///
    /// The reason is read by a model on the next attempt, so it should say what
    /// was wrong and where, not merely that something was.
    pub fn fail(reason: impl Into<String>) -> Self {
        Self {
            verdict: Verdict::Fail(reason.into()),
            also: Vec::new(),
        }
    }

    /// The check could not reach a conclusion.
    ///
    /// A timeout, a tool that crashed, an input this checker does not handle.
    /// Never commits — see [`Verdict`].
    pub fn inconclusive(reason: impl Into<String>) -> Self {
        Self {
            verdict: Verdict::Inconclusive(reason.into()),
            also: Vec::new(),
        }
    }

    /// Record another digest this verdict speaks about.
    #[must_use]
    pub fn covering(mut self, digest: Digest) -> Self {
        self.also.push(digest);
        self
    }

    /// Whether this judgement would permit a commit.
    pub fn is_pass(&self) -> bool {
        self.verdict.is_pass()
    }
}

/// Whether a grant set is narrow enough for a checker to hold.
///
/// Exposed separately from [`Checker::check`] so the compiler can ask the same
/// question statically when it resolves a `CheckerRef` (US-0401), rather than
/// discovering at run time that a flow's checker was never legitimate.
///
/// # Errors
///
/// [`CheckError::Overreach`] if an atom escapes [`checker_ceiling`], or
/// [`CheckError::UndecidableGrants`] if containment could not be decided.
pub fn ensure_model_free(checker: &CheckerId, grants: &GrantSet) -> Result<(), CheckError> {
    let ceiling = checker_ceiling();

    match set_leq(grants, &ceiling) {
        Tri::Yes => Ok(()),
        Tri::No => {
            // Name the first offender rather than the whole set: a message that
            // dumps every grant makes the reader find the problem themselves.
            let atom = grants
                .iter()
                .find(|a| !set_leq(&GrantSet::new([(*a).clone()]), &ceiling).is_yes())
                .map(ToString::to_string)
                .unwrap_or_else(|| "?".to_string());
            Err(CheckError::Overreach {
                checker: checker.clone(),
                atom,
            })
        }
        Tri::Unknown => Err(CheckError::UndecidableGrants {
            checker: checker.clone(),
        }),
    }
}

/// Layer 5: turns a proposal and a result into a signed verdict.
///
/// Implement [`id`](Self::id) and [`judge`](Self::judge), and declare
/// [`grants`](Self::grants) if the checker needs any. Do not implement
/// [`check`](Self::check) — it is what enforces the contract, and the design of
/// this module is that an implementation cannot opt out of it.
#[async_trait]
pub trait Checker: Send + Sync + fmt::Debug {
    /// Which checker this is, and at what version.
    ///
    /// Recorded into every piece of evidence. The version is not decoration: a
    /// verdict is only meaningful against a specific checker, and "the tests
    /// passed" means nothing without knowing which runner said so.
    fn id(&self) -> CheckerId;

    /// The authority this checker needs.
    ///
    /// Nothing, by default. Checked against [`checker_ceiling`] before the
    /// checker runs, so a declaration wide enough to reach a model is refused
    /// rather than trusted.
    fn grants(&self) -> GrantSet {
        GrantSet::EMPTY
    }

    /// Decide. The part an implementation writes.
    ///
    /// Must be a pure function of its two arguments — see the module
    /// documentation on determinism. There is no error return: a checker that
    /// could not decide returns [`Judgement::inconclusive`], which never
    /// commits.
    async fn judge(&self, order: &WorkOrder, condensate: &Condensate) -> Judgement;

    /// Check the authority, decide, bind the verdict to its inputs, and sign.
    ///
    /// In that order, and the order matters. The ceiling is enforced *before*
    /// `judge` runs, so an over-authorised checker never executes; the inputs
    /// are bound by this method rather than by the implementation, so a
    /// checker cannot produce a verdict that omits what it judged.
    ///
    /// The evidence is always [`EvidenceKind::Deterministic`]. That is not a
    /// parameter because this trait *is* the model-free checker: quorum
    /// evidence comes from the `quorum` combinator (US-1403) and human evidence
    /// from a gate, and neither of those is a `Checker`.
    ///
    /// # Errors
    ///
    /// [`CheckError::Overreach`] or [`CheckError::UndecidableGrants`] if the
    /// checker may not hold what it declared, [`CheckError::Address`] if the
    /// inputs could not be digested, or [`CheckError::Sign`] if the verdict
    /// could not be signed. In every case there is no evidence, and so no
    /// commit.
    async fn check(
        &self,
        order: &WorkOrder,
        condensate: &Condensate,
        signer: &dyn Sign,
    ) -> Result<Evidence, CheckError> {
        let id = self.id();

        // Before anything runs: a checker that could reach a reasoner does not
        // get to produce a verdict, even a correct one.
        ensure_model_free(&id, &self.grants())?;

        let address = |value: Result<Digest, boundgraph_core::CanonicalError>| {
            value.map_err(|e| CheckError::Address {
                checker: id.clone(),
                detail: e.to_string(),
            })
        };
        let order_digest = address(order.digest())?;
        let condensate_digest = address(condensate.digest())?;

        let judgement = self.judge(order, condensate).await;

        // The trait names the inputs, not the implementation. A checker that
        // forgot to would produce evidence that could be reattached to a
        // different patch, which is the forgery `Evidence::covers` exists to
        // stop.
        let inputs = [order_digest, condensate_digest]
            .into_iter()
            .chain(judgement.also);

        sign_evidence(
            judgement.verdict,
            id.clone(),
            inputs,
            EvidenceKind::Deterministic,
            signer,
        )
        .map_err(|source| CheckError::Sign {
            checker: id,
            source,
        })
    }
}

/// A checker that always returns the same verdict.
///
/// For tests, for cassette replay (US-1008), and for a flow being wired up
/// before its real checker exists. It declares no grants and reads neither of
/// its arguments, so it is trivially model-free and trivially deterministic.
///
/// Named for what it is. A checker that always passes is exactly the thing Law
/// III exists to prevent, so it should be obvious in a flow definition that
/// this is what is there.
///
/// # Example
///
/// ```
/// use boundgraph_check::{Checker, Constant, LocalKey};
/// # use boundgraph_core::{Condensate, CondensatePayload, Digest, GrantSet, Intent,
/// #     ProposalOrigin, SchemaId, SlicerId, WorkOrder};
/// # let order = WorkOrder::new(
/// #     Intent::new("patch.apply", &"fix it")?,
/// #     vec![],
/// #     GrantSet::EMPTY,
/// #     ProposalOrigin::new("claude-opus-5", [], Digest::of(b"prompt")),
/// # );
/// # let condensate = Condensate::new(
/// #     SchemaId::new("boundgraph.log.v1", 1),
/// #     CondensatePayload::inline(&"3 errors")?,
/// #     Digest::of(b"raw"),
/// #     400,
/// #     true,
/// #     SlicerId::new("log", 1),
/// # );
/// let key = LocalKey::from_seed("host-key-1", [7u8; 32]);
///
/// let evidence = tokio::runtime::Builder::new_current_thread()
///     .build()?
///     .block_on(Constant::failing("not implemented yet").check(&order, &condensate, &key))?;
///
/// assert!(!evidence.permits_commit());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Constant {
    id: CheckerId,
    verdict: Verdict,
}

impl Constant {
    /// A checker that always passes.
    ///
    /// Use it knowingly. Nothing it vouches for has been checked.
    pub fn passing() -> Self {
        Self {
            id: CheckerId::new("constant-pass", 1),
            verdict: Verdict::Pass,
        }
    }

    /// A checker that always fails, with a reason.
    pub fn failing(reason: impl Into<String>) -> Self {
        Self {
            id: CheckerId::new("constant-fail", 1),
            verdict: Verdict::Fail(reason.into()),
        }
    }

    /// A checker that never decides.
    pub fn undecided(reason: impl Into<String>) -> Self {
        Self {
            id: CheckerId::new("constant-inconclusive", 1),
            verdict: Verdict::Inconclusive(reason.into()),
        }
    }

    /// Name it something else, so a ledger says which stand-in this was.
    #[must_use]
    pub fn named(mut self, name: impl Into<String>, version: u32) -> Self {
        self.id = CheckerId::new(name, version);
        self
    }
}

#[async_trait]
impl Checker for Constant {
    fn id(&self) -> CheckerId {
        self.id.clone()
    }

    async fn judge(&self, _order: &WorkOrder, _condensate: &Condensate) -> Judgement {
        Judgement {
            verdict: self.verdict.clone(),
            also: Vec::new(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sign::{LocalKey, verify};
    use boundgraph_core::{
        CondensatePayload, GrantAtom, Intent, ProposalOrigin, SchemaId, SigningKeyId, SlicerId,
    };

    fn order() -> WorkOrder {
        WorkOrder::new(
            Intent::new("patch.apply", &"fix the off-by-one").unwrap(),
            vec![],
            GrantSet::parse(["fs:write:/src/**"]).unwrap(),
            ProposalOrigin::new("claude-opus-5", [], Digest::of(b"prompt")),
        )
    }

    fn condensate() -> Condensate {
        Condensate::new(
            SchemaId::new("boundgraph.diff.v1", 1),
            CondensatePayload::inline(&"one file changed").unwrap(),
            Digest::of(b"the raw patch"),
            400,
            false,
            SlicerId::new("diff", 1),
        )
    }

    fn key() -> LocalKey {
        LocalKey::from_seed("host-key-1", [7u8; 32])
    }

    /// A checker declaring whatever a test needs it to.
    #[derive(Debug)]
    struct Declaring {
        grants: GrantSet,
    }

    impl Declaring {
        fn new(atoms: &[&str]) -> Self {
            Self {
                grants: GrantSet::parse(atoms.iter().copied()).expect("test grants should parse"),
            }
        }
    }

    #[async_trait]
    impl Checker for Declaring {
        fn id(&self) -> CheckerId {
            CheckerId::new("declaring", 1)
        }
        fn grants(&self) -> GrantSet {
            self.grants.clone()
        }
        async fn judge(&self, _order: &WorkOrder, _condensate: &Condensate) -> Judgement {
            Judgement::pass()
        }
    }

    // ── the contract ────────────────────────────────────────────────────────

    /// The criterion: `check` takes a work order and a condensate.
    #[tokio::test]
    async fn check_takes_a_work_order_and_a_condensate_and_returns_evidence() {
        let evidence = Constant::passing()
            .check(&order(), &condensate(), &key())
            .await
            .unwrap();

        assert_eq!(evidence.verdict, Verdict::Pass);
        assert!(evidence.permits_commit());
    }

    /// The criterion: every checker declares an id and version, and it is
    /// recorded in the evidence.
    #[tokio::test]
    async fn the_checker_id_and_version_reach_the_evidence() {
        let evidence = Constant::passing()
            .named("json-schema", 3)
            .check(&order(), &condensate(), &key())
            .await
            .unwrap();

        assert_eq!(evidence.checker, CheckerId::new("json-schema", 3));
        assert_eq!(evidence.checker.version, 3);
    }

    /// The criterion: all three verdicts are reachable, and only one commits.
    #[tokio::test]
    async fn a_checker_returns_pass_fail_or_inconclusive() {
        let cases = [
            (Constant::passing(), true),
            (Constant::failing("schema violation at /items/2"), false),
            (Constant::undecided("the compiler timed out"), false),
        ];

        for (checker, commits) in cases {
            let evidence = checker
                .check(&order(), &condensate(), &key())
                .await
                .unwrap();
            assert_eq!(evidence.permits_commit(), commits, "{checker:?}");
        }
    }

    /// The criterion, stated on its own because it is the one a two-valued
    /// verdict would have got wrong.
    #[tokio::test]
    async fn inconclusive_never_commits() {
        let evidence = Constant::undecided("the test run timed out")
            .check(&order(), &condensate(), &key())
            .await
            .unwrap();

        assert!(!evidence.permits_commit());
        assert_eq!(evidence.verdict.reason(), Some("the test run timed out"));
    }

    /// The trait binds the verdict to what was judged, so an implementation
    /// cannot produce evidence that could be reattached elsewhere.
    #[tokio::test]
    async fn evidence_names_the_work_order_and_the_condensate() {
        let (order, condensate) = (order(), condensate());
        let evidence = Constant::passing()
            .check(&order, &condensate, &key())
            .await
            .unwrap();

        assert!(evidence.covers(&order.digest().unwrap()));
        assert!(evidence.covers(&condensate.digest().unwrap()));
        assert!(!evidence.covers(&Digest::of(b"some other artefact")));
    }

    #[tokio::test]
    async fn a_checker_can_name_further_inputs_it_looked_at() {
        #[derive(Debug)]
        struct Schema;

        #[async_trait]
        impl Checker for Schema {
            fn id(&self) -> CheckerId {
                CheckerId::new("json-schema", 1)
            }
            async fn judge(&self, _o: &WorkOrder, _k: &Condensate) -> Judgement {
                Judgement::pass().covering(Digest::of(b"the schema"))
            }
        }

        let evidence = Schema.check(&order(), &condensate(), &key()).await.unwrap();
        assert!(evidence.covers(&Digest::of(b"the schema")));
    }

    #[tokio::test]
    async fn the_evidence_is_signed_and_verifies() {
        let key = key();
        let evidence = Constant::passing()
            .check(&order(), &condensate(), &key)
            .await
            .unwrap();

        assert!(verify(&evidence, &key.public_key()).is_ok());
        assert_eq!(evidence.key, SigningKeyId("host-key-1".into()));
        assert_eq!(evidence.kind, EvidenceKind::Deterministic);
    }

    /// The criterion: same inputs, same verdict — and, because signing is
    /// deterministic too, the same bytes all the way out.
    #[tokio::test]
    async fn the_same_inputs_always_yield_the_same_evidence() {
        let (order, condensate, key) = (order(), condensate(), key());
        let checker = Constant::passing();

        let first = checker.check(&order, &condensate, &key).await.unwrap();
        for _ in 0..8 {
            assert_eq!(
                checker.check(&order, &condensate, &key).await.unwrap(),
                first
            );
        }
    }

    #[tokio::test]
    async fn different_inputs_yield_different_evidence() {
        let key = key();
        let checker = Constant::passing();

        let one = checker.check(&order(), &condensate(), &key).await.unwrap();

        let mut other = condensate();
        other.raw = Digest::of(b"a different raw patch");
        let two = checker.check(&order(), &other, &key).await.unwrap();

        assert_ne!(one, two);
    }

    // ── the capability set ──────────────────────────────────────────────────

    /// The criterion: a checker cannot call a reasoner, and it is the
    /// capability set that says so.
    #[tokio::test]
    async fn a_checker_that_could_reach_a_model_provider_is_refused() {
        for reaching in [
            "net:egress:api.anthropic.com:443",
            "net:egress:**",
            "secret:use:anthropic_key",
        ] {
            let err = Declaring::new(&[reaching])
                .check(&order(), &condensate(), &key())
                .await
                .unwrap_err();

            assert!(
                matches!(err, CheckError::Overreach { .. }),
                "{reaching} should be refused, got {err:?}"
            );
        }
    }

    /// And it is refused *before* running, so an over-authorised checker never
    /// executes at all.
    #[tokio::test]
    async fn an_over_authorised_checker_never_runs() {
        #[derive(Debug)]
        struct Explodes;

        #[async_trait]
        impl Checker for Explodes {
            fn id(&self) -> CheckerId {
                CheckerId::new("explodes", 1)
            }
            fn grants(&self) -> GrantSet {
                GrantSet::parse(["net:egress:**"]).unwrap()
            }
            async fn judge(&self, _o: &WorkOrder, _k: &Condensate) -> Judgement {
                panic!("an over-authorised checker must not reach its own body");
            }
        }

        assert!(
            Explodes
                .check(&order(), &condensate(), &key())
                .await
                .is_err()
        );
    }

    /// The same ceiling is what keeps a checker deterministic.
    #[tokio::test]
    async fn a_checker_cannot_hold_a_clock_or_a_source_of_randomness() {
        for nondeterministic in ["time:now", "rand:bytes"] {
            let err = Declaring::new(&[nondeterministic])
                .check(&order(), &condensate(), &key())
                .await
                .unwrap_err();
            assert!(
                matches!(err, CheckError::Overreach { .. }),
                "{nondeterministic}"
            );
        }
    }

    /// A checker that could edit the workspace could make its verdict true.
    #[tokio::test]
    async fn a_checker_cannot_write_to_what_it_is_judging() {
        let err = Declaring::new(&["fs:write:/src/**"])
            .check(&order(), &condensate(), &key())
            .await
            .unwrap_err();

        let CheckError::Overreach { atom, .. } = err else {
            panic!("expected Overreach");
        };
        assert!(
            atom.contains("fs:write"),
            "the message should name it: {atom}"
        );
    }

    #[tokio::test]
    async fn the_grants_a_real_checker_needs_are_allowed() {
        let checker = Declaring::new(&["fs:read:/workspace/**", "proc:exec:/usr/bin/cargo"]);
        assert!(checker.check(&order(), &condensate(), &key()).await.is_ok());
    }

    #[tokio::test]
    async fn declaring_nothing_is_the_default_and_is_allowed() {
        assert_eq!(Constant::passing().grants(), GrantSet::EMPTY);
        assert!(
            Constant::passing()
                .check(&order(), &condensate(), &key())
                .await
                .is_ok()
        );
    }

    /// Goal G5: an undecidable containment is a refusal, never a pass.
    #[test]
    fn an_undecidable_grant_is_refused_rather_than_assumed() {
        let id = CheckerId::new("templated", 1);
        // A template segment is symbolic, so containment cannot be decided.
        let grants = GrantSet::new([GrantAtom::new("fs", "read", "{workspace}")]);

        assert!(matches!(
            ensure_model_free(&id, &grants),
            Err(CheckError::UndecidableGrants { .. })
        ));
    }

    #[test]
    fn the_ceiling_omits_every_domain_that_could_reach_a_model() {
        let ceiling = checker_ceiling();
        for domain in ["net", "secret", "time", "rand", "env"] {
            assert!(
                ceiling.iter().all(|a| a.domain != domain),
                "`{domain}` must not be within a checker's authority"
            );
        }
        assert!(ceiling.iter().all(|a| a.action != "write"));
    }

    // ── signing failure ─────────────────────────────────────────────────────

    /// The criterion from US-0802, restated at this boundary: no signature, no
    /// evidence, no commit.
    #[tokio::test]
    async fn a_signing_failure_yields_no_evidence() {
        #[derive(Debug)]
        struct Broken;

        impl Sign for Broken {
            fn key_id(&self) -> SigningKeyId {
                SigningKeyId("kms-key-1".into())
            }
            fn sign(&self, _payload: &[u8]) -> Result<boundgraph_core::Signature, SignError> {
                Err(SignError::Unavailable {
                    key: self.key_id(),
                    detail: "the KMS did not answer".into(),
                })
            }
        }

        let err = Constant::passing()
            .check(&order(), &condensate(), &Broken)
            .await
            .unwrap_err();

        assert!(matches!(err, CheckError::Sign { .. }));
    }

    // ── judgements ──────────────────────────────────────────────────────────

    #[test]
    fn a_judgement_says_which_of_the_three_it_is() {
        assert!(Judgement::pass().is_pass());
        assert!(!Judgement::fail("no").is_pass());
        assert!(!Judgement::inconclusive("could not tell").is_pass());
    }

    #[test]
    fn a_failure_reason_survives_to_the_repair_loop() {
        let judgement = Judgement::fail("expected string at /items/2, found number");
        assert_eq!(
            judgement.verdict.reason(),
            Some("expected string at /items/2, found number")
        );
    }
}