boundgraph-core 0.1.0

Core primitives for the BoundGraph runtime: content-addressed digests, work orders, context, condensates, evidence, and the ledger.
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
//! The Evidence (`ε`) — a signed verdict, not a claim.
//!
//! Law III: model output is a proposal, never ground truth. No state change
//! commits on probabilistic output. A step commits only on [`Evidence`] from a
//! deterministic checker or a statistical quorum.
//!
//! Three details do the real work here, and each closes a specific hole:
//!
//! - **[`Verdict`] has no implicit pass.** `Inconclusive` is its own case, so a
//!   checker that timed out cannot be mistaken for one that succeeded.
//! - **[`Evidence::inputs`] lists digests.** Evidence names exactly what was
//!   checked, so it cannot later be re-pointed at different data. Without this
//!   a passing verdict could be harvested and reattached to a failing patch.
//! - **The signature covers everything else.** An unsigned verdict is
//!   indistinguishable from a claim someone typed.
//!
//! This module defines the *type*. Producing signatures is US-0802, and key
//! management is still open (`ARCHITECTURE.md` §17) — which is precisely why
//! [`SigningKeyId`] is recorded alongside every signature: a verifier must know
//! which key to check against without that decision being baked in here.

use std::fmt;

use serde::{Deserialize, Serialize};

use crate::digest::Digest;

/// The outcome of a check.
///
/// Deliberately three-valued. A two-valued verdict forces "we could not tell"
/// into either `Pass` (unsafe) or `Fail` (blocks legitimate work), and the
/// unsafe choice is the tempting one.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Verdict {
    /// The check succeeded. This is the only verdict that may commit.
    Pass,
    /// The check failed, with a reason the repair loop can act on.
    Fail(String),
    /// The check could not reach a conclusion — a timeout, a crashed tool, an
    /// unsupported input. Never commits.
    Inconclusive(String),
}

impl Verdict {
    /// Whether this verdict permits a commit.
    ///
    /// Only [`Verdict::Pass`] does. `Inconclusive` is explicitly not a pass.
    pub fn is_pass(&self) -> bool {
        matches!(self, Self::Pass)
    }

    /// Why the check did not pass, if it did not.
    pub fn reason(&self) -> Option<&str> {
        match self {
            Self::Pass => None,
            Self::Fail(r) | Self::Inconclusive(r) => Some(r),
        }
    }
}

/// Which checker produced a verdict, and at what version.
///
/// Versioned because a verdict is only meaningful against a specific checker:
/// "the tests passed" means nothing without knowing which test runner said so.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct CheckerId {
    /// Checker name, e.g. `pytest`, `tsc`, `diff-scope`.
    pub name: String,
    /// Checker version.
    pub version: u32,
}

impl CheckerId {
    /// Name a checker.
    pub fn new(name: impl Into<String>, version: u32) -> Self {
        Self {
            name: name.into(),
            version,
        }
    }
}

/// Rendered `name@version`, because a checker diagnostic that named only the
/// checker would be ambiguous across versions — and the version is the half
/// that makes the verdict reproducible.
impl fmt::Display for CheckerId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}@{}", self.name, self.version)
    }
}

/// Identifies the key a signature was made with.
///
/// Recorded so a verifier knows which public key to check against. Whether
/// keys are per-host, per-run, or held in an external KMS is unresolved, so
/// this is an opaque identifier rather than an embedded key.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct SigningKeyId(pub String);

impl fmt::Display for SigningKeyId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

/// An ed25519 signature over the canonical encoding of an [`Evidence`].
///
/// This crate defines the type and the contract; producing and verifying
/// signatures is the checker engine's job (US-0802).
#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Signature(#[serde(with = "sig_bytes")] [u8; 64]);

impl Signature {
    /// Wrap raw signature bytes.
    pub const fn from_bytes(bytes: [u8; 64]) -> Self {
        Self(bytes)
    }

    /// The raw signature bytes.
    pub const fn as_bytes(&self) -> &[u8; 64] {
        &self.0
    }
}

impl fmt::Debug for Signature {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use fmt::Write as _;
        let head = self.0[..6].iter().fold(String::new(), |mut s, b| {
            let _ = write!(s, "{b:02x}");
            s
        });
        write!(f, "Signature({head}…)")
    }
}

/// How a verdict was reached.
///
/// The distinction matters when weighing evidence: a deterministic checker and
/// a majority vote are not the same kind of assurance, and an auditor must be
/// able to tell them apart.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EvidenceKind {
    /// A model-free checker. The strongest form.
    Deterministic,
    /// A statistical quorum: `k` of `n` branches agreed.
    Quorum {
        /// Branches run.
        n: u8,
        /// Branches that had to agree.
        k: u8,
    },
    /// A human approved, at a gate. Always signed by a human identity.
    Human {
        /// Who approved.
        identity: String,
    },
}

