clm-kernel 0.0.17

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
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
//! Sheaf gluing engine scaffold for Stage 4.
//!
//! Implements the bare-bones sheaf model from Sprint 139.4 Story 1:
//! - `Place` is an open-set identifier.
//! - `Marking` maps token colors to ordered lists of manifest hashes.
//! - `Section` pairs an open set with a local marking.
//! - `Sheaf::gluing_check` validates pairwise restriction agreement and either
//!   produces a global section or returns a `CohomologyError`.

use serde::{Deserialize, Serialize};
use std::collections::{BTreeSet, HashMap};

#[cfg(feature = "native")]
pub use crate::cpn::mcard_token::PlaceMCard;
#[cfg(feature = "native")]
pub use crate::cpn::token_namespace::MCardMarking;

#[cfg(not(feature = "native"))]
#[derive(Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
pub struct PlaceMCard {
    pub place_id: String,
    pub role: String,
    pub color_type: String,
}

#[cfg(not(feature = "native"))]
impl PlaceMCard {
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            place_id: id.into(),
            role: "Ordinary".into(),
            color_type: "unit".into(),
        }
    }
}

#[cfg(not(feature = "native"))]
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct MCardMarking {
    pub by_place: std::collections::BTreeMap<String, Vec<String>>,
}

#[cfg(not(feature = "native"))]
impl MCardMarking {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn restrict(&self, colors: &BTreeSet<String>) -> Self {
        let mut by_place = std::collections::BTreeMap::new();
        for (p, toks) in &self.by_place {
            if colors.contains(p) {
                by_place.insert(p.clone(), toks.clone());
            }
        }
        Self { by_place }
    }
}



/// Unified canonical Petri Net Marking alias for Sheaf sections (Sprint 551).
pub type Marking = MCardMarking;

#[derive(Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
pub struct Place {
    pub id: String,
}

impl Place {
    pub fn new(id: impl Into<String>) -> Self {
        Self { id: id.into() }
    }

    pub fn to_mcard(&self) -> PlaceMCard {
        PlaceMCard::new(&self.id)
    }

    pub fn from_mcard(mcard: &PlaceMCard) -> Self {
        Self { id: mcard.place_id.clone() }
    }
}

impl From<PlaceMCard> for Place {
    fn from(m: PlaceMCard) -> Self {
        Self { id: m.place_id }
    }
}

impl From<&PlaceMCard> for Place {
    fn from(m: &PlaceMCard) -> Self {
        Self { id: m.place_id.clone() }
    }
}

impl From<Place> for PlaceMCard {
    fn from(p: Place) -> Self {
        PlaceMCard::new(p.id)
    }
}

impl From<&Place> for PlaceMCard {
    fn from(p: &Place) -> Self {
        PlaceMCard::new(&p.id)
    }
}

#[derive(Debug, Clone, Default, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct OpenSet {
    pub places: BTreeSet<Place>,
}

impl OpenSet {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn from_places<I: IntoIterator<Item = Place>>(places: I) -> Self {
        Self {
            places: places.into_iter().collect(),
        }
    }

    pub fn intersection(&self, other: &OpenSet) -> OpenSet {
        OpenSet {
            places: self
                .places
                .intersection(&other.places)
                .cloned()
                .collect(),
        }
    }

    pub fn is_disjoint(&self, other: &OpenSet) -> bool {
        self.places.is_disjoint(&other.places)
    }

    pub fn is_subset(&self, other: &OpenSet) -> bool {
        self.places.is_subset(&other.places)
    }

    pub fn is_empty(&self) -> bool {
        self.places.is_empty()
    }

