Skip to main content

brygge_ir/
lib.rs

1//! brygge's intermediate representation — the light core (RFC 001/002/003, under RFC 009).
2//!
3//! This crate is the durable product boundary of brygge (requirement PU-3): decoders write an [`Ir`],
4//! `inspect`/`verify` read it, encoders consume it, and a foreign encoder for another target depends on
5//! this crate and nothing heavier. It **links no source-decoder dependency** (RFC 009 D-1): the whole
6//! honesty and verification path runs here, so a target can check a brygge import on its own surface.
7//!
8//! The one idea it turns on (RFC 001): **faithfulness-with-provenance, not neutrality.** The IR records
9//! what each source *literally guaranteed*, plus a *marked* place for what a decoder or encoder
10//! *derived* — and it carries **evidence for** identity (stated and inferred renames), never identity
11//! itself, leaving a node-identity encoder to author identity visibly. Honesty is a property of the
12//! model, not a convention: an inference has no representation except a [`status::Derived`] record, and
13//! there is no field in which to store target identity.
14//!
15//! Modules: [`version`] the IR contract version + read gate · [`canon`] the hand-rolled canonical codec ·
16//! [`content`] the content-addressed blob store · [`status`] the epistemic-status type + taxonomy ·
17//! [`model`] the IR types · [`builder`] deterministic construction · [`artifact`] the single-file,
18//! digested, versioned container · [`honesty`] the loss boundary + the recoverable fidelity report.
19
20#![forbid(unsafe_code)]
21#![warn(missing_docs)]
22
23pub mod artifact;
24pub mod builder;
25pub(crate) mod canon;
26pub mod content;
27pub mod honesty;
28pub mod model;
29pub mod restamp;
30pub mod status;
31pub mod transform;
32pub mod version;
33
34pub use artifact::{Decoded, digest_of, from_bytes, from_file, read_from, to_bytes};
35pub use builder::{AtomDraft, IrBuilder};
36pub use content::{BlobId, ContentStore, Storage};
37pub use honesty::{FidelityReport, summary};
38pub use model::{
39    Annotation, AtomId, ChangeAtom, ChangedPart, Content, CopyRecord, DropRecord, Extra, Flag,
40    FlagKind, Identity, ImportProvenance, Ir, LossBoundary, LossClass, MetadataClaims, PathOp,
41    RefKind, RefRecord, Signature, SourceIdentity, SourceKind, Text, Time, TransformRecord,
42};
43pub use status::{Derivation, DerivationKind, EpistemicStatus};
44pub use version::ContractVersion;
45
46/// The result type for fallible `brygge-ir` operations.
47pub type Result<T> = std::result::Result<T, Error>;
48
49/// Everything `brygge-ir` can fail with. Reading an artifact never panics on malformed bytes — a bad
50/// input is a typed error (brygge parses untrusted history; the core must be unshakeable).
51#[derive(Debug)]
52#[non_exhaustive]
53pub enum Error {
54    /// The artifact's bytes ended or were malformed while decoding (a truncation, an invalid UTF-8
55    /// byte in a `text` field, a declared length exceeding the input).
56    Decode(String),
57    /// The artifact's integrity digest did not match its contents (tamper or truncation — RFC 003 D-3).
58    DigestMismatch,
59    /// The artifact's container format byte is `1` (`PreReleaseArtifact`): a pre-contract-0.2.0
60    /// artifact, from before RFC 011. Its metadata is never parsed — the wire shape underneath changed
61    /// too much to read safely. Re-decode the source.
62    PreReleaseArtifact,
63    /// The artifact declares an IR-contract version this build does not read (RFC 011 D-3's "0.y"
64    /// rule, widened by RFC 018 D-7's [`version::READABLE`]): while major 0, a reader accepts only the
65    /// minors it lists (any patch); from major 1, it accepts its own major with any minor.
66    UnsupportedContract {
67        /// The contract version found in the artifact.
68        found: version::ContractVersion,
69        /// The contract version this build writes.
70        supported: version::ContractVersion,
71    },
72    /// A record carried a field with an unrecognized id and its critical bit set (RFC 011 §2.2 rule
73    /// 9): this build cannot safely ignore it, since the field may change the record's meaning.
74    UnknownCriticalField {
75        /// The record type the field was found in (e.g. `"PathOp::Add"`).
76        record: &'static str,
77        /// The unrecognized field's id (not the raw tag — the critical bit already stripped).
78        tag: u64,
79    },
80    /// The bytes decode but violate a canonical-form rule (RFC 011 §2.2): an out-of-order or
81    /// duplicate tag, a non-minimal varint, an omittable field encoded anyway, an unsorted list or
82    /// map, or trailing bytes. Accepting non-canonical input would let two different byte strings mean
83    /// the same value, defeating content-addressing and the integrity digest.
84    NonCanonical(String),
85    /// A structural invariant was violated while building or writing (e.g. a ref targets an unknown
86    /// atom). Signals a bug in a caller, never malformed *input*.
87    Invariant(String),
88    /// [`artifact::write_to`] could not write to, or seek on, its destination (RFC 015 D-2); or a
89    /// file-backed [`content::ContentStore`] (RFC 015 D-3) could not create, write, or read its spill
90    /// file — a disk-full condition included. Never a panic: the caller's own I/O failed, not
91    /// brygge-ir's encoding.
92    Io(String),
93    /// A blob read from an artifact-backed [`content::ContentStore`] (RFC 015 D-4), after the streaming
94    /// reader's own pass verified it, no longer matches its content address: something modified the
95    /// artifact while it was open. The caller is never handed the changed bytes.
96    ArtifactChanged(String),
97    /// A declared resource ceiling was reached while building an [`Ir`] (0.8.1, the amplification-bounds
98    /// patch): [`builder::IrBuilder::add_atom`]'s running count of every atom's `ops` crossed
99    /// `max_ir_ops` before the atom that crossed it was stored. Holds for every decoder and every
100    /// `Edit`-based transform, since both build through [`builder::IrBuilder`].
101    ResourceLimit {
102        /// What was being counted (e.g. `"the path-operation total in this artifact"`).
103        what: String,
104        /// The ceiling that was reached, already formatted for a message (e.g. `"200000000 operations"`).
105        ceiling: String,
106    },
107}
108
109impl Error {
110    /// Wrap an [`std::io::Error`] as [`Error::Io`].
111    pub(crate) fn io(e: std::io::Error) -> Self {
112        Self::Io(e.to_string())
113    }
114
115    /// Build [`Error::Io`] from a message directly (no [`std::io::Error`] in hand).
116    pub(crate) fn io_msg(m: impl Into<String>) -> Self {
117        Self::Io(m.into())
118    }
119}
120
121impl std::fmt::Display for Error {
122    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123        match self {
124            Self::Decode(m) => write!(f, "malformed brygge-ir artifact: {m}"),
125            Self::DigestMismatch => {
126                write!(
127                    f,
128                    "brygge-ir integrity digest mismatch (tampered or truncated)"
129                )
130            }
131            Self::PreReleaseArtifact => write!(
132                f,
133                "this artifact predates brygge-ir contract 0.2.0 (a pre-release format); re-decode the \
134                 source"
135            ),
136            Self::UnsupportedContract { found, .. } => write!(
137                f,
138                "artifact contract {found} is not supported by this build (reads {})",
139                version::readable_summary()
140            ),
141            Self::UnknownCriticalField { record, tag } => write!(
142                f,
143                "{record}: unrecognized critical field {tag}; this build cannot safely ignore it"
144            ),
145            Self::NonCanonical(m) => write!(f, "brygge-ir artifact is not in canonical form: {m}"),
146            Self::Invariant(m) => write!(f, "brygge-ir invariant violated: {m}"),
147            Self::Io(m) => write!(f, "writing a brygge-ir artifact failed: {m}"),
148            Self::ArtifactChanged(m) => {
149                write!(f, "the artifact changed while it was being read: {m}")
150            }
151            Self::ResourceLimit { what, ceiling } => {
152                write!(f, "refused: {what} exceeds brygge's ceiling ({ceiling})")
153            }
154        }
155    }
156}
157
158impl std::error::Error for Error {}