doldskrift 0.5.0

Machine-native typography, encoding, and agent communication (DOLDSKRIFT/1)
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
//! Reader backends — reconstruction from observation graphs.
//!
//! Wrong or unknown grammar fails cleanly. Never fabricate convincing false plaintext.

use crate::semantic::Value;
use crate::{Error, Result};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

use super::epoch::{GrammarEpoch, ReaderCompatibility};
use super::lsg::{LatentGraph, LatentNodeKind};
use super::observation::ObservationGraph;

/// Stable reader identifier.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ReaderId(pub String);

impl ReaderId {
    /// Construct from string.
    pub fn new(s: impl Into<String>) -> Self {
        Self(s.into())
    }
}

impl std::fmt::Display for ReaderId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Reconstruction outcome status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReaderStatus {
    /// Semantics reconstructed successfully.
    Reconstructed,
    /// Grammar epoch / reader mismatch.
    Incompatible,
    /// Detected Doldskrift but confidence too low (reserved).
    LowConfidence,
    /// Grammar epoch unknown to this reader.
    UnknownGrammar,
    /// Reconstruction attempted but failed structurally.
    ReconstructionFailed,
    /// Input not recognized as Doldskrift.
    NotDoldskrift,
}

/// Output of a reader attempt.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ReaderOutput {
    /// Status (always set; check before trusting `value`).
    pub status: ReaderStatus,
    /// Confidence in \[0, 1\] when applicable.
    pub confidence: f64,
    /// Reconstructed value only when `status == Reconstructed`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub value: Option<Value>,
    /// Content id when available (SHA-256 hex).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub content_id: Option<String>,
    /// Human-readable reason (no security theater).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    /// Reader that produced this output.
    pub reader_id: String,
}

impl ReaderOutput {
    /// True when semantics are trustworthy.
    pub fn ok(&self) -> bool {
        self.status == ReaderStatus::Reconstructed && self.value.is_some()
    }
}

/// Trait for Neural readers (DSK-R).
pub trait ReaderBackend {
    /// Reader id.
    fn id(&self) -> &str;

    /// Compatibility declaration.
    fn compatibility(&self) -> ReaderCompatibility;

    /// Reconstruct semantics from an observation graph.
    ///
    /// MUST NOT invent plausible plaintext on failure — return a non-Reconstructed status.
    fn reconstruct(&self, observation: &ObservationGraph) -> Result<ReaderOutput>;

    /// Reset session state (isolation stub).
    fn reset(&mut self) {
        // Default: stateless.
    }
}

/// Deterministic baseline reader for CI — exact reverse of [`DeterministicComposer`].
#[derive(Debug, Default, Clone)]
pub struct DeterministicBaseline {
    /// Supported epochs.
    supported: Vec<GrammarEpoch>,
}

impl DeterministicBaseline {
    /// Create with E0001 support.
    pub fn new() -> Self {
        Self {
            supported: vec![GrammarEpoch::E0001],
        }
    }

    /// Create with an explicit epoch allow-list.
    pub fn with_epochs(supported: Vec<GrammarEpoch>) -> Self {
        Self { supported }
    }
}

impl ReaderBackend for DeterministicBaseline {
    fn id(&self) -> &str {
        "deterministic-baseline/1"
    }

    fn compatibility(&self) -> ReaderCompatibility {
        ReaderCompatibility {
            reader_id: self.id().into(),
            supported_epochs: self.supported.clone(),
        }
    }

    fn reconstruct(&self, observation: &ObservationGraph) -> Result<ReaderOutput> {
        if !observation.is_doldskrift {
            return Ok(ReaderOutput {
                status: ReaderStatus::NotDoldskrift,
                confidence: 0.0,
                value: None,
                content_id: None,
                message: Some("observation is not Doldskrift".into()),
                reader_id: self.id().into(),
            });
        }

        let Some(graph) = observation.latent_carrier.as_ref() else {
            return Ok(ReaderOutput {
                status: ReaderStatus::ReconstructionFailed,
                confidence: 0.0,
                value: None,
                content_id: None,
                message: Some(
                    "DeterministicBaseline requires latent_carrier (camera path not implemented)"
                        .into(),
                ),
                reader_id: self.id().into(),
            });
        };

        let epoch = &graph.meta.epoch;
        if !self.compatibility().supports(epoch) {
            let status = if epoch.number == 0 {
                ReaderStatus::UnknownGrammar
            } else {
                ReaderStatus::Incompatible
            };
            return Ok(ReaderOutput {
                status,
                confidence: 0.0,
                value: None,
                content_id: graph.meta.content_id.clone(),
                message: Some(format!(
                    "reader {} does not support epoch {}",
                    self.id(),
                    epoch
                )),
                reader_id: self.id().into(),
            });
        }

        match latent_to_value(graph) {
            Ok(value) => Ok(ReaderOutput {
                status: ReaderStatus::Reconstructed,
                confidence: 1.0,
                content_id: graph.meta.content_id.clone(),
                value: Some(value),
                message: None,
                reader_id: self.id().into(),
            }),
            Err(e) => Ok(ReaderOutput {
                status: ReaderStatus::ReconstructionFailed,
                confidence: 0.0,
                value: None,
                content_id: graph.meta.content_id.clone(),
                message: Some(e.to_string()),
                reader_id: self.id().into(),
            }),
        }
    }
}

