Skip to main content

vibe/cbor_ast/cbor_ld/
value_codec.rs

1//! Deterministic W3C CBOR-LD (`0xD9 0x0501`) binary codec for VibeScript [`Value`].
2
3use std::collections::BTreeMap;
4
5use super::super::codec::{CborDecoder, CborEncoder};
6use super::super::decode::decode_expr;
7use super::super::encode::encode_expr;
8use super::super::DecodeError;
9use super::terms::*;
10use crate::value::{
11    AssetRef, CausalRelation, ConservationQuantity, ConservationResult, DisclosureBoundary,
12    Duration, EnumValue, FieldRef, Frame, GeometryRef, Instant, MaterialRef, Miscibility,
13    Mixture, MixturePhase, Pose, Quantity, QuinRef, SpeciesRef, TensorRef, TimeScale, Transform,
14    Value, WorldLine,
15};
16
17/// Encodes a runtime [`Value`] into deterministic compressed W3C CBOR-LD (`0xD9 0x0501`).
18pub fn encode_value_cbor_ld(value: &Value, context_iri: &str) -> Vec<u8> {
19    let mut enc = CborEncoder::new();
20    enc.tag(TAG_CBOR_LD_COMPRESSED);
21    enc.map(2);
22    enc.uint(1); // 1 = "@context"
23    write_term_or_str(&mut enc, context_iri);
24    enc.uint(5); // 5 = "@graph" (payload)
25    encode_val(&mut enc, value);
26    enc.finish()
27}
28
29/// Decodes compressed (`0x0501`) or uncompressed (`0x0500`) CBOR-LD bytes into `(context_iri, Value)`.
30pub fn decode_value_cbor_ld(bytes: &[u8]) -> Result<(String, Value), DecodeError> {
31    let mut dec = CborDecoder::new(bytes);
32    let tag = dec.tag()?;
33    if tag != TAG_CBOR_LD_COMPRESSED && tag != TAG_CBOR_LD_UNCOMPRESSED {
34        return Err(DecodeError::UnexpectedTag(tag));
35    }
36    let map_len = dec.map()?;
37    let mut context_iri = DEFAULT_CONTEXT_IRI.to_string();
38    let mut payload: Option<Value> = None;
39    for _ in 0..map_len {
40        let key = read_term_or_str(&mut dec, &context_iri)?;
41        match key.as_str() {
42            "@context" => {
43                context_iri = read_term_or_str(&mut dec, "")?;
44            }
45            "@graph" | "@value" => {
46                payload = Some(decode_val(&mut dec, &context_iri)?);
47            }
48            _ => {
49                dec.skip()?;
50            }
51        }
52    }
53    let value = payload.ok_or(DecodeError::MissingField("@graph"))?;
54    Ok((context_iri, value))
55}
56
57fn write_f64(enc: &mut CborEncoder, v: f64) {
58    enc.write_u8(0xFB); // major 7, ai 27 (IEEE 754 binary64)
59    for b in v.to_bits().to_be_bytes() {
60        enc.write_u8(b);
61    }
62}
63
64fn write_f64_slice(enc: &mut CborEncoder, values: &[f64]) {
65    enc.array(values.len() as u64);
66    for &v in values {
67        write_f64(enc, v);
68    }
69}
70
71fn read_f64_vec(dec: &mut CborDecoder<'_>) -> Result<Vec<f64>, DecodeError> {
72    let n = dec.array()?;
73    let mut out = Vec::with_capacity(n as usize);
74    for _ in 0..n {
75        out.push(read_f64(dec)?);
76    }
77    Ok(out)
78}
79
80fn write_opt_str(enc: &mut CborEncoder, s: Option<&str>) {
81    match s {
82        Some(v) => enc.str(v),
83        None => enc.null(),
84    }
85}
86
87fn read_opt_str(dec: &mut CborDecoder<'_>) -> Result<Option<String>, DecodeError> {
88    if dec.is_null()? {
89        dec.null()?;
90        Ok(None)
91    } else {
92        Ok(Some(dec.str()?))
93    }
94}
95
96fn read_f64(dec: &mut CborDecoder<'_>) -> Result<f64, DecodeError> {
97    let b = dec.read_u8()?;
98    if b != 0xFB {
99        return Err(DecodeError::UnexpectedType("expected f64 (0xFB)"));
100    }
101    let mut arr = [0u8; 8];
102    for slot in &mut arr {
103        *slot = dec.read_u8()?;
104    }
105    Ok(f64::from_bits(u64::from_be_bytes(arr)))
106}
107
108fn write_bytes(enc: &mut CborEncoder, bytes: &[u8]) {
109    enc.write_type_and_len(2, bytes.len() as u64);
110    for &b in bytes {
111        enc.write_u8(b);
112    }
113}
114
115fn read_bytes(dec: &mut CborDecoder<'_>) -> Result<Vec<u8>, DecodeError> {
116    let (major, len) = dec.read_type_and_len()?;
117    if major != 2 {
118        return Err(DecodeError::UnexpectedType("expected byte string"));
119    }
120    let mut out = Vec::with_capacity(len as usize);
121    for _ in 0..len {
122        out.push(dec.read_u8()?);
123    }
124    Ok(out)
125}
126
127fn write_term_or_str(enc: &mut CborEncoder, s: &str) {
128    if let Some(id) = lookup_static_term_id(s) {
129        enc.uint(id);
130    } else {
131        enc.str(s);
132    }
133}
134
135fn read_term_or_str(dec: &mut CborDecoder<'_>, context_iri: &str) -> Result<String, DecodeError> {
136    let next = dec.peek()?;
137    if (next >> 5) == 0 {
138        let id = dec.uint()?;
139        expand_term(id, context_iri)
140            .ok_or_else(|| DecodeError::InvalidCbor(format!("unknown term id {id}")))
141    } else {
142        dec.str()
143    }
144}
145
146fn encode_val(enc: &mut CborEncoder, val: &Value) {
147    match val {
148        Value::Null => enc.null(),
149        Value::Bool(b) => enc.bool(*b),
150        Value::I64(n) => enc.int(*n),
151        Value::U64(n) => {
152            enc.tag(TAG_VIBE_U64);
153            enc.uint(*n);
154        }
155        Value::F64(f) => write_f64(enc, *f),
156        Value::String(s) => enc.str(s),
157        Value::Iri(iri) => {
158            enc.tag(TAG_VIBE_IRI);
159            write_term_or_str(enc, iri);
160        }
161        Value::Prefixed(prefix, local) => {
162            enc.tag(TAG_VIBE_PREFIXED);
163            enc.array(2);
164            enc.str(prefix);
165            enc.str(local);
166        }
167        Value::Blank(b) => {
168            enc.tag(TAG_VIBE_BLANK);
169            enc.str(b);
170        }
171        Value::Var(v) => {
172            enc.tag(TAG_VIBE_VAR);
173            enc.str(v);
174        }
175        Value::List(items) => {
176            enc.array(items.len() as u64);
177            for item in items {
178                encode_val(enc, item);
179            }
180        }
181        Value::Record(map) => {
182            // RFC 8949 ยง4.2 deterministic CBOR: sort keys by encoded key bytes.
183            let mut encoded_entries: Vec<(Vec<u8>, &Value)> = Vec::with_capacity(map.len());
184            for (k, v) in map {
185                let mut k_enc = CborEncoder::new();
186                write_term_or_str(&mut k_enc, k);
187                encoded_entries.push((k_enc.finish(), v));
188            }
189            encoded_entries.sort_by(|a, b| a.0.cmp(&b.0));
190            enc.map(encoded_entries.len() as u64);
191            for (k_bytes, v) in encoded_entries {
192                for b in k_bytes {
193                    enc.write_u8(b);
194                }
195                encode_val(enc, v);
196            }
197        }
198        Value::Quantity(q) => {
199            enc.tag(TAG_VIBE_QUANTITY);
200            enc.array(2);
201            write_f64(enc, q.value);
202            write_term_or_str(enc, &q.unit);
203        }
204        Value::Instant(inst) => {
205            enc.tag(TAG_VIBE_INSTANT);
206            enc.array(5);
207            let scale_id = match inst.scale {
208                TimeScale::Unix => 0,
209                TimeScale::Tai => 1,
210                TimeScale::Gps => 2,
211                TimeScale::Monotonic => 3,
212                TimeScale::Proper => 4,
213            };
214            enc.uint(scale_id);
215            enc.int(inst.secs);
216            enc.uint(inst.nanos as u64);
217            match &inst.frame {
218                Some(f) => enc.str(f),
219                None => enc.null(),
220            }
221            match &inst.seal {
222                Some(sig) => write_bytes(enc, sig),
223                None => enc.null(),
224            }
225        }
226        Value::Duration(dur) => {
227            enc.tag(TAG_VIBE_DURATION);
228            enc.array(2);
229            enc.int(dur.secs);
230            enc.uint(dur.nanos as u64);
231        }
232        Value::QuinRef(q) => {
233            enc.tag(TAG_VIBE_QUIN_REF);
234            let mut raw = [0u8; 48];
235            for (i, word) in q.raw_fields().iter().enumerate() {
236                raw[i * 8..(i + 1) * 8].copy_from_slice(&word.to_be_bytes());
237            }
238            write_bytes(enc, &raw);
239        }
240        Value::DisclosureDenied { capability, reason } => {
241            enc.tag(TAG_VIBE_DISCLOSURE_DENIED);
242            enc.array(2);
243            enc.str(capability);
244            enc.str(reason);
245        }
246        Value::Receipt => {
247            enc.tag(TAG_VIBE_RECEIPT);
248            enc.null();
249        }
250        Value::Ok(inner) => {
251            enc.tag(TAG_VIBE_OK);
252            encode_val(enc, inner);
253        }
254        Value::Err(inner) => {
255            enc.tag(TAG_VIBE_ERR);
256            encode_val(enc, inner);
257        }
258        Value::Triple(s, p, o) => {
259            enc.tag(TAG_VIBE_TRIPLE);
260            enc.array(3);
261            encode_val(enc, s);
262            encode_val(enc, p);
263            encode_val(enc, o);
264        }
265        Value::Reified { s, p, o, r } => {
266            enc.tag(TAG_VIBE_REIFIED);
267            enc.array(4);
268            encode_val(enc, s);
269            encode_val(enc, p);
270            encode_val(enc, o);
271            encode_val(enc, r);
272        }
273        Value::Frame(f) => {
274            enc.tag(TAG_VIBE_FRAME);
275            enc.array(3);
276            write_f64_slice(enc, &f.origin);
277            enc.array(f.basis.len() as u64);
278            for row in &f.basis {
279                write_f64_slice(enc, row);
280            }
281            write_opt_str(enc, f.parent.as_deref());
282        }
283        Value::Pose(p) => {
284            enc.tag(TAG_VIBE_POSE);
285            enc.array(3);
286            write_f64_slice(enc, &p.position);
287            write_f64_slice(enc, &p.orientation);
288            write_opt_str(enc, p.frame.as_deref());
289        }
290        Value::Transform(t) => {
291            enc.tag(TAG_VIBE_TRANSFORM);
292            enc.array(4);
293            write_f64_slice(enc, &t.translate);
294            write_f64_slice(enc, &t.rotate);
295            write_f64_slice(enc, &t.scale);
296            write_f64_slice(enc, &t.skew);
297        }
298        Value::FieldRef(r) => {
299            enc.tag(TAG_VIBE_FIELD_REF);
300            enc.array(2);
301            write_term_or_str(enc, &r.iri);
302            enc.uint(r.hash);
303        }
304        Value::MaterialRef(r) => {
305            enc.tag(TAG_VIBE_MATERIAL_REF);
306            enc.array(2);
307            write_term_or_str(enc, &r.iri);
308            enc.uint(r.hash);
309        }
310        Value::TensorRef(r) => {
311            enc.tag(TAG_VIBE_TENSOR_REF);
312            enc.array(2);
313            enc.uint(r.handle);
314            enc.uint(r.hash);
315        }
316        Value::GeometryRef(r) => {
317            enc.tag(TAG_VIBE_GEOMETRY_REF);
318            enc.array(2);
319            enc.uint(r.handle);
320            enc.uint(r.hash);
321        }
322        Value::AssetRef(r) => {
323            enc.tag(TAG_VIBE_ASSET_REF);
324            enc.array(2);
325            write_term_or_str(enc, &r.iri);
326            enc.uint(r.hash);
327        }
328        Value::WorldLine(w) => {
329            enc.tag(TAG_VIBE_WORLDLINE);
330            enc.array(3);
331            write_term_or_str(enc, &w.iri);
332            enc.str(&w.asserted_by);
333            enc.int(w.created_at);
334        }
335        Value::Enum(e) => {
336            enc.tag(TAG_VIBE_ENUM);
337            enc.array(3);
338            enc.str(&e.enum_name);
339            enc.str(&e.variant_name);
340            enc.array(e.payload.len() as u64);
341            for item in &e.payload {
342                encode_val(enc, item);
343            }
344        }
345        Value::Lambda { params, body } => {
346            enc.tag(TAG_VIBE_LAMBDA);
347            enc.array(2);
348            enc.array(params.len() as u64);
349            for p in params {
350                enc.str(p);
351            }
352            encode_expr(enc, body);
353        }
354        Value::SpeciesRef(s) => {
355            enc.tag(TAG_VIBE_SPECIES_REF);
356            enc.array(2);
357            write_term_or_str(enc, &s.iri);
358            enc.uint(s.hash);
359        }
360        Value::Mixture(m) => {
361            enc.tag(TAG_VIBE_MIXTURE);
362            enc.array(4);
363            write_opt_str(enc, m.iri.as_deref());
364            enc.array(m.components.len() as u64);
365            for (sp, frac) in &m.components {
366                enc.array(3);
367                write_term_or_str(enc, &sp.iri);
368                enc.uint(sp.hash);
369                write_f64(enc, *frac);
370            }
371            enc.uint(match m.phase {
372                MixturePhase::Solid => 0,
373                MixturePhase::Liquid => 1,
374                MixturePhase::Gas => 2,
375                MixturePhase::Plasma => 3,
376                MixturePhase::Supercritical => 4,
377            });
378            enc.uint(match m.miscibility {
379                Miscibility::Miscible => 0,
380                Miscibility::Immiscible => 1,
381                Miscibility::Partial => 2,
382            });
383        }
384        Value::Conservation(c) => {
385            enc.tag(TAG_VIBE_CONSERVATION);
386            enc.array(5);
387            enc.uint(match c.quantity {
388                ConservationQuantity::Mass => 0,
389                ConservationQuantity::Mole => 1,
390                ConservationQuantity::Energy => 2,
391                ConservationQuantity::Charge => 3,
392                ConservationQuantity::Momentum => 4,
393                ConservationQuantity::AngularMomentum => 5,
394            });
395            write_f64(enc, c.before);
396            write_f64(enc, c.after);
397            enc.bool(c.conserved);
398            write_f64(enc, c.tolerance);
399        }
400        Value::Causal(c) => {
401            enc.tag(TAG_VIBE_CAUSAL);
402            enc.uint(match c {
403                CausalRelation::Timelike => 0,
404                CausalRelation::Lightlike => 1,
405                CausalRelation::Spacelike => 2,
406            });
407        }
408        Value::DisclosureBoundary(b) => {
409            enc.tag(TAG_VIBE_DISCLOSURE_BOUNDARY);
410            enc.array(4);
411            enc.bool(b.publication);
412            enc.bool(b.replication);
413            enc.bool(b.agency);
414            enc.bool(b.exfiltration);
415        }
416    }
417}
418
419fn decode_val(dec: &mut CborDecoder<'_>, context_iri: &str) -> Result<Value, DecodeError> {
420    let peek = dec.peek()?;
421    let major = peek >> 5;
422    match major {
423        0 | 1 => Ok(Value::I64(dec.int()?)),
424        3 => Ok(Value::String(dec.str()?)),
425        4 => {
426            let len = dec.array()?;
427            let mut items = Vec::with_capacity(len as usize);
428            for _ in 0..len {
429                items.push(decode_val(dec, context_iri)?);
430            }
431            Ok(Value::List(items))
432        }
433        5 => {
434            let len = dec.map()?;
435            let mut map = BTreeMap::new();
436            for _ in 0..len {
437                let k = read_term_or_str(dec, context_iri)?;
438                let v = decode_val(dec, context_iri)?;
439                map.insert(k, v);
440            }
441            Ok(Value::Record(map))
442        }
443        6 => decode_tagged_val(dec, context_iri),
444        7 => match peek {
445            0xF4 | 0xF5 => Ok(Value::Bool(dec.bool()?)),
446            0xF6 => {
447                dec.null()?;
448                Ok(Value::Null)
449            }
450            0xFB => Ok(Value::F64(read_f64(dec)?)),
451            _ => Err(DecodeError::UnexpectedType("unsupported major 7 value")),
452        },
453        _ => Err(DecodeError::UnexpectedType("unsupported CBOR major type")),
454    }
455}
456
457fn decode_tagged_val(dec: &mut CborDecoder<'_>, context_iri: &str) -> Result<Value, DecodeError> {
458    let tag = dec.tag()?;
459    match tag {
460        TAG_VIBE_U64 => Ok(Value::U64(dec.uint()?)),
461        TAG_VIBE_IRI => Ok(Value::Iri(read_term_or_str(dec, context_iri)?)),
462        TAG_VIBE_PREFIXED => {
463            if dec.array()? != 2 {
464                return Err(DecodeError::InvalidCbor("prefixed requires len 2".into()));
465            }
466            Ok(Value::Prefixed(dec.str()?, dec.str()?))
467        }
468        TAG_VIBE_BLANK => Ok(Value::Blank(dec.str()?)),
469        TAG_VIBE_VAR => Ok(Value::Var(dec.str()?)),
470        TAG_VIBE_QUANTITY => {
471            if dec.array()? != 2 {
472                return Err(DecodeError::InvalidCbor("quantity requires len 2".into()));
473            }
474            let value = read_f64(dec)?;
475            let unit = read_term_or_str(dec, context_iri)?;
476            Ok(Value::Quantity(Quantity { value, unit }))
477        }
478        TAG_VIBE_INSTANT => {
479            if dec.array()? != 5 {
480                return Err(DecodeError::InvalidCbor("instant requires len 5".into()));
481            }
482            let scale = match dec.uint()? {
483                0 => TimeScale::Unix,
484                1 => TimeScale::Tai,
485                2 => TimeScale::Gps,
486                3 => TimeScale::Monotonic,
487                4 => TimeScale::Proper,
488                s => return Err(DecodeError::InvalidCbor(format!("invalid TimeScale {s}"))),
489            };
490            let secs = dec.int()?;
491            let nanos = dec.uint()? as u32;
492            let frame = if dec.is_null()? {
493                dec.null()?;
494                None
495            } else {
496                Some(dec.str()?)
497            };
498            let seal = if dec.is_null()? {
499                dec.null()?;
500                None
501            } else {
502                let raw = read_bytes(dec)?;
503                let arr: [u8; 64] = raw
504                    .try_into()
505                    .map_err(|_| DecodeError::InvalidCbor("seal must be 64 bytes".into()))?;
506                Some(arr)
507            };
508            Ok(Value::Instant(Instant {
509                scale,
510                secs,
511                nanos,
512                frame,
513                seal,
514            }))
515        }
516        TAG_VIBE_DURATION => {
517            if dec.array()? != 2 {
518                return Err(DecodeError::InvalidCbor("duration requires len 2".into()));
519            }
520            Ok(Value::Duration(Duration {
521                secs: dec.int()?,
522                nanos: dec.uint()? as u32,
523            }))
524        }
525        TAG_VIBE_QUIN_REF => {
526            let raw = read_bytes(dec)?;
527            if raw.len() != 48 {
528                return Err(DecodeError::InvalidCbor("QuinRef must be 48 bytes".into()));
529            }
530            let mut words = [0u64; 6];
531            for (i, w) in words.iter_mut().enumerate() {
532                let mut b = [0u8; 8];
533                b.copy_from_slice(&raw[i * 8..(i + 1) * 8]);
534                *w = u64::from_be_bytes(b);
535            }
536            Ok(Value::QuinRef(QuinRef::from_raw(
537                words[0], words[1], words[2], words[3], words[4], words[5],
538            )))
539        }
540        TAG_VIBE_DISCLOSURE_DENIED => {
541            if dec.array()? != 2 {
542                return Err(DecodeError::InvalidCbor(
543                    "DisclosureDenied requires len 2".into(),
544                ));
545            }
546            Ok(Value::DisclosureDenied {
547                capability: dec.str()?,
548                reason: dec.str()?,
549            })
550        }
551        TAG_VIBE_RECEIPT => {
552            dec.null()?;
553            Ok(Value::Receipt)
554        }
555        TAG_VIBE_OK => Ok(Value::Ok(Box::new(decode_val(dec, context_iri)?))),
556        TAG_VIBE_ERR => Ok(Value::Err(Box::new(decode_val(dec, context_iri)?))),
557        TAG_VIBE_TRIPLE => {
558            if dec.array()? != 3 {
559                return Err(DecodeError::InvalidCbor("Triple requires len 3".into()));
560            }
561            Ok(Value::Triple(
562                Box::new(decode_val(dec, context_iri)?),
563                Box::new(decode_val(dec, context_iri)?),
564                Box::new(decode_val(dec, context_iri)?),
565            ))
566        }
567        TAG_VIBE_REIFIED => {
568            if dec.array()? != 4 {
569                return Err(DecodeError::InvalidCbor("Reified requires len 4".into()));
570            }
571            Ok(Value::Reified {
572                s: Box::new(decode_val(dec, context_iri)?),
573                p: Box::new(decode_val(dec, context_iri)?),
574                o: Box::new(decode_val(dec, context_iri)?),
575                r: Box::new(decode_val(dec, context_iri)?),
576            })
577        }
578        TAG_VIBE_FRAME => {
579            if dec.array()? != 3 {
580                return Err(DecodeError::InvalidCbor("Frame requires len 3".into()));
581            }
582            let origin = read_f64_vec(dec)?;
583            let rows = dec.array()?;
584            let mut basis = Vec::with_capacity(rows as usize);
585            for _ in 0..rows {
586                basis.push(read_f64_vec(dec)?);
587            }
588            let parent = read_opt_str(dec)?;
589            Ok(Value::Frame(Frame {
590                origin,
591                basis,
592                parent,
593            }))
594        }
595        TAG_VIBE_POSE => {
596            if dec.array()? != 3 {
597                return Err(DecodeError::InvalidCbor("Pose requires len 3".into()));
598            }
599            Ok(Value::Pose(Pose {
600                position: read_f64_vec(dec)?,
601                orientation: read_f64_vec(dec)?,
602                frame: read_opt_str(dec)?,
603            }))
604        }
605        TAG_VIBE_TRANSFORM => {
606            if dec.array()? != 4 {
607                return Err(DecodeError::InvalidCbor("Transform requires len 4".into()));
608            }
609            Ok(Value::Transform(Transform {
610                translate: read_f64_vec(dec)?,
611                rotate: read_f64_vec(dec)?,
612                scale: read_f64_vec(dec)?,
613                skew: read_f64_vec(dec)?,
614            }))
615        }
616        TAG_VIBE_FIELD_REF => {
617            if dec.array()? != 2 {
618                return Err(DecodeError::InvalidCbor("FieldRef requires len 2".into()));
619            }
620            Ok(Value::FieldRef(FieldRef {
621                iri: read_term_or_str(dec, context_iri)?,
622                hash: dec.uint()?,
623            }))
624        }
625        TAG_VIBE_MATERIAL_REF => {
626            if dec.array()? != 2 {
627                return Err(DecodeError::InvalidCbor(
628                    "MaterialRef requires len 2".into(),
629                ));
630            }
631            Ok(Value::MaterialRef(MaterialRef {
632                iri: read_term_or_str(dec, context_iri)?,
633                hash: dec.uint()?,
634            }))
635        }
636        TAG_VIBE_TENSOR_REF => {
637            if dec.array()? != 2 {
638                return Err(DecodeError::InvalidCbor("TensorRef requires len 2".into()));
639            }
640            Ok(Value::TensorRef(TensorRef {
641                handle: dec.uint()?,
642                hash: dec.uint()?,
643            }))
644        }
645        TAG_VIBE_GEOMETRY_REF => {
646            if dec.array()? != 2 {
647                return Err(DecodeError::InvalidCbor(
648                    "GeometryRef requires len 2".into(),
649                ));
650            }
651            Ok(Value::GeometryRef(GeometryRef {
652                handle: dec.uint()?,
653                hash: dec.uint()?,
654            }))
655        }
656        TAG_VIBE_ASSET_REF => {
657            if dec.array()? != 2 {
658                return Err(DecodeError::InvalidCbor("AssetRef requires len 2".into()));
659            }
660            Ok(Value::AssetRef(AssetRef {
661                iri: read_term_or_str(dec, context_iri)?,
662                hash: dec.uint()?,
663            }))
664        }
665        TAG_VIBE_WORLDLINE => {
666            if dec.array()? != 3 {
667                return Err(DecodeError::InvalidCbor("WorldLine requires len 3".into()));
668            }
669            Ok(Value::WorldLine(WorldLine {
670                iri: read_term_or_str(dec, context_iri)?,
671                asserted_by: dec.str()?,
672                created_at: dec.int()?,
673            }))
674        }
675        TAG_VIBE_ENUM => {
676            if dec.array()? != 3 {
677                return Err(DecodeError::InvalidCbor("Enum requires len 3".into()));
678            }
679            let enum_name = dec.str()?;
680            let variant_name = dec.str()?;
681            let n = dec.array()?;
682            let mut payload = Vec::with_capacity(n as usize);
683            for _ in 0..n {
684                payload.push(decode_val(dec, context_iri)?);
685            }
686            Ok(Value::Enum(EnumValue {
687                enum_name,
688                variant_name,
689                payload,
690            }))
691        }
692        TAG_VIBE_LAMBDA => {
693            if dec.array()? != 2 {
694                return Err(DecodeError::InvalidCbor("Lambda requires len 2".into()));
695            }
696            let n = dec.array()?;
697            let mut params = Vec::with_capacity(n as usize);
698            for _ in 0..n {
699                params.push(dec.str()?);
700            }
701            let body = Box::new(decode_expr(dec)?);
702            Ok(Value::Lambda { params, body })
703        }
704        TAG_VIBE_SPECIES_REF => {
705            if dec.array()? != 2 {
706                return Err(DecodeError::InvalidCbor("SpeciesRef requires len 2".into()));
707            }
708            Ok(Value::SpeciesRef(SpeciesRef {
709                iri: read_term_or_str(dec, context_iri)?,
710                hash: dec.uint()?,
711            }))
712        }
713        TAG_VIBE_MIXTURE => {
714            if dec.array()? != 4 {
715                return Err(DecodeError::InvalidCbor("Mixture requires len 4".into()));
716            }
717            let iri = read_opt_str(dec)?;
718            let n = dec.array()?;
719            let mut components = Vec::with_capacity(n as usize);
720            for _ in 0..n {
721                if dec.array()? != 3 {
722                    return Err(DecodeError::InvalidCbor(
723                        "Mixture component requires len 3".into(),
724                    ));
725                }
726                let sp = SpeciesRef {
727                    iri: read_term_or_str(dec, context_iri)?,
728                    hash: dec.uint()?,
729                };
730                let frac = read_f64(dec)?;
731                components.push((sp, frac));
732            }
733            let phase = match dec.uint()? {
734                0 => MixturePhase::Solid,
735                1 => MixturePhase::Liquid,
736                2 => MixturePhase::Gas,
737                3 => MixturePhase::Plasma,
738                4 => MixturePhase::Supercritical,
739                p => return Err(DecodeError::InvalidCbor(format!("invalid MixturePhase {p}"))),
740            };
741            let miscibility = match dec.uint()? {
742                0 => Miscibility::Miscible,
743                1 => Miscibility::Immiscible,
744                2 => Miscibility::Partial,
745                m => return Err(DecodeError::InvalidCbor(format!("invalid Miscibility {m}"))),
746            };
747            Ok(Value::Mixture(Mixture {
748                iri,
749                components,
750                phase,
751                miscibility,
752            }))
753        }
754        TAG_VIBE_CONSERVATION => {
755            if dec.array()? != 5 {
756                return Err(DecodeError::InvalidCbor(
757                    "Conservation requires len 5".into(),
758                ));
759            }
760            let quantity = match dec.uint()? {
761                0 => ConservationQuantity::Mass,
762                1 => ConservationQuantity::Mole,
763                2 => ConservationQuantity::Energy,
764                3 => ConservationQuantity::Charge,
765                4 => ConservationQuantity::Momentum,
766                5 => ConservationQuantity::AngularMomentum,
767                q => {
768                    return Err(DecodeError::InvalidCbor(format!(
769                        "invalid ConservationQuantity {q}"
770                    )))
771                }
772            };
773            let before = read_f64(dec)?;
774            let after = read_f64(dec)?;
775            let conserved = dec.bool()?;
776            let tolerance = read_f64(dec)?;
777            Ok(Value::Conservation(ConservationResult {
778                quantity,
779                before,
780                after,
781                conserved,
782                tolerance,
783            }))
784        }
785        TAG_VIBE_CAUSAL => {
786            let c = match dec.uint()? {
787                0 => CausalRelation::Timelike,
788                1 => CausalRelation::Lightlike,
789                2 => CausalRelation::Spacelike,
790                v => return Err(DecodeError::InvalidCbor(format!("invalid CausalRelation {v}"))),
791            };
792            Ok(Value::Causal(c))
793        }
794        TAG_VIBE_DISCLOSURE_BOUNDARY => {
795            if dec.array()? != 4 {
796                return Err(DecodeError::InvalidCbor(
797                    "DisclosureBoundary requires len 4".into(),
798                ));
799            }
800            Ok(Value::DisclosureBoundary(DisclosureBoundary {
801                publication: dec.bool()?,
802                replication: dec.bool()?,
803                agency: dec.bool()?,
804                exfiltration: dec.bool()?,
805            }))
806        }
807        other => Err(DecodeError::UnexpectedTag(other)),
808    }
809}