Skip to main content

vibe/
law_package.rs

1//! Law packages as signed content (T72, W10).
2//!
3//! A law declaration carries more than just the condition and
4//! consequence — it carries provenance: who authored it, under what
5//! licence, whether it is physical or fictional, and a cryptographic
6//! signature binding the author to the law's content.
7//!
8//! Without signed law packages, any agent can inject a "law" that
9//! says `transform.dissolve(self)` without anyone knowing who wrote
10//! it or whether it's physically valid. Signed law packages make
11//! the provenance travel with the law.
12//!
13//! ## Structure
14//!
15//! A `LawPackage` wraps a `LawDecl` with:
16//! - **Author DID**: who wrote the law.
17//! - **Licence IRI**: under what terms the law may be used.
18//! - **Physical validity**: is this a physical law (conservation-
19//!   respecting) or a fictional/game rule?
20//! - **Signature**: Ed25519 signature over the law's canonical
21//!   encoding, binding the author to the content.
22//! - **Asserted at**: when the law was authored (Instant).
23//!
24//! Reference: `docs/vibescript-full-impl-PLAN.md` §8.14 T72,
25//! excellence-first §3.8, W10.
26
27use crate::value::{Instant, Value};
28use std::collections::BTreeMap;
29
30/// Whether a law is physically valid or a fictional/game rule (T72).
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
32pub enum LawKind {
33    /// A physical law — respects conservation of mass, energy, charge,
34    /// etc. Violations are diagnostic errors, not gameplay.
35    #[default]
36    Physical,
37    /// A fictional/game rule — may violate physics for narrative or
38    /// gameplay purposes. Provenance still travels, but the kind is
39    /// explicit so physics simulations can reject it.
40    Fictional,
41}
42
43impl LawKind {
44    /// `str` form.
45    pub fn as_str(&self) -> &'static str {
46        match self {
47            Self::Physical => "physical",
48            Self::Fictional => "fictional",
49        }
50    }
51
52    /// Constructs from str.
53    pub fn from_str(s: &str) -> Option<Self> {
54        match s {
55            "physical" => Some(Self::Physical),
56            "fictional" => Some(Self::Fictional),
57            _ => None,
58        }
59    }
60}
61
62/// A signed law package — a law declaration with provenance and
63/// cryptographic signature (T72, W10).
64#[derive(Debug, Clone, PartialEq)]
65pub struct LawPackage {
66    /// The law's name (matches LawDecl.name).
67    pub name: String,
68    /// The law's condition (canonical text form).
69    pub condition_text: String,
70    /// The law's consequence (canonical text form).
71    pub consequence_text: String,
72    /// Who authored the law (DID or IRI).
73    pub author: String,
74    /// Under what licence the law may be used (IRI).
75    pub licence: String,
76    /// Whether the law is physical or fictional.
77    pub kind: LawKind,
78    /// When the law was authored.
79    pub asserted_at: Instant,
80    /// Optional Ed25519 signature over the canonical encoding.
81    pub signature: Option<[u8; 64]>,
82    /// Optional version tag for law evolution.
83    pub version: Option<String>,
84}
85
86impl LawPackage {
87    /// Create a new unsigned law package.
88    pub fn new(
89        name: &str,
90        condition: &str,
91        consequence: &str,
92        author: &str,
93        licence: &str,
94        kind: LawKind,
95        asserted_at: Instant,
96    ) -> Self {
97        Self {
98            name: name.into(),
99            condition_text: condition.into(),
100            consequence_text: consequence.into(),
101            author: author.into(),
102            licence: licence.into(),
103            kind,
104            asserted_at,
105            signature: None,
106            version: None,
107        }
108    }
109
110    /// Attach a signature to the law package.
111    pub fn with_signature(mut self, sig: [u8; 64]) -> Self {
112        self.signature = Some(sig);
113        self
114    }
115
116    /// Attach a version tag.
117    pub fn with_version(mut self, version: &str) -> Self {
118        self.version = Some(version.into());
119        self
120    }
121
122    /// Is the law package signed?
123    pub fn is_signed(&self) -> bool {
124        self.signature.is_some()
125    }
126
127    /// Canonical encoding for signing — the bytes that the signature
128    /// covers. This is a deterministic encoding of the law's content
129    /// (name + condition + consequence + author + licence + kind +
130    /// asserted_at).
131    pub fn canonical_bytes(&self) -> Vec<u8> {
132        let mut buf = Vec::with_capacity(256);
133        buf.extend_from_slice(self.name.as_bytes());
134        buf.push(0);
135        buf.extend_from_slice(self.condition_text.as_bytes());
136        buf.push(0);
137        buf.extend_from_slice(self.consequence_text.as_bytes());
138        buf.push(0);
139        buf.extend_from_slice(self.author.as_bytes());
140        buf.push(0);
141        buf.extend_from_slice(self.licence.as_bytes());
142        buf.push(0);
143        buf.extend_from_slice(self.kind.as_str().as_bytes());
144        buf.push(0);
145        buf.extend_from_slice(&self.asserted_at.secs.to_le_bytes());
146        buf.extend_from_slice(&self.asserted_at.nanos.to_le_bytes());
147        if let Some(ref v) = self.version {
148            buf.push(0);
149            buf.extend_from_slice(v.as_bytes());
150        }
151        buf
152    }
153
154    /// Convert to a Value::Record for inspection and graph storage.
155    pub fn to_value(&self) -> Value {
156        let mut rec = BTreeMap::new();
157        rec.insert("name".into(), Value::String(self.name.clone()));
158        rec.insert(
159            "condition".into(),
160            Value::String(self.condition_text.clone()),
161        );
162        rec.insert(
163            "consequence".into(),
164            Value::String(self.consequence_text.clone()),
165        );
166        rec.insert("author".into(), Value::String(self.author.clone()));
167        rec.insert("licence".into(), Value::String(self.licence.clone()));
168        rec.insert("kind".into(), Value::String(self.kind.as_str().into()));
169        rec.insert(
170            "asserted_at".into(),
171            Value::Instant(self.asserted_at.clone()),
172        );
173        rec.insert("is_signed".into(), Value::Bool(self.is_signed()));
174        if let Some(ref v) = self.version {
175            rec.insert("version".into(), Value::String(v.clone()));
176        }
177        Value::Record(rec)
178    }
179}
180
181/// A registry of law packages — a law store (T72, W10).
182#[derive(Debug, Clone, Default)]
183pub struct LawStore {
184    laws: Vec<LawPackage>,
185}
186
187impl LawStore {
188    /// Creates a new `LawStore`.
189    pub fn new() -> Self {
190        Self::default()
191    }
192
193    /// Register a law package.
194    pub fn register(&mut self, law: LawPackage) -> &mut Self {
195        self.laws.push(law);
196        self
197    }
198
199    /// Get all laws.
200    pub fn all(&self) -> &[LawPackage] {
201        &self.laws
202    }
203
204    /// Get laws by author.
205    pub fn by_author(&self, author: &str) -> Vec<&LawPackage> {
206        self.laws.iter().filter(|l| l.author == author).collect()
207    }
208
209    /// Get laws by kind (physical or fictional).
210    pub fn by_kind(&self, kind: LawKind) -> Vec<&LawPackage> {
211        self.laws.iter().filter(|l| l.kind == kind).collect()
212    }
213
214    /// Get a law by name.
215    pub fn get(&self, name: &str) -> Option<&LawPackage> {
216        self.laws.iter().find(|l| l.name == name)
217    }
218
219    /// Get only signed laws.
220    pub fn signed(&self) -> Vec<&LawPackage> {
221        self.laws.iter().filter(|l| l.is_signed()).collect()
222    }
223
224    /// Number of laws.
225    pub fn len(&self) -> usize {
226        self.laws.len()
227    }
228
229    /// Is the store empty?
230    pub fn is_empty(&self) -> bool {
231        self.laws.is_empty()
232    }
233}
234
235#[cfg(test)]
236mod tests {
237    use super::*;
238
239    fn make_instant() -> Instant {
240        Instant::unix(1_000_000_000, 0)
241    }
242
243    // ── LawKind tests ─────────────────────────────────────────────────
244
245    #[test]
246    fn t72_law_kind_round_trip() {
247        for k in &[LawKind::Physical, LawKind::Fictional] {
248            let s = k.as_str();
249            assert_eq!(LawKind::from_str(s), Some(*k));
250        }
251        assert_eq!(LawKind::from_str("unknown"), None);
252    }
253
254    #[test]
255    fn t72_default_is_physical() {
256        assert_eq!(LawKind::default(), LawKind::Physical);
257    }
258
259    // ── LawPackage tests ──────────────────────────────────────────────
260
261    #[test]
262    fn t72_law_package_basic() {
263        let law = LawPackage::new(
264            "crush",
265            "when sample(pressure_ambient, pose(self)) > self.material.yield",
266            "transform.yield(self)",
267            "did:alice",
268            "https://opensource.org/licenses/MIT",
269            LawKind::Physical,
270            make_instant(),
271        );
272        assert_eq!(law.name, "crush");
273        assert_eq!(law.author, "did:alice");
274        assert_eq!(law.kind, LawKind::Physical);
275        assert!(!law.is_signed());
276        assert!(law.version.is_none());
277    }
278
279    #[test]
280    fn t72_law_package_with_signature() {
281        let law = LawPackage::new(
282            "crush",
283            "condition",
284            "consequence",
285            "did:alice",
286            "MIT",
287            LawKind::Physical,
288            make_instant(),
289        )
290        .with_signature([0u8; 64]);
291        assert!(law.is_signed());
292    }
293
294    #[test]
295    fn t72_law_package_with_version() {
296        let law = LawPackage::new(
297            "crush",
298            "condition",
299            "consequence",
300            "did:alice",
301            "MIT",
302            LawKind::Physical,
303            make_instant(),
304        )
305        .with_version("1.0.0");
306        assert_eq!(law.version, Some("1.0.0".into()));
307    }
308
309    #[test]
310    fn t72_law_package_fictional() {
311        let law = LawPackage::new(
312            "respawn",
313            "when self.hp <= 0",
314            "transform.respawn(self)",
315            "did:game-dev",
316            "https://example.com/game-licence",
317            LawKind::Fictional,
318            make_instant(),
319        );
320        assert_eq!(law.kind, LawKind::Fictional);
321    }
322
323    #[test]
324    fn t72_canonical_bytes_deterministic() {
325        let law1 = LawPackage::new(
326            "crush",
327            "cond",
328            "cons",
329            "did:alice",
330            "MIT",
331            LawKind::Physical,
332            make_instant(),
333        );
334        let law2 = LawPackage::new(
335            "crush",
336            "cond",
337            "cons",
338            "did:alice",
339            "MIT",
340            LawKind::Physical,
341            make_instant(),
342        );
343        assert_eq!(law1.canonical_bytes(), law2.canonical_bytes());
344    }
345
346    #[test]
347    fn t72_canonical_bytes_differ_on_content() {
348        let law1 = LawPackage::new(
349            "crush",
350            "cond1",
351            "cons",
352            "did:alice",
353            "MIT",
354            LawKind::Physical,
355            make_instant(),
356        );
357        let law2 = LawPackage::new(
358            "crush",
359            "cond2",
360            "cons",
361            "did:alice",
362            "MIT",
363            LawKind::Physical,
364            make_instant(),
365        );
366        assert_ne!(law1.canonical_bytes(), law2.canonical_bytes());
367    }
368
369    #[test]
370    fn t72_canonical_bytes_differ_on_kind() {
371        let law1 = LawPackage::new(
372            "crush",
373            "cond",
374            "cons",
375            "did:alice",
376            "MIT",
377            LawKind::Physical,
378            make_instant(),
379        );
380        let law2 = LawPackage::new(
381            "crush",
382            "cond",
383            "cons",
384            "did:alice",
385            "MIT",
386            LawKind::Fictional,
387            make_instant(),
388        );
389        assert_ne!(law1.canonical_bytes(), law2.canonical_bytes());
390    }
391
392    #[test]
393    fn t72_to_value() {
394        let law = LawPackage::new(
395            "crush",
396            "cond",
397            "cons",
398            "did:alice",
399            "MIT",
400            LawKind::Physical,
401            make_instant(),
402        )
403        .with_version("1.0");
404        let v = law.to_value();
405        match v {
406            Value::Record(r) => {
407                assert_eq!(r.len(), 9);
408                assert!(r.contains_key("name"));
409                assert!(r.contains_key("condition"));
410                assert!(r.contains_key("consequence"));
411                assert!(r.contains_key("author"));
412                assert!(r.contains_key("licence"));
413                assert!(r.contains_key("kind"));
414                assert!(r.contains_key("asserted_at"));
415                assert!(r.contains_key("is_signed"));
416                assert!(r.contains_key("version"));
417            }
418            _ => panic!("expected Record"),
419        }
420    }
421
422    // ── LawStore tests ────────────────────────────────────────────────
423
424    #[test]
425    fn t72_law_store_register_and_query() {
426        let mut store = LawStore::new();
427        store.register(LawPackage::new(
428            "crush",
429            "cond1",
430            "cons1",
431            "did:alice",
432            "MIT",
433            LawKind::Physical,
434            make_instant(),
435        ));
436        store.register(LawPackage::new(
437            "melt",
438            "cond2",
439            "cons2",
440            "did:bob",
441            "Apache",
442            LawKind::Physical,
443            make_instant(),
444        ));
445        store.register(LawPackage::new(
446            "respawn",
447            "cond3",
448            "cons3",
449            "did:game-dev",
450            "GameLic",
451            LawKind::Fictional,
452            make_instant(),
453        ));
454        assert_eq!(store.len(), 3);
455        assert_eq!(store.by_author("did:alice").len(), 1);
456        assert_eq!(store.by_kind(LawKind::Physical).len(), 2);
457        assert_eq!(store.by_kind(LawKind::Fictional).len(), 1);
458        assert!(store.get("crush").is_some());
459        assert!(store.get("unknown").is_none());
460    }
461
462    #[test]
463    fn t72_law_store_signed_filter() {
464        let mut store = LawStore::new();
465        store.register(LawPackage::new(
466            "crush",
467            "cond",
468            "cons",
469            "did:alice",
470            "MIT",
471            LawKind::Physical,
472            make_instant(),
473        ));
474        store.register(
475            LawPackage::new(
476                "melt",
477                "cond",
478                "cons",
479                "did:bob",
480                "MIT",
481                LawKind::Physical,
482                make_instant(),
483            )
484            .with_signature([1u8; 64]),
485        );
486        assert_eq!(store.signed().len(), 1);
487    }
488
489    #[test]
490    fn t72_law_store_empty() {
491        let store = LawStore::new();
492        assert!(store.is_empty());
493        assert_eq!(store.len(), 0);
494    }
495}