/// Mock reader — alias behavior of DeterministicBaseline with a distinct id for demos.
#[derive(Debug, Default, Clone)]
pub struct MockReader {
    inner: DeterministicBaseline,
}

impl MockReader {
    /// Create mock reader.
    pub fn new() -> Self {
        Self {
            inner: DeterministicBaseline::new(),
        }
    }
}

impl ReaderBackend for MockReader {
    fn id(&self) -> &str {
        "mock-reader/1"
    }

    fn compatibility(&self) -> ReaderCompatibility {
        let mut c = self.inner.compatibility();
        c.reader_id = self.id().into();
        c
    }

    fn reconstruct(&self, observation: &ObservationGraph) -> Result<ReaderOutput> {
        let mut out = self.inner.reconstruct(observation)?;
        out.reader_id = self.id().into();
        Ok(out)
    }
}

/// Session-isolated wrapper that clears ephemeral state on reset.
#[derive(Debug, Clone)]
pub struct SessionReader<R: ReaderBackend> {
    inner: R,
    /// Call counter (stub isolation evidence).
    pub calls: u64,
}

impl<R: ReaderBackend> SessionReader<R> {
    /// Wrap a backend.
    pub fn new(inner: R) -> Self {
        Self { inner, calls: 0 }
    }
}

impl<R: ReaderBackend> ReaderBackend for SessionReader<R> {
    fn id(&self) -> &str {
        self.inner.id()
    }

    fn compatibility(&self) -> ReaderCompatibility {
        self.inner.compatibility()
    }

    fn reconstruct(&self, observation: &ObservationGraph) -> Result<ReaderOutput> {
        // Note: calls bump requires &mut — use reset path for isolation demos.
        self.inner.reconstruct(observation)
    }

    fn reset(&mut self) {
        self.calls = 0;
        self.inner.reset();
    }
}

/// Stub for future Gemma-based reader. Enabled only with `gemma-reader` feature.
/// Does **not** download or run weights; returns `ReconstructionFailed`.
#[cfg(feature = "gemma-reader")]
#[derive(Debug, Default, Clone)]
pub struct GemmaReaderStub;

#[cfg(feature = "gemma-reader")]
impl ReaderBackend for GemmaReaderStub {
    fn id(&self) -> &str {
        "gemma-reader/stub"
    }

    fn compatibility(&self) -> ReaderCompatibility {
        ReaderCompatibility {
            reader_id: self.id().into(),
            supported_epochs: vec![GrammarEpoch::E0001],
        }
    }

    fn reconstruct(&self, observation: &ObservationGraph) -> Result<ReaderOutput> {
        let _ = observation;
        Ok(ReaderOutput {
            status: ReaderStatus::ReconstructionFailed,
            confidence: 0.0,
            value: None,
            content_id: None,
            message: Some(
                "GemmaReader stub: trained inference not wired; use DeterministicBaseline/MockReader"
                    .into(),
            ),
            reader_id: self.id().into(),
        })
    }
}

/// Reader that only supports a future epoch — used in wrong-reader tests.
#[derive(Debug, Clone)]
pub struct EpochLockedReader {
    /// Epochs this reader accepts.
    pub supported: Vec<GrammarEpoch>,
    id: String,
}

impl EpochLockedReader {
    /// Lock to a specific epoch.
    pub fn only(epoch: GrammarEpoch) -> Self {
        Self {
            supported: vec![epoch],
            id: format!("epoch-locked/{}", epoch.label()),
        }
    }
}

impl ReaderBackend for EpochLockedReader {
    fn id(&self) -> &str {
        &self.id
    }

    fn compatibility(&self) -> ReaderCompatibility {
        ReaderCompatibility {
            reader_id: self.id.clone(),
            supported_epochs: self.supported.clone(),
        }
    }

    fn reconstruct(&self, observation: &ObservationGraph) -> Result<ReaderOutput> {
        DeterministicBaseline::with_epochs(self.supported.clone())
            .reconstruct(observation)
            .map(|mut o| {
                o.reader_id = self.id.clone();
                o
            })
    }
}

