1use crate::span::Span;
19use crate::value::Value;
20use std::collections::BTreeMap;
21
22#[derive(Debug, Clone)]
35pub struct Stalk {
36 pub snapshot_id: u64,
38 pub capability_lease_id: u64,
40 pub topic_prefix: String,
42 pub agent_did: String,
44}
45
46impl Stalk {
47 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 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 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#[derive(Debug, Clone)]
118pub struct SheafCondition {
119 pub name: String,
121 pub predicate_name: String,
125 pub required: bool,
127}
128
129impl SheafCondition {
130 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 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#[derive(Debug, Clone, PartialEq, Eq)]
154pub enum SheafResult {
155 Passed,
157 Failed(String),
160 Skipped,
162}
163
164#[derive(Debug, Clone)]
173pub struct Simplex {
174 pub name: String,
176 pub members: Vec<u64>,
178 pub dimension: u8,
180}
181
182impl Simplex {
183 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 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 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#[derive(Debug, Clone)]
229pub struct TopologicalTear {
230 pub diagnostic: String,
232 pub mu: f64,
234 pub lambda: f64,
236 pub stalk_id: u64,
238 pub span: Span,
240}
241
242impl TopologicalTear {
243 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 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#[derive(Debug, Clone)]
272pub struct LocalSection {
273 pub open_set_id: u64,
274 pub values: BTreeMap<String, Value>,
275}
276
277impl LocalSection {
278 pub fn new(open_set_id: u64, values: BTreeMap<String, Value>) -> Self {
280 Self {
281 open_set_id,
282 values,
283 }
284 }
285
286 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#[derive(Debug, Clone, Default)]
300pub struct CechCover {
301 pub sections: Vec<LocalSection>,
302}
303
304impl CechCover {
305 pub fn new() -> Self {
307 Self::default()
308 }
309
310 pub fn add_section(&mut self, s: LocalSection) {
312 self.sections.push(s);
313 }
314
315 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 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}