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
//! Epiplexity VM integration scaffold for Stage 5.
//!
//! Implements the bounded-learning metrics `S_T`, `H_T`, `L = S_T - H_T`, and
//! `ΔL`. These are attached to VCard witnesses after PCard firings so that
//! Baldwin operator refactors can be evaluated by their Epiplexity delta.
//!
//! GitNexus cluster data is accepted as an input rather than queried inline;
//! this keeps the module WASM-safe and free of subprocess dependencies.

use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct EpiplexityMetrics {
    pub s_t: f64,
    pub h_t: f64,
    pub l: f64,
    pub delta_l: f64,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct GitNexusCluster {
    pub id: String,
    pub label: String,
    pub cohesion: f64,
    pub symbol_count: u32,
}

/// Compute structural signal `S_T` as the cohesion-weighted symbol count.
pub fn compute_s_t(clusters: &[GitNexusCluster]) -> f64 {
    clusters.iter().map(|c| c.cohesion * c.symbol_count as f64).sum()
}

/// Compute residual entropy `H_T` as the raw node + edge count of the affected
/// subgraph. In the scaffold `nodes` and `edges` are supplied directly.
pub fn compute_h_t(nodes: u32, edges: u32) -> f64 {
    nodes as f64 + edges as f64
}

/// Compute the Software Lagrangian `L = S_T - H_T`.
pub fn compute_l(s_t: f64, h_t: f64) -> f64 {
    s_t - h_t
}

/// Compute the Epiplexity delta between two metric snapshots.
pub fn compute_delta_l(pre: &EpiplexityMetrics, post: &EpiplexityMetrics) -> f64 {
    post.l - pre.l
}

/// Full Epiplexity snapshot for a transition.
pub fn compute_epiplexity_for_transition(
    affected_clusters: &[GitNexusCluster],
    nodes: u32,
    edges: u32,
    pre_metrics: Option<&EpiplexityMetrics>,
) -> EpiplexityMetrics {
    let s_t = compute_s_t(affected_clusters);
    let h_t = compute_h_t(nodes, edges);
    let l = compute_l(s_t, h_t);
    let delta_l = pre_metrics.map(|pre| compute_delta_l(pre, &EpiplexityMetrics { s_t, h_t, l, delta_l: 0.0 })).unwrap_or(0.0);
    EpiplexityMetrics {
        s_t,
        h_t,
        l,
        delta_l,
    }
}

/// Forecast the Epiplexity delta of a proposed refactor.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct EpiplexityForecast {
    pub predicted_s_t: f64,
    pub predicted_h_t: f64,
    pub predicted_l: f64,
    pub predicted_delta_l: f64,
    pub confidence: f64,
    pub affected_clusters: Vec<String>,
}

/// Meta-Epiplexity score (A²I): the Epiplexity of the Epiplexity extractor itself.
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct MetaEpiplexityScore {
    pub meta_s_t: f64,
    pub meta_h_t: f64,
    pub meta_l: f64,
    pub meta_delta_l: f64,
}

/// GitNexus index metadata loaded from `.gitnexus/meta.json`.
#[derive(Debug, Clone, Default, Deserialize)]
struct GitNexusMeta {
    #[serde(default)]
    nodes: u32,
    #[serde(default)]
    edges: u32,
    #[serde(default)]
    symbols: u32,
}

/// Read GitNexus index stats from `.gitnexus/meta.json` and compute first-order
/// Epiplexity metrics. Returns `EpiplexityMetrics` with `S_T` (cohesion-weighted
/// symbol count approximated as total symbols), `H_T` (nodes + edges), `L`, and
/// `ΔL = 0` (no prior snapshot).
pub fn measure_epiplexity(repo: &str) -> Result<EpiplexityMetrics, String> {
    let meta_path = std::path::Path::new(repo).join(".gitnexus").join("meta.json");
    let meta_str = std::fs::read_to_string(&meta_path)
        .map_err(|e| format!("Failed to read .gitnexus/meta.json at {}: {}", meta_path.display(), e))?;
    let meta: GitNexusMeta = serde_json::from_str(&meta_str)
        .map_err(|e| format!("Failed to parse .gitnexus/meta.json: {}", e))?;

    let s_t = meta.symbols as f64;
    let h_t = compute_h_t(meta.nodes, meta.edges);
    let l = compute_l(s_t, h_t);
    Ok(EpiplexityMetrics {
        s_t,
        h_t,
        l,
        delta_l: 0.0,
    })
}

/// Compute the A²I (Abstract² Interpretation) meta-Epiplexity score.
///
/// This measures the Epiplexity of the GitNexus extractor's own code structure.
/// `extractor_clusters` are the functional areas of the extractor code itself,
/// `extractor_nodes` and `extractor_edges` are the graph stats of the extractor.
pub fn compute_a2i_score(
    extractor_clusters: &[GitNexusCluster],
    extractor_nodes: u32,
    extractor_edges: u32,
) -> MetaEpiplexityScore {
    let meta_s_t = compute_s_t(extractor_clusters);
    let meta_h_t = compute_h_t(extractor_nodes, extractor_edges);
    let meta_l = compute_l(meta_s_t, meta_h_t);
    MetaEpiplexityScore {
        meta_s_t,
        meta_h_t,
        meta_l,
        meta_delta_l: 0.0,
    }
}

