Skip to main content

supercode_interchange/ontology/
codec.rs

1//! The codec contract both pieces obey (`docs/ONTOLOGY.md` ยง2.5): every
2//! artifact a codec reads or writes names the [`Fidelity`] it reached and,
3//! only at [`Fidelity::Semantic`], the loss it accepted. The session half is
4//! the [`crate::Session`] loaders and writers; the world half implements
5//! [`WorldCodec`].
6
7use std::path::Path;
8
9use schemars::JsonSchema;
10use serde::{Deserialize, Serialize};
11
12use crate::{Fidelity, Result};
13
14/// What one artifact reached on the way in or out.
15#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
16pub struct ArtifactFidelity {
17    /// Path relative to the home the codec read or wrote.
18    pub path: String,
19    /// The tier reached.
20    pub fidelity: Fidelity,
21    /// Named loss; non-empty only when `fidelity` tolerates residue.
22    #[serde(default, skip_serializing_if = "Vec::is_empty")]
23    pub loss: Vec<String>,
24}
25
26impl ArtifactFidelity {
27    /// An artifact reproduced or reused byte for byte.
28    pub fn byte(path: impl Into<String>) -> Self {
29        Self {
30            path: path.into(),
31            fidelity: Fidelity::ByteLossless,
32            loss: Vec::new(),
33        }
34    }
35
36    /// Every value survived; the container was re-synthesized.
37    pub fn value(path: impl Into<String>) -> Self {
38        Self {
39            path: path.into(),
40            fidelity: Fidelity::ValueLossless,
41            loss: Vec::new(),
42        }
43    }
44
45    /// Meaning survived; `loss` says what did not.
46    pub fn semantic(path: impl Into<String>, loss: Vec<String>) -> Self {
47        Self {
48            path: path.into(),
49            fidelity: Fidelity::Semantic,
50            loss,
51        }
52    }
53}
54
55/// A harness's operational home compiled into a world value and back.
56pub trait WorldCodec<W> {
57    /// Read a home into the world value, naming what each artifact reached.
58    fn compile(&self, home: &Path) -> Result<(W, Vec<ArtifactFidelity>)>;
59    /// Write the world value as this harness's home, naming what each artifact
60    /// reached; a write that would have to guess is an error naming its gate.
61    fn decompile(&self, world: &W, dest: &Path) -> Result<Vec<ArtifactFidelity>>;
62}