Skip to main content

vibe/
sheaf.rs

1//! Sheaves, stalks, simplex, and topological tears (T47–T50).
2//!
3//! These are the geometric structures for agent context isolation and
4//! consistency. They map topological concepts to the VibeScript runtime:
5//!
6//! - **Stalk (T47):** An isolated snapshot of agent context — a pointer,
7//!   not a copied transcript. Contains a PoetSnapshot reference, a
8//!   capability lease, and a pulse topic prefix.
9//! - **Sheaf condition (T48):** A Pure predicate checked at commit of
10//!   staged deltas. Failure is a diagnostic, not an exception unwind.
11//! - **Simplex (T49):** A named record of jointly-required cells/graph
12//!   shapes. Missing a member ⇒ load or commit reject.
13//! - **Topological tear (T50):** A diagnostic + evidential (μ, λ) on a
14//!   sealed receipt. Quarantine context is a host routing decision.
15//!
16//! Reference: `docs/vibescript-full-impl-PLAN.md` §8.10 T47–T50.
17
18use crate::span::Span;
19use crate::value::Value;
20use std::collections::BTreeMap;
21
22// ── T47: Stalk ──────────────────────────────────────────────────────────────
23
24/// A stalk — an isolated agent context (T47).
25///
26/// The stalk is a pointer to an isolated `PoetSnapshot`, not a copied
27/// transcript. It carries:
28/// - A snapshot ID (opaque handle to the host's snapshot store).
29/// - A capability lease ID (what capabilities this stalk is allowed).
30/// - A pulse topic prefix (what events this stalk subscribes to).
31///
32/// The stalk is the agent's "local patch" — the region of the graph
33/// it can see and act on. Outside the stalk, the agent is blind.
34#[derive(Debug, Clone)]
35pub struct Stalk {
36    /// Opaque handle to the host's snapshot store.
37    pub snapshot_id: u64,
38    /// Capability lease ID — what capabilities this stalk is allowed.
39    pub capability_lease_id: u64,
40    /// Pulse topic prefix — what events this stalk subscribes to.
41    pub topic_prefix: String,
42    /// The agent DID that owns this stalk.
43    pub agent_did: String,
44}
45
46impl Stalk {
47    /// Creates a new `Stalk`.
48    pub fn new(
49        snapshot_id: u64,
50        capability_lease_id: u64,
51        topic_prefix: &str,
52        agent_did: &str,
53    ) -> Self {
54        Self {
55            snapshot_id,
56            capability_lease_id,
57            topic_prefix: topic_prefix.to_string(),
58            agent_did: agent_did.to_string(),
59        }
60    }
61
62    /// Convert to a VibeScript Record value.
63    pub fn to_value(&self) -> Value {
64        let mut rec = BTreeMap::new();
65        rec.insert("snapshot_id".into(), Value::U64(self.snapshot_id));
66        rec.insert(
67            "capability_lease_id".into(),
68            Value::U64(self.capability_lease_id),
69        );
70        rec.insert(
71            "topic_prefix".into(),
72            Value::String(self.topic_prefix.clone()),
73        );
74        rec.insert("agent_did".into(), Value::String(self.agent_did.clone()));
75        Value::Record(rec)
76    }
77
78    /// Extract from a VibeScript Record value.
79    pub fn from_value(val: &Value) -> Option<Self> {
80        let rec = match val {
81            Value::Record(r) => r,
82            _ => return None,
83        };
84        let snapshot_id = match rec.get("snapshot_id")? {
85            Value::U64(n) => *n,
86            _ => return None,
87        };
88        let capability_lease_id = match rec.get("capability_lease_id")? {
89            Value::U64(n) => *n,
90            _ => return None,
91        };
92        let topic_prefix = match rec.get("topic_prefix")? {
93            Value::String(s) => s.clone(),
94            _ => return None,
95        };
96        let agent_did = match rec.get("agent_did")? {
97            Value::String(s) => s.clone(),
98            _ => return None,
99        };
100        Some(Self {
101            snapshot_id,
102            capability_lease_id,
103            topic_prefix,
104            agent_did,
105        })
106    }
107}
108
109// ── T48: Sheaf condition ────────────────────────────────────────────────────
110
111/// A sheaf condition — a Pure predicate checked at commit (T48).
112///
113/// The sheaf condition verifies that staged deltas are consistent
114/// before they are committed. If the condition fails, the result is
115/// a diagnostic (not an exception unwind). The host decides whether
116/// to retry, quarantine, or reject.
117#[derive(Debug, Clone)]
118pub struct SheafCondition {
119    /// Human-readable name of the condition.
120    pub name: String,
121    /// The predicate expression (as VibeScript source or a host-side callback).
122    /// In v0, this is a name the host resolves; VibeScript doesn't evaluate
123    /// the predicate itself — the host does.
124    pub predicate_name: String,
125    /// Whether this condition is required (true) or advisory (false).
126    pub required: bool,
127}
128
129impl SheafCondition {
130    /// Creates a new `SheafCondition`.
131    pub fn new(name: &str, predicate_name: &str, required: bool) -> Self {
132        Self {
133            name: name.to_string(),
134            predicate_name: predicate_name.to_string(),
135            required,
136        }
137    }
138
139    /// Converts to value.
140    pub fn to_value(&self) -> Value {
141        let mut rec = BTreeMap::new();
142        rec.insert("name".into(), Value::String(self.name.clone()));
143        rec.insert(
144            "predicate_name".into(),
145            Value::String(self.predicate_name.clone()),
146        );
147        rec.insert("required".into(), Value::Bool(self.required));
148        Value::Record(rec)
149    }
150}
151
152/// Result of checking a sheaf condition at commit.
153#[derive(Debug, Clone, PartialEq, Eq)]
154pub enum SheafResult {
155    /// Condition passed — deltas are consistent.
156    Passed,
157    /// Condition failed — deltas are inconsistent. The diagnostic
158    /// describes what went wrong. The host decides what to do.
159    Failed(String),
160    /// Condition was advisory and skipped.
161    Skipped,
162}
163
164// ── T49: Simplex ────────────────────────────────────────────────────────────
165
166/// A simplex — a named record of jointly-required cells/graph shapes (T49).
167///
168/// A simplex declares that a set of cells (or graph shapes) must all
169/// be present together. If any member is missing, the load or commit
170/// is rejected. This is the "jointly-required" constraint: you can't
171/// have a face without its edges, or an edge without its vertices.
172#[derive(Debug, Clone)]
173pub struct Simplex {
174    /// Human-readable name (e.g. "triangle", "tetrahedron").
175    pub name: String,
176    /// The IDs of the jointly-required members.
177    pub members: Vec<u64>,
178    /// The dimension of the simplex (0=vertex, 1=edge, 2=face, 3=cell, ...).
179    pub dimension: u8,
180}
181
182impl Simplex {
183    /// Creates a new `Simplex`.
184    pub fn new(name: &str, dimension: u8, members: Vec<u64>) -> Self {
185        Self {
186            name: name.to_string(),
187            members,
188            dimension,
189        }
190    }
191
192    /// Check that all members are present in the given set.
193    /// Returns the first missing member, or None if all present.
194    pub fn check_members(&self, available: &[u64]) -> Option<u64> {
195        for &m in &self.members {
196            if !available.contains(&m) {
197                return Some(m);
198            }
199        }
200        None
201    }
202
203    /// Converts to value.
204    pub fn to_value(&self) -> Value {
205        let mut rec = BTreeMap::new();
206        rec.insert("name".into(), Value::String(self.name.clone()));
207        rec.insert("dimension".into(), Value::I64(self.dimension as i64));
208        rec.insert(
209            "members".into(),
210            Value::List(self.members.iter().map(|&m| Value::U64(m)).collect()),
211        );
212        Value::Record(rec)
213    }
214}
215
216// ── T50: Topological tear ───────────────────────────────────────────────────
217
218/// A topological tear — a diagnostic + evidential (μ, λ) on a sealed receipt (T50).
219///
220/// When a stalk's context is torn (quarantined), the tear is recorded
221/// as a sealed receipt with:
222/// - The diagnostic (what went wrong).
223/// - The evidential μ (provenance weight) and λ (wavelength/penalty).
224/// - The stalk ID that was torn.
225///
226/// Quarantine context is a host routing decision — the tear receipt
227/// is the evidence the host uses to decide what to do.
228#[derive(Debug, Clone)]
229pub struct TopologicalTear {
230    /// The diagnostic message.
231    pub diagnostic: String,
232    /// Evidential μ (provenance weight) — how much provenance was at stake.
233    pub mu: f64,
234    /// Evidential λ (wavelength/penalty) — the severity of the tear.
235    pub lambda: f64,
236    /// The stalk ID that was torn.
237    pub stalk_id: u64,
238    /// The span where the tear was detected.
239    pub span: Span,
240}
241
242impl TopologicalTear {
243    /// Creates a new `TopologicalTear`.
244    pub fn new(diagnostic: &str, mu: f64, lambda: f64, stalk_id: u64, span: Span) -> Self {
245        Self {
246            diagnostic: diagnostic.to_string(),
247            mu,
248            lambda,
249            stalk_id,
250            span,
251        }
252    }
253
254    /// Convert to a sealed receipt Value.
255    pub fn to_receipt(&self) -> Value {
256        let mut rec = BTreeMap::new();
257        rec.insert("diagnostic".into(), Value::String(self.diagnostic.clone()));
258        rec.insert("mu".into(), Value::F64(self.mu));
259        rec.insert("lambda".into(), Value::F64(self.lambda));
260        rec.insert("stalk_id".into(), Value::U64(self.stalk_id));
261        rec.insert("span_start".into(), Value::U64(self.span.start as u64));
262        rec.insert("span_end".into(), Value::U64(self.span.end as u64));
263        rec.insert("sealed".into(), Value::Bool(true));
264        Value::Record(rec)
265    }
266}
267
268// ── Čech Cohomology Restriction & Gluing Verification ─────────────────────────
269
270/// A local section of a sheaf over open set / simplex U_i.
271#[derive(Debug, Clone)]
272pub struct LocalSection {
273    pub open_set_id: u64,
274    pub values: BTreeMap<String, Value>,
275}
276
277impl LocalSection {
278    /// Creates a new `LocalSection`.
279    pub fn new(open_set_id: u64, values: BTreeMap<String, Value>) -> Self {
280        Self {
281            open_set_id,
282            values,
283        }
284    }
285
286    /// Restrict the local section to an intersection / common key set.
287    pub fn restrict(&self, keys: &[&str]) -> BTreeMap<String, Value> {
288        let mut restricted = BTreeMap::new();
289        for &k in keys {
290            if let Some(v) = self.values.get(k) {
291                restricted.insert(k.to_string(), v.clone());
292            }
293        }
294        restricted
295    }
296}
297
298/// An open cover consisting of local sections.
299#[derive(Debug, Clone, Default)]
300pub struct CechCover {
301    pub sections: Vec<LocalSection>,
302}
303
304impl CechCover {
305    /// Creates a new `CechCover`.
306    pub fn new() -> Self {
307        Self::default()
308    }
309
310    /// Adds section.
311    pub fn add_section(&mut self, s: LocalSection) {
312        self.sections.push(s);
313    }
314
315    /// Verify 0-cocycle Čech gluing condition: for all pairs (i, j),
316    /// sections s_i and s_j must agree on all shared keys (overlap U_i ∩ U_j).
317    pub fn verify_gluing(&self) -> Result<(), String> {
318        for i in 0..self.sections.len() {
319            for j in (i + 1)..self.sections.len() {
320                let s_i = &self.sections[i];
321                let s_j = &self.sections[j];
322                for (k, v_i) in &s_i.values {
323                    if let Some(v_j) = s_j.values.get(k) {
324                        if v_i != v_j {
325                            return Err(format!(
326                                "Čech gluing mismatch on overlap (U_{}, U_{}) for key '{}': {:?} vs {:?}",
327                                s_i.open_set_id, s_j.open_set_id, k, v_i, v_j
328                            ));
329                        }
330                    }
331                }
332            }
333        }
334        Ok(())
335    }
336
337    /// Glue all local sections into a single global section if gluing passes.
338    pub fn glue_global_section(&self) -> Result<BTreeMap<String, Value>, String> {
339        self.verify_gluing()?;
340        let mut global = BTreeMap::new();
341        for s in &self.sections {
342            for (k, v) in &s.values {
343                global.insert(k.clone(), v.clone());
344            }
345        }
346        Ok(global)
347    }
348}
349
350#[cfg(test)]
351mod tests {
352    use super::*;
353
354    #[test]
355    fn t47_stalk_construction() {
356        let stalk = Stalk::new(42, 7, "agent/updates", "did:example:agent");
357        assert_eq!(stalk.snapshot_id, 42);
358        assert_eq!(stalk.capability_lease_id, 7);
359        assert_eq!(stalk.topic_prefix, "agent/updates");
360        assert_eq!(stalk.agent_did, "did:example:agent");
361    }
362
363    #[test]
364    fn t47_stalk_value_round_trip() {
365        let stalk = Stalk::new(100, 200, "pulse/topic", "did:example:a");
366        let val = stalk.to_value();
367        let restored = Stalk::from_value(&val).unwrap();
368        assert_eq!(restored.snapshot_id, 100);
369        assert_eq!(restored.capability_lease_id, 200);
370        assert_eq!(restored.topic_prefix, "pulse/topic");
371        assert_eq!(restored.agent_did, "did:example:a");
372    }
373
374    #[test]
375    fn t47_stalk_from_value_none_on_non_record() {
376        assert!(Stalk::from_value(&Value::Null).is_none());
377        assert!(Stalk::from_value(&Value::I64(42)).is_none());
378    }
379
380    #[test]
381    fn t48_sheaf_condition_construction() {
382        let cond = SheafCondition::new("glue_check", "pred.glue_consistent", true);
383        assert_eq!(cond.name, "glue_check");
384        assert_eq!(cond.predicate_name, "pred.glue_consistent");
385        assert!(cond.required);
386    }
387
388    #[test]
389    fn t48_sheaf_condition_value() {
390        let cond = SheafCondition::new("glue", "pred.glue", false);
391        let val = cond.to_value();
392        let rec = match &val {
393            Value::Record(r) => r,
394            _ => panic!("expected Record"),
395        };
396        assert_eq!(
397            match rec.get("name").unwrap() {
398                Value::String(s) => s.as_str(),
399                _ => panic!("expected String"),
400            },
401            "glue"
402        );
403        assert_eq!(
404            match rec.get("required").unwrap() {
405                Value::Bool(b) => *b,
406                _ => panic!("expected Bool"),
407            },
408            false
409        );
410    }
411
412    #[test]
413    fn t48_sheaf_result_variants() {
414        assert_eq!(SheafResult::Passed, SheafResult::Passed);
415        assert_ne!(SheafResult::Passed, SheafResult::Skipped);
416        assert_eq!(
417            SheafResult::Failed("inconsistent".into()),
418            SheafResult::Failed("inconsistent".into())
419        );
420    }
421
422    #[test]
423    fn t49_simplex_construction() {
424        let simplex = Simplex::new("triangle", 2, vec![1, 2, 3]);
425        assert_eq!(simplex.name, "triangle");
426        assert_eq!(simplex.dimension, 2);
427        assert_eq!(simplex.members, vec![1, 2, 3]);
428    }
429
430    #[test]
431    fn t49_simplex_check_members_all_present() {
432        let simplex = Simplex::new("edge", 1, vec![10, 20]);
433        assert!(simplex.check_members(&[10, 20, 30]).is_none());
434    }
435
436    #[test]
437    fn t49_simplex_check_members_missing() {
438        let simplex = Simplex::new("triangle", 2, vec![1, 2, 3]);
439        assert_eq!(simplex.check_members(&[1, 2]), Some(3));
440    }
441
442    #[test]
443    fn t49_simplex_check_members_empty_available() {
444        let simplex = Simplex::new("vertex", 0, vec![42]);
445        assert_eq!(simplex.check_members(&[]), Some(42));
446    }
447
448    #[test]
449    fn t49_simplex_value() {
450        let simplex = Simplex::new("tet", 3, vec![1, 2, 3, 4]);
451        let val = simplex.to_value();
452        let rec = match &val {
453            Value::Record(r) => r,
454            _ => panic!("expected Record"),
455        };
456        assert_eq!(
457            match rec.get("name").unwrap() {
458                Value::String(s) => s.as_str(),
459                _ => panic!("expected String"),
460            },
461            "tet"
462        );
463        assert_eq!(
464            match rec.get("dimension").unwrap() {
465                Value::I64(n) => *n,
466                _ => panic!("expected I64"),
467            },
468            3
469        );
470        let members = match rec.get("members").unwrap() {
471            Value::List(l) => l,
472            _ => panic!("expected List"),
473        };
474        assert_eq!(members.len(), 4);
475    }
476
477    #[test]
478    fn t50_topological_tear_construction() {
479        let tear = TopologicalTear::new("context inconsistency", 0.8, 0.3, 42, Span::point(100));
480        assert_eq!(tear.diagnostic, "context inconsistency");
481        assert_eq!(tear.mu, 0.8);
482        assert_eq!(tear.lambda, 0.3);
483        assert_eq!(tear.stalk_id, 42);
484    }
485
486    #[test]
487    fn t50_topological_tear_receipt() {
488        let tear = TopologicalTear::new("tear detected", 0.5, 0.9, 7, Span::new(10, 20));
489        let receipt = tear.to_receipt();
490        let rec = match &receipt {
491            Value::Record(r) => r,
492            _ => panic!("expected Record"),
493        };
494        assert_eq!(
495            match rec.get("diagnostic").unwrap() {
496                Value::String(s) => s.as_str(),
497                _ => panic!("expected String"),
498            },
499            "tear detected"
500        );
501        assert_eq!(rec.get("mu").unwrap().as_f64(), Some(0.5));
502        assert_eq!(rec.get("lambda").unwrap().as_f64(), Some(0.9));
503        assert_eq!(
504            match rec.get("stalk_id").unwrap() {
505                Value::U64(n) => *n,
506                _ => panic!("expected U64"),
507            },
508            7
509        );
510        assert_eq!(
511            match rec.get("sealed").unwrap() {
512                Value::Bool(b) => *b,
513                _ => panic!("expected Bool"),
514            },
515            true
516        );
517        assert_eq!(
518            match rec.get("span_start").unwrap() {
519                Value::U64(n) => *n,
520                _ => panic!("expected U64"),
521            },
522            10
523        );
524        assert_eq!(
525            match rec.get("span_end").unwrap() {
526                Value::U64(n) => *n,
527                _ => panic!("expected U64"),
528            },
529            20
530        );
531    }
532
533    #[test]
534    fn test_cech_gluing_consistent() {
535        let mut cover = CechCover::new();
536        let mut s1 = BTreeMap::new();
537        s1.insert("x".into(), Value::I64(10));
538        s1.insert("shared".into(), Value::String("agree".into()));
539        cover.add_section(LocalSection::new(1, s1));
540
541        let mut s2 = BTreeMap::new();
542        s2.insert("y".into(), Value::I64(20));
543        s2.insert("shared".into(), Value::String("agree".into()));
544        cover.add_section(LocalSection::new(2, s2));
545
546        assert!(cover.verify_gluing().is_ok());
547        let global = cover.glue_global_section().unwrap();
548        assert_eq!(global.len(), 3);
549        assert_eq!(global.get("shared"), Some(&Value::String("agree".into())));
550    }
551
552    #[test]
553    fn test_cech_gluing_inconsistent() {
554        let mut cover = CechCover::new();
555        let mut s1 = BTreeMap::new();
556        s1.insert("shared".into(), Value::String("value_a".into()));
557        cover.add_section(LocalSection::new(1, s1));
558
559        let mut s2 = BTreeMap::new();
560        s2.insert("shared".into(), Value::String("value_b".into()));
561        cover.add_section(LocalSection::new(2, s2));
562
563        let res = cover.verify_gluing();
564        assert!(res.is_err());
565        assert!(res.unwrap_err().contains("Čech gluing mismatch"));
566    }
567}