/// Seal the A²I meta-Epiplexity score as a VCard witness and store it as the
/// `meta/a2i_epiplexity` MCard in the execution_log database.
///
/// Returns the VCard hash on success.
#[cfg(feature = "native")]
pub fn seal_a2i_mcard(
    conn: &rusqlite::Connection,
    score: &MetaEpiplexityScore,
    clm_root: &str,
) -> Result<String, String> {
    let timestamp = crate::utils::now_iso8601();

    let vcard_yaml = format!(
        "vcard_token:\n  gate_type: \"dispatch\"\n  result: \"pass\"\n  meta_epiplexity_score:\n    meta_s_t: {}\n    meta_h_t: {}\n    meta_l: {}\n    meta_delta_l: {}\n  timestamp: \"{}\"",
        score.meta_s_t, score.meta_h_t, score.meta_l, score.meta_delta_l, timestamp
    );

    let vcard_hash = crate::hash::raw_hash_string(&vcard_yaml);
    // The stored coordinate must name the algorithm that produced `vcard_hash` (charter L2);
    // the bare ISO value stays inside the hashed YAML as content.
    let g_time = crate::fs_utils::compute_g_time();

    conn.execute(
        "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?, ?, ?)",
        rusqlite::params![vcard_hash, vcard_yaml, g_time],
    )
    .map_err(|e| format!("Failed to insert A²I MCard: {}", e))?;

    let handle = "meta/a2i_epiplexity";
    conn.execute(
        "INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) VALUES (?, ?, ?)",
        rusqlite::params![handle, vcard_hash, timestamp],
    )
    .map_err(|e| format!("Failed to bind handle {}: {}", handle, e))?;

    let kv_args = vec![
        format!("vcard_hash={}", vcard_hash),
        "gate_type=dispatch".to_string(),
        format!("handle={}", handle),
    ];
    let _ = crate::jsonl::jsonl_emit("a2i_mcard_sealed", kv_args, clm_root);

    Ok(vcard_hash)
}