/// `ε` — a signed verdict from a checker or a quorum.
///
/// # Example
///
/// ```
/// use boundgraph_core::{CheckerId, Digest, Evidence, EvidenceKind, Signature, SigningKeyId, Verdict};
///
/// let patch = Digest::of(b"the patch that was checked");
///
/// let ev = Evidence::new(
///     Verdict::Pass,
///     CheckerId::new("cargo-test", 1),
///     vec![patch],
///     Signature::from_bytes([0u8; 64]),
///     SigningKeyId("host-key-1".into()),
///     EvidenceKind::Deterministic,
/// );
///
/// assert!(ev.permits_commit());
/// // Evidence names exactly what it covers, so it cannot be reattached.
/// assert!(ev.covers(&patch));
/// assert!(!ev.covers(&Digest::of(b"some other patch")));
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Evidence {
    /// The outcome.
    pub verdict: Verdict,
    /// Which checker decided, and at what version.
    pub checker: CheckerId,
    /// Digests of exactly what was checked.
    ///
    /// This is what stops evidence being re-pointed at different data: a
    /// verdict only speaks about these inputs.
    pub inputs: Vec<Digest>,
    /// Signature over the canonical encoding of every other field.
    pub signature: Signature,
    /// Which key signed.
    pub key: SigningKeyId,
    /// How the verdict was reached.
    pub kind: EvidenceKind,
}

impl Evidence {
    /// Construct evidence.
    ///
    /// Inputs are sorted, so two verdicts over the same set of inputs share a
    /// digest regardless of the order the checker happened to list them.
    pub fn new(
        verdict: Verdict,
        checker: CheckerId,
        inputs: impl IntoIterator<Item = Digest>,
        signature: Signature,
        key: SigningKeyId,
        kind: EvidenceKind,
    ) -> Self {
        let mut inputs: Vec<Digest> = inputs.into_iter().collect();
        inputs.sort_unstable();
        inputs.dedup();
        Self {
            verdict,
            checker,
            inputs,
            signature,
            key,
            kind,
        }
    }

    /// Whether this evidence permits a state change to commit.
    ///
    /// True only for [`Verdict::Pass`].
    pub fn permits_commit(&self) -> bool {
        self.verdict.is_pass()
    }

    /// Whether this evidence actually speaks about the given input.
    ///
    /// A commit must check this. Passing evidence about a *different* artefact
    /// is not permission to commit this one.
    pub fn covers(&self, digest: &Digest) -> bool {
        self.inputs.binary_search(digest).is_ok()
    }

    /// The bytes a signature is made over: everything except the signature.
    ///
    /// Exposed so the signer (US-0802) and any verifier compute the same
    /// pre-image, rather than each deriving it and hoping they agree.
    pub fn signing_payload(&self) -> Result<Vec<u8>, crate::CanonicalError> {
        crate::to_canonical_cbor(&(
            &self.verdict,
            &self.checker,
            &self.inputs,
            &self.key,
            &self.kind,
        ))
    }
}

/// Fixed 64-byte arrays are not `serde`-native; encode as a byte string.
mod sig_bytes {
    use serde::de::{Error as _, Unexpected};
    use serde::{Deserializer, Serializer};

    pub(super) fn serialize<S: Serializer>(bytes: &[u8; 64], s: S) -> Result<S::Ok, S::Error> {
        s.serialize_bytes(bytes)
    }