    pub fn colors(&self) -> BTreeSet<String> {
        // In this simple model, each place carries a single color equal to its id.
        self.places.iter().map(|p| p.id.clone()).collect()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Section {
    pub open_set: OpenSet,
    pub marking: Marking,
}

impl Section {
    pub fn new(open_set: OpenSet, marking: Marking) -> Self {
        Self { open_set, marking }
    }

    /// Restrict this section to a smaller open set.
    pub fn restrict(&self, subset: &OpenSet) -> Result<Section, CohomologyError> {
        if !subset.is_subset(&self.open_set) {
            return Err(CohomologyError::InvalidRestriction {
                subset: subset.clone(),
                superset: self.open_set.clone(),
            });
        }
        let colors = subset.colors();
        let marking = self.marking.restrict(&colors);
        Ok(Section {
            open_set: subset.clone(),
            marking,
        })
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Sheaf {
    pub sections: HashMap<OpenSet, Section>,
}

impl Default for Sheaf {
    fn default() -> Self {
        Self::new()
    }
}

impl Sheaf {
    pub fn new() -> Self {
        Self {
            sections: HashMap::new(),
        }
    }

    /// Restrict a section to a smaller open set.
    pub fn restriction(&self, section: &Section, subset: &OpenSet) -> Result<Section, CohomologyError> {
        section.restrict(subset)
    }

    /// Verify that a list of local sections agree on all pairwise intersections
    /// and, if so, return a global section over the union of the cover.
    ///
    /// Uses Merkle sub-root comparison for O(1) per-overlap verification.
    /// On failure, returns a `CohomologyError::GluingFailure` containing
    /// the mismatched markings for conflict report generation.
    pub fn gluing_check(
        &self,
        local_sections: &[Section],
        open_cover: &[OpenSet],
    ) -> Result<Section, CohomologyError> {
        if local_sections.len() != open_cover.len() {
            return Err(CohomologyError::InputMismatch);
        }
        if local_sections.is_empty() {
            return Ok(Section::new(OpenSet::new(), Marking::new()));
        }

        // Pre-compute Merkle trees for each section.
        let merkle_trees: Vec<MerkleNode> =
            local_sections.iter().map(section_to_merkle).collect();

        let n = local_sections.len();
        for i in 0..n {
            for j in (i + 1)..n {
                let intersection = open_cover[i].intersection(&open_cover[j]);
                if intersection.is_empty() {
                    continue;
                }
                // O(1) per-overlap: compare Merkle sub-roots.
                let root_i = merkle_sub_root(&merkle_trees[i], &intersection.places);
                let root_j = merkle_sub_root(&merkle_trees[j], &intersection.places);
                if root_i != root_j {
                    // Mismatch detected — fall back to full restriction
                    // to capture the expected/actual markings for the
                    // conflict report.
                    let left = self.restriction(&local_sections[i], &intersection)?;
                    let right = self.restriction(&local_sections[j], &intersection)?;
                    return Err(CohomologyError::GluingFailure {
                        place_i: local_sections[i].open_set.places.iter().next().cloned().unwrap_or(Place::new("?")),
                        place_j: local_sections[j].open_set.places.iter().next().cloned().unwrap_or(Place::new("?")),
                        intersection: intersection.clone(),
                        expected_marking: left.marking,
                        actual_marking: right.marking,
                        cohomology_class: "[delta_s]".to_string(),
                    });
                }
            }
        }

        let mut union = OpenSet::new();
        let mut marking = Marking::new();
        for (section, cover) in local_sections.iter().zip(open_cover.iter()) {
            union.places.extend(cover.places.iter().cloned());
            // Merge tokens; gluing_check guarantees consistency on overlaps.
            for (color, vals) in &section.marking.by_place {
                marking.by_place.insert(color.clone(), vals.clone());
            }
        }
        Ok(Section::new(union, marking))
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum CohomologyError {
    InputMismatch,
    InvalidRestriction { subset: OpenSet, superset: OpenSet },
    GluingFailure {
        place_i: Place,
        place_j: Place,
        intersection: OpenSet,
        expected_marking: Marking,
        actual_marking: Marking,
        cohomology_class: String,
    },
}

impl std::fmt::Display for CohomologyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CohomologyError::InputMismatch => write!(f, "open cover and local sections have different lengths"),
            CohomologyError::InvalidRestriction { subset, superset } => {
                write!(f, "cannot restrict {:?} to subset {:?}", superset, subset)
            }
            CohomologyError::GluingFailure { place_i, place_j, intersection, .. } => {
                write!(
                    f,
                    "COHOMOLOGICAL OBSTRUCTION: Sections disagree on intersection of {:?} and {:?}: {:?}",
                    place_i.id, place_j.id, intersection
                )
            }
        }
    }
}

impl std::error::Error for CohomologyError {}

// ─────────────────────────────────────────────────────────────────────
// Merkle-DAG Section Encoding (Story 139.4.2)
// ─────────────────────────────────────────────────────────────────────

/// A Merkle node for content-addressed section encoding.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MerkleNode {
    pub hash: [u8; 32],
    pub children: Vec<MerkleNode>,
    pub place_id: Option<String>,
    pub payload: Option<Vec<u8>>,
}

/// Compute the content hash of a payload, returning a 32-byte hash.
pub fn compute_merkle_root(payload: &[u8]) -> [u8; 32] {
    crate::hash::raw_hash_bytes_32(payload)
}

/// Compute the Merkle root of a set of child nodes by hashing their
/// concatenated child hashes.
pub fn compute_merkle_node(children: &[MerkleNode]) -> [u8; 32] {
    let mut combined = Vec::new();
    for child in children {
        combined.extend_from_slice(&child.hash);
    }
    crate::hash::raw_hash_bytes_32(&combined)
}

/// Encode a section as a Merkle tree — one leaf per place in the section.
/// Each leaf is the SHA-256 of the place's marking (serialized as
/// `color:hash1,hash2,...` sorted by color).
pub fn section_to_merkle(section: &Section) -> MerkleNode {
    let mut leaves: Vec<MerkleNode> = section
        .open_set
        .places
        .iter()
        .map(|place| {
            let tokens = section.marking.by_place.get(&place.id);
            let payload = match tokens {
                Some(vals) => format!("{}:{}", place.id, vals.join(",")),
                None => place.id.clone(),
            };
            let hash = compute_merkle_root(payload.as_bytes());
            MerkleNode {
                hash,
                children: vec![],
                place_id: Some(place.id.clone()),
                payload: Some(payload.into_bytes()),
            }
        })
        .collect();
    leaves.sort_by(|a, b| a.place_id.cmp(&b.place_id));
    let root_hash = compute_merkle_node(&leaves);
    MerkleNode {
        hash: root_hash,
        children: leaves,
        place_id: None,
        payload: None,
    }
}

/// Compute the Merkle root of the subset of leaves corresponding to the
/// given places. This enables O(1) per-overlap verification by comparing
/// only the sub-root hashes.
pub fn merkle_sub_root(node: &MerkleNode, places: &BTreeSet<Place>) -> [u8; 32] {
    let place_ids: BTreeSet<String> = places.iter().map(|p| p.id.clone()).collect();
    let matching: Vec<&MerkleNode> = node
        .children
        .iter()
        .filter(|c| {
            c.place_id
                .as_ref()
                .map(|id| place_ids.contains(id))
                .unwrap_or(false)
        })
        .collect();
    if matching.is_empty() {
        return [0u8; 32];
    }
    let mut combined = Vec::new();
    for child in &matching {
        combined.extend_from_slice(&child.hash);
    }
    crate::hash::raw_hash_bytes_32(&combined)
}

#[cfg(feature = "native")]
pub use crate::layer2::sheaf_persistence::{load_section_merkle, store_section_merkle};

// ─────────────────────────────────────────────────────────────────────
// Cohomology Conflict Reporter (Story 139.4.3)
// ─────────────────────────────────────────────────────────────────────

/// A structured conflict report produced when gluing fails. This is
/// content-addressed and stored as an MCard in `execution_log`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CohomologyConflictReport {
    pub conflicting_places: (Place, Place),
    pub intersection: OpenSet,
    pub expected_marking: Marking,
    pub actual_marking: Marking,
    pub cohomology_class: String,
    pub timestamp: String,
    pub agent_dids: Vec<String>,
}

impl CohomologyConflictReport {
    /// Serialize the conflict report as YAML.
    pub fn to_yaml(&self) -> String {
        serde_yaml::to_string(self).unwrap_or_else(|_| "cohomology_conflict: <error>".to_string())
    }

    /// Compute the content address of the report.
    pub fn content_hash(&self) -> String {
        crate::hash::raw_hash_string(&self.to_yaml())
    }

    /// Create a conflict report from a `CohomologyError::GluingFailure`.
    pub fn from_error(
        err: &CohomologyError,
        agent_dids: Vec<String>,
    ) -> Option<Self> {
        match err {
            CohomologyError::GluingFailure {
                place_i,
                place_j,
                intersection,
                expected_marking,
                actual_marking,
                cohomology_class,
            } => Some(CohomologyConflictReport {
                conflicting_places: (place_i.clone(), place_j.clone()),
                intersection: intersection.clone(),
                expected_marking: expected_marking.clone(),
                actual_marking: actual_marking.clone(),
                cohomology_class: cohomology_class.clone(),
                timestamp: chrono::Utc::now().to_rfc3339(),
                agent_dids,
            }),
            _ => None,
        }
    }
}

#[cfg(feature = "native")]
pub use crate::layer2::sheaf_persistence::store_conflict_report;

#[cfg(test)]
#[path = "sheaf_tests.rs"]
mod tests;