/// Predict metrics for a Baldwin `Split` or generic refactor.
pub fn evaluate_refactor(
    affected_clusters: &[GitNexusCluster],
    added_nodes: u32,
    added_edges: u32,
    current_metrics: &EpiplexityMetrics,
) -> EpiplexityForecast {
    // Baldwin Split heuristic: cohesion improves by 10%, entropy grows by
    // added nodes/edges. Generic changes keep cohesion flat.
    let split_bonus: f64 = 1.10;
    let predicted_s_t: f64 = affected_clusters
        .iter()
        .map(|c| c.cohesion * split_bonus * c.symbol_count as f64)
        .sum();
    let predicted_h_t = current_metrics.h_t + compute_h_t(added_nodes, added_edges);
    let predicted_l = compute_l(predicted_s_t, predicted_h_t);
    let predicted_delta_l = predicted_l - current_metrics.l;
    EpiplexityForecast {
        predicted_s_t,
        predicted_h_t,
        predicted_l,
        predicted_delta_l,
        confidence: 0.5,
        affected_clusters: affected_clusters.iter().map(|c| c.id.clone()).collect(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_s_t_sum() {
        let clusters = vec![
            GitNexusCluster {
                id: "a".to_string(),
                label: "A".to_string(),
                cohesion: 0.8,
                symbol_count: 10,
            },
            GitNexusCluster {
                id: "b".to_string(),
                label: "B".to_string(),
                cohesion: 0.5,
                symbol_count: 20,
            },
        ];
        assert!((compute_s_t(&clusters) - 18.0).abs() < 1e-9);
    }

    #[test]
    fn test_h_t_and_l() {
        let s_t = compute_s_t(&[GitNexusCluster {
            id: "a".to_string(),
            label: "A".to_string(),
            cohesion: 1.0,
            symbol_count: 10,
        }]);
        let h_t = compute_h_t(5, 3);
        assert_eq!(h_t, 8.0);
        assert_eq!(compute_l(s_t, h_t), 2.0);
    }

    #[test]
    fn test_delta_l_positive_for_split() {
        let pre = EpiplexityMetrics {
            s_t: 10.0,
            h_t: 8.0,
            l: 2.0,
            delta_l: 0.0,
        };
        let clusters = vec![GitNexusCluster {
            id: "a".to_string(),
            label: "A".to_string(),
            cohesion: 1.0,
            symbol_count: 10,
        }];
        let forecast = evaluate_refactor(&clusters, 0, 0, &pre);
        assert!(forecast.predicted_delta_l > 0.0);
    }

    #[test]
    fn test_delta_l_negative_for_entropy_increase() {
        let pre = EpiplexityMetrics {
            s_t: 10.0,
            h_t: 8.0,
            l: 2.0,
            delta_l: 0.0,
        };
        let clusters = vec![GitNexusCluster {
            id: "a".to_string(),
            label: "A".to_string(),
            cohesion: 1.0,
            symbol_count: 10,
        }];
        // Add many nodes/edges without cohesion gain.
        let forecast = evaluate_refactor(&clusters, 100, 50, &pre);
        assert!(forecast.predicted_delta_l < 0.0);
    }

    #[test]
    fn test_compute_transition_metrics() {
        let clusters = vec![GitNexusCluster {
            id: "a".to_string(),
            label: "A".to_string(),
            cohesion: 1.0,
            symbol_count: 10,
        }];
        let pre = EpiplexityMetrics {
            s_t: 8.0,
            h_t: 5.0,
            l: 3.0,
            delta_l: 0.0,
        };
        let post = compute_epiplexity_for_transition(&clusters, 2, 1, Some(&pre));
        assert_eq!(post.s_t, 10.0);
        assert_eq!(post.h_t, 3.0);
        assert_eq!(post.l, 7.0);
        assert_eq!(post.delta_l, 4.0);
    }

    #[test]
    fn test_measure_epiplexity_with_meta_json() {
        let tmp = tempfile::tempdir().expect("create temp dir");
        let gn_dir = tmp.path().join(".gitnexus");
        std::fs::create_dir_all(&gn_dir).expect("create .gitnexus dir");
        let meta = serde_json::json!({
            "nodes": 100,
            "edges": 200,
            "symbols": 50
        });
        std::fs::write(gn_dir.join("meta.json"), meta.to_string()).expect("write meta.json");
        let result = measure_epiplexity(tmp.path().to_str().unwrap()).expect("measure_epiplexity should succeed");
        assert_eq!(result.s_t, 50.0);
        assert_eq!(result.h_t, 300.0);
        assert_eq!(result.l, -250.0);
        assert_eq!(result.delta_l, 0.0);
    }

    #[test]
    fn test_measure_epiplexity_no_index() {
        let tmp = tempfile::tempdir().expect("create temp dir");
        let result = measure_epiplexity(tmp.path().to_str().unwrap());
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Failed to read"));
    }

    #[test]
    fn test_compute_a2i_score_nonzero() {
        let extractor_clusters = vec![
            GitNexusCluster {
                id: "extractor_a".to_string(),
                label: "GraphBuilder".to_string(),
                cohesion: 0.8,
                symbol_count: 30,
            },
            GitNexusCluster {
                id: "extractor_b".to_string(),
                label: "Clusterer".to_string(),
                cohesion: 0.6,
                symbol_count: 20,
            },
        ];
        let score = compute_a2i_score(&extractor_clusters, 40, 60);
        assert!(score.meta_s_t > 0.0);
        assert_eq!(score.meta_s_t, 0.8 * 30.0 + 0.6 * 20.0);
        assert_eq!(score.meta_h_t, 100.0);
        assert_eq!(score.meta_l, score.meta_s_t - score.meta_h_t);
    }

    #[test]
    fn test_compute_a2i_score_empty() {
        let score = compute_a2i_score(&[], 0, 0);
        assert_eq!(score.meta_s_t, 0.0);
        assert_eq!(score.meta_h_t, 0.0);
        assert_eq!(score.meta_l, 0.0);
    }

    #[cfg(feature = "native")]
    #[test]
    fn test_a2i_mcard_sealed_and_queryable() {
        let conn = rusqlite::Connection::open_in_memory().unwrap();
        conn.execute(
            "CREATE TABLE card (hash TEXT PRIMARY KEY, content TEXT, g_time TEXT)",
            [],
        )
        .unwrap();
        conn.execute(
            "CREATE TABLE handle_registry (handle TEXT PRIMARY KEY, current_hash TEXT, updated_at TEXT)",
            [],
        )
        .unwrap();

        let score = MetaEpiplexityScore {
            meta_s_t: 36.0,
            meta_h_t: 100.0,
            meta_l: -64.0,
            meta_delta_l: 0.0,
        };

        let vcard_hash = seal_a2i_mcard(&conn, &score, "/tmp/clm_root").expect("seal_a2i_mcard should succeed");

        // Verify MCard content contains meta-epiplexity fields
        let content: String = conn
            .query_row("SELECT content FROM card WHERE hash = ?", rusqlite::params![vcard_hash], |row| row.get(0))
            .unwrap();
        assert!(content.contains("meta_epiplexity_score:"));
        assert!(content.contains("meta_s_t: 36"));
        assert!(content.contains("meta_h_t: 100"));
        assert!(content.contains("meta_l: -64"));

        // Verify handle is bound
        let handle_hash: String = conn
            .query_row(
                "SELECT current_hash FROM handle_registry WHERE handle = 'meta/a2i_epiplexity'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(handle_hash, vcard_hash);
    }
}