    pub(super) fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<[u8; 64], D::Error> {
        struct V;
        impl<'de> serde::de::Visitor<'de> for V {
            type Value = [u8; 64];
            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str("a 64-byte signature")
            }
            fn visit_bytes<E: serde::de::Error>(self, v: &[u8]) -> Result<[u8; 64], E> {
                <[u8; 64]>::try_from(v)
                    .map_err(|_| E::invalid_value(Unexpected::Bytes(v), &"exactly 64 bytes"))
            }
            fn visit_seq<A: serde::de::SeqAccess<'de>>(
                self,
                mut seq: A,
            ) -> Result<[u8; 64], A::Error> {
                let mut out = Vec::with_capacity(64);
                while let Some(b) = seq.next_element::<u8>()? {
                    out.push(b);
                }
                <[u8; 64]>::try_from(out.as_slice())
                    .map_err(|_| A::Error::invalid_length(out.len(), &"exactly 64 bytes"))
            }
        }
        d.deserialize_bytes(V)
    }
}

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

    fn evidence(verdict: Verdict) -> Evidence {
        Evidence::new(
            verdict,
            CheckerId::new("cargo-test", 1),
            [Digest::of(b"patch")],
            Signature::from_bytes([7u8; 64]),
            SigningKeyId("host-key-1".into()),
            EvidenceKind::Deterministic,
        )
    }

    #[test]
    fn carries_verdict_checker_inputs_signature_and_kind() {
        let e = evidence(Verdict::Pass);
        assert_eq!(e.verdict, Verdict::Pass);
        assert_eq!(e.checker, CheckerId::new("cargo-test", 1));
        assert_eq!(e.inputs, vec![Digest::of(b"patch")]);
        assert_eq!(e.signature, Signature::from_bytes([7u8; 64]));
        assert_eq!(e.kind, EvidenceKind::Deterministic);
    }

    #[test]
    fn only_pass_permits_a_commit() {
        assert!(evidence(Verdict::Pass).permits_commit());
        assert!(!evidence(Verdict::Fail("2 tests failed".into())).permits_commit());
        assert!(!evidence(Verdict::Inconclusive("timed out".into())).permits_commit());
    }

    #[test]
    fn inconclusive_is_not_an_implicit_pass() {
        let e = evidence(Verdict::Inconclusive("checker crashed".into()));
        assert!(!e.permits_commit());
        assert_eq!(e.verdict.reason(), Some("checker crashed"));
    }

    #[test]
    fn evidence_cannot_be_repointed_at_other_data() {
        let e = evidence(Verdict::Pass);
        assert!(e.covers(&Digest::of(b"patch")));
        assert!(
            !e.covers(&Digest::of(b"a different patch")),
            "passing evidence must not vouch for something it never saw"
        );
    }

    #[test]
    fn input_order_does_not_change_identity() {
        let a = Evidence::new(
            Verdict::Pass,
            CheckerId::new("c", 1),
            [Digest::of(b"x"), Digest::of(b"y")],
            Signature::from_bytes([0u8; 64]),
            SigningKeyId("k".into()),
            EvidenceKind::Deterministic,
        );
        let b = Evidence::new(
            Verdict::Pass,
            CheckerId::new("c", 1),
            [Digest::of(b"y"), Digest::of(b"x")],
            Signature::from_bytes([0u8; 64]),
            SigningKeyId("k".into()),
            EvidenceKind::Deterministic,
        );
        assert_eq!(a.digest().unwrap(), b.digest().unwrap());
        // …and `covers` still works after the sort.
        assert!(a.covers(&Digest::of(b"x")));
        assert!(a.covers(&Digest::of(b"y")));
    }

    #[test]
    fn ids_render_for_a_diagnostic() {
        assert_eq!(
            CheckerId::new("json-schema", 2).to_string(),
            "json-schema@2"
        );
        assert_eq!(SigningKeyId("host-key-1".into()).to_string(), "host-key-1");
    }

    #[test]
    fn kinds_are_distinguishable() {
        assert_ne!(
            EvidenceKind::Deterministic,
            EvidenceKind::Quorum { n: 3, k: 2 }
        );
        assert_ne!(
            EvidenceKind::Quorum { n: 3, k: 2 },
            EvidenceKind::Human {
                identity: "alex".into()
            }
        );
    }

    #[test]
    fn signing_payload_excludes_the_signature_but_covers_everything_else() {
        let base = evidence(Verdict::Pass);

        // A different signature over the same claim has the same pre-image.
        let mut resigned = base.clone();
        resigned.signature = Signature::from_bytes([9u8; 64]);
        assert_eq!(
            base.signing_payload().unwrap(),
            resigned.signing_payload().unwrap()
        );

        // Changing any covered field changes the pre-image.
        let flipped = evidence(Verdict::Fail("no".into()));
        assert_ne!(
            base.signing_payload().unwrap(),
            flipped.signing_payload().unwrap()
        );

        let mut rekeyed = base.clone();
        rekeyed.key = SigningKeyId("other-key".into());
        assert_ne!(
            base.signing_payload().unwrap(),
            rekeyed.signing_payload().unwrap()
        );

        let mut recovered = base.clone();
        recovered.inputs = vec![Digest::of(b"other")];
        assert_ne!(
            base.signing_payload().unwrap(),
            recovered.signing_payload().unwrap()
        );
    }

    #[test]
    fn signature_debug_does_not_dump_all_64_bytes() {
        let d = format!("{:?}", Signature::from_bytes([0xab; 64]));
        assert!(d.len() < 40, "debug output should be abbreviated: {d}");
    }

    #[test]
    fn round_trips_through_canonical_cbor() {
        let e = evidence(Verdict::Fail("2 tests failed".into()));
        let bytes = crate::to_canonical_cbor(&e).unwrap();
        let back: Evidence = crate::from_canonical_cbor(&bytes).unwrap();
        assert_eq!(e, back);
    }
}