fn latent_to_value(graph: &LatentGraph) -> Result<Value> {
    let root = graph
        .nodes
        .iter()
        .find(|n| n.kind == LatentNodeKind::Root)
        .ok_or_else(|| Error::Semantic("latent graph missing root".into()))?;
    let child = graph
        .edges
        .iter()
        .find(|e| e.from == root.id && e.rel == "child")
        .ok_or_else(|| Error::Semantic("root missing child edge".into()))?;
    decode_node(graph, &child.to)
}

fn decode_node(graph: &LatentGraph, id: &str) -> Result<Value> {
    let node = graph
        .node(id)
        .ok_or_else(|| Error::Semantic(format!("missing node {id}")))?;
    match node.kind {
        LatentNodeKind::Null => Ok(Value::Null),
        LatentNodeKind::Atom | LatentNodeKind::Opaque => decode_atom(node),
        LatentNodeKind::Sequence => {
            let mut items: Vec<(usize, Value)> = Vec::new();
            for e in &graph.edges {
                if e.from == id {
                    if let Some(rest) = e.rel.strip_prefix("item:") {
                        let idx: usize = rest
                            .parse()
                            .map_err(|_| Error::Semantic("bad item index".into()))?;
                        items.push((idx, decode_node(graph, &e.to)?));
                    }
                }
            }
            items.sort_by_key(|(i, _)| *i);
            Ok(Value::Array(items.into_iter().map(|(_, v)| v).collect()))
        }
        LatentNodeKind::Record => {
            let mut map = BTreeMap::new();
            for e in &graph.edges {
                if e.from == id && e.rel == "field" {
                    let field = graph
                        .node(&e.to)
                        .ok_or_else(|| Error::Semantic("missing field node".into()))?;
                    let name = field
                        .attrs
                        .get("name")
                        .cloned()
                        .or_else(|| {
                            field
                                .value
                                .as_ref()
                                .and_then(|v| v.as_str().map(str::to_string))
                        })
                        .ok_or_else(|| Error::Semantic("field missing name".into()))?;
                    let value_edge = graph
                        .edges
                        .iter()
                        .find(|x| x.from == field.id && x.rel == "value")
                        .ok_or_else(|| Error::Semantic("field missing value".into()))?;
                    map.insert(name, decode_node(graph, &value_edge.to)?);
                }
            }
            Ok(Value::Map(map))
        }
        LatentNodeKind::Field | LatentNodeKind::Root => Err(Error::Semantic(
            "unexpected node kind at decode root of subtree".into(),
        )),
    }
}

fn decode_atom(node: &super::lsg::LatentNode) -> Result<Value> {
    let v = node
        .value
        .as_ref()
        .ok_or_else(|| Error::Semantic("atom missing value".into()))?;
    if let Some(t) = node.attrs.get("type") {
        match t.as_str() {
            "timestamp_ms" => {
                let n = v
                    .as_i64()
                    .ok_or_else(|| Error::Semantic("bad timestamp".into()))?;
                return Ok(Value::Timestamp(n));
            }
            "uuid" => {
                let s = v
                    .as_str()
                    .ok_or_else(|| Error::Semantic("bad uuid".into()))?;
                let bytes = hex::decode(s).map_err(|e| Error::Semantic(e.to_string()))?;
                if bytes.len() != 16 {
                    return Err(Error::Semantic("uuid must be 16 bytes".into()));
                }
                let mut arr = [0u8; 16];
                arr.copy_from_slice(&bytes);
                return Ok(Value::Uuid(arr));
            }
            "uri" => {
                return Ok(Value::Uri(
                    v.as_str()
                        .ok_or_else(|| Error::Semantic("bad uri".into()))?
                        .into(),
                ));
            }
            "identifier" => {
                return Ok(Value::Identifier(
                    v.as_str()
                        .ok_or_else(|| Error::Semantic("bad identifier".into()))?
                        .into(),
                ));
            }
            "bytes-hex" => {
                let s = v
                    .as_str()
                    .ok_or_else(|| Error::Semantic("bad bytes".into()))?;
                let bytes = hex::decode(s).map_err(|e| Error::Semantic(e.to_string()))?;
                return Ok(Value::Bytes(bytes));
            }
            _ => {}
        }
    }
    match v {
        serde_json::Value::Null => Ok(Value::Null),
        serde_json::Value::Bool(b) => Ok(Value::Bool(*b)),
        serde_json::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                Ok(Value::Integer(i))
            } else if let Some(f) = n.as_f64() {
                Ok(Value::Float(f))
            } else {
                Err(Error::Semantic("unsupported number".into()))
            }
        }
        serde_json::Value::String(s) => Ok(Value::String(s.clone())),
        other => Err(Error::Semantic(format!("unsupported atom JSON: {other}"))),
    }
}