clm-kernel 0.0.2

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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
use super::types::{PetriNetYaml, RootTopologyYaml, hash_string, pcard_hash_placeholder};
use super::invariants::{build_incidence_matrix, compute_invariants, verify_t_invariant_idempotency, check_net_assertions};
use super::zta::{check_consensus, check_transition_acl, authorize_kenotic_sponsor};
use super::token_ops::{write_marking_dir, serialize_pcard, emit_state_token, emit_state_failed, build_marking_json};
use super::binding::execute_pcard_binding;
use crate::epiplexity::EpiplexityMetrics;
use std::collections::HashMap;
use std::env;
use std::fs;
use std::path::Path;

/// Parse and deserialize the Petri net topology YAML file.
fn parse_topology(topo_file: &str) -> Result<(PetriNetYaml, String), String> {
    let topo_content = if Path::new(topo_file).exists() {
        fs::read_to_string(topo_file)
            .map_err(|e| format!("Failed to read topology file: {}", e))?
    } else {
        return Err(format!("Topology file not found: {}", topo_file));
    };

    let root_topo: RootTopologyYaml = serde_yaml::from_str(&topo_content)
        .map_err(|e| format!("Failed to parse topology YAML: {}", e))?;
    Ok((root_topo.petri_net, topo_content))
}

pub fn petri_run_net(topo_file: &str, clm_root: &str) -> Result<String, String> {
    let (net, topo_content) = parse_topology(topo_file)?;

    let is_kenotic = env::var("CLM_PETRI_KENOTIC").unwrap_or_default() == "true";
    let zero_fs = crate::utils::is_zero_fs();
    let run_id = env::var("CLM_RUN_ID").unwrap_or_else(|_| {
        let ts = chrono::Utc::now().timestamp();
        let generated = format!("pn_{}_{}_{}", net.name, ts, std::process::id());
        crate::utils::set_env_var("CLM_RUN_ID", &generated);
        generated
    });

    if env::var("CLM_EVENT_LOG_PATH").is_err() {
        let scratch_dir = if zero_fs {
            Path::new(&env::var("TMPDIR").unwrap_or_else(|_| "/tmp".to_string()))
                .join(format!(".{}_scratch", run_id))
        } else {
            Path::new(clm_root)
                .join("data")
                .join("execution_logs")
                .join(format!(".{}_scratch", run_id))
        };
        let log_path = scratch_dir.join("token_events.jsonl").to_string_lossy().to_string();
        crate::utils::set_env_var("CLM_EVENT_LOG_PATH", &log_path);
    }

    if env::var("CLM_PETRI_MARKING_DIR").is_err() {
        let scratch_dir = if zero_fs {
            Path::new(&env::var("TMPDIR").unwrap_or_else(|_| "/tmp".to_string()))
                .join(format!(".{}_scratch", run_id))
        } else {
            Path::new(clm_root)
                .join("data")
                .join("execution_logs")
                .join(format!(".{}_scratch", run_id))
        };
        let marking_dir = scratch_dir.join("marking").to_string_lossy().to_string();
        crate::utils::set_env_var("CLM_PETRI_MARKING_DIR", &marking_dir);
    }

    let mut place_markings = HashMap::new();
    let mut place_colors = HashMap::new();
    let mut place_ids = Vec::new();
    for p in &net.places {
        place_markings.insert(p.id.clone(), p.initial_tokens);
        if let Some(col) = &p.initial_color
            && !col.is_empty() && col != "null" {
                place_colors.insert(p.id.clone(), col.clone());
            }
        place_ids.push(p.id.clone());
    }

    // ── Build incidence matrix ──────────────────────────────────────────
    let matrix = build_incidence_matrix(&net);
    let place_count = matrix.place_count;
    let trans_count = matrix.trans_count;

    // ── Compute Noetherian invariants ───────────────────────────────────
    let inv = compute_invariants(&net, &matrix, &place_ids, &place_markings);
    let active_p_invariants = inv.p_invariants;
    let active_p_constants = inv.p_constants;
    let active_t_invariants = inv.t_invariants;

    let mut out_buf = String::new();

    out_buf.push_str(&format!(
        "  🔍 Noetherian P-Invariants active: {}\n",
        active_p_invariants.len()
    ));
    for (pi_idx, weights) in active_p_invariants.iter().enumerate() {
        let weights_str = weights
            .iter()
            .map(|w| w.to_string())
            .collect::<Vec<_>>()
            .join(" ");
        out_buf.push_str(&format!(
            "    P-Inv #{}: [{}] (Expected Constant: {})\n",
            pi_idx, weights_str, active_p_constants[pi_idx]
        ));
    }

    out_buf.push_str(&format!(
        "  🔍 Noetherian T-Invariants active: {}\n",
        active_t_invariants.len()
    ));
    for (ti_idx, firings) in active_t_invariants.iter().enumerate() {
        let firings_str = firings
            .iter()
            .map(|f| f.to_string())
            .collect::<Vec<_>>()
            .join(" ");
        out_buf.push_str(&format!("    T-Inv #{}: [{}]\n", ti_idx, firings_str));
    }

    let marking_dir = if zero_fs {
        String::new()
    } else {
        env::var("CLM_PETRI_MARKING_DIR").unwrap_or_else(|_| {
            let scratch_dir = Path::new(clm_root)
                .join("data")
                .join("execution_logs")
                .join(&run_id);
            scratch_dir.join("marking").to_string_lossy().to_string()
        })
    };

    if !zero_fs && !marking_dir.is_empty() {
        let _ = fs::create_dir_all(&marking_dir);
    }
    for p in &net.places {
        let tok = place_markings.get(&p.id).cloned().unwrap_or(0);
        let col = place_colors.get(&p.id).map(|s| s.as_str());
        write_marking_dir(&marking_dir, &p.id, tok, col);
    }

    let db_conn = crate::db::get_connection("execution_log", clm_root)
        .map_err(|e| format!("Failed to connect to execution_log DB: {}", e))?;

    let sync_sqlite = |place_markings: &HashMap<String, i64>,
                       place_colors: &HashMap<String, String>|
     -> Result<(), String> {
        let mut markings_map = serde_json::Map::new();
        let mut colors_map = serde_json::Map::new();
        for p in &net.places {
            let tok = place_markings.get(&p.id).cloned().unwrap_or(0);
            markings_map.insert(p.id.clone(), serde_json::Value::Number(tok.into()));
            if let Some(col) = place_colors.get(&p.id)
                && !col.is_empty() {
                    colors_map.insert(p.id.clone(), serde_json::Value::String(col.clone()));
                }
        }
        let markings_json = serde_json::json!({
            "run_id": run_id,
            "markings": markings_map,
            "colors": colors_map
        })
        .to_string();

        let handle_name = format!("run:{}:markings", run_id);
        let markings_hash = hash_string(&markings_json);
        crate::db::handle_register_batch(
            "execution_log",
            clm_root,
            &handle_name,
            &markings_hash,
            &markings_json,
        )
        .map_err(|e| e.to_string())?;

        Ok(())
    };

    sync_sqlite(&place_markings, &place_colors)?;

    let mut current_marking_hash = String::new();
    let sponsor_did = env::var("ACTIVE_AGENT_DID")
        .or_else(|_| env::var("CLM_AGENT_DID"))
        .unwrap_or_else(|_| "did:clm:bootstrap".to_string());

    if is_kenotic {
        let topo_hash = hash_string(&topo_content);
        crate::db::handle_register_batch(
            "execution_log",
            clm_root,
            &format!("run:{}:topology", run_id),
            &topo_hash,
            &topo_content,
        )
        .map_err(|e| e.to_string())?;

        authorize_kenotic_sponsor(&sponsor_did, &net.authorized_sponsors)?;

        let sponsor_hash = hash_string(&sponsor_did);
        crate::db::handle_register_batch(
            "execution_log",
            clm_root,
            &format!("run:{}:sponsor", run_id),
            &sponsor_hash,
            &sponsor_did,
        )
        .map_err(|e| e.to_string())?;

        let init_marking_json = build_marking_json(
            &topo_hash,
            &net.places,
            &place_markings,
            &place_colors,
            &sponsor_did,
            &sponsor_did,
            "",
            None,
        );
        let init_marking_str = init_marking_json.to_string();
        let init_marking_hash = hash_string(&init_marking_str);

        crate::db::handle_register_batch(
            "execution_log",
            clm_root,
            &format!("run:{}:marking", run_id),
            &init_marking_hash,
            &init_marking_str,
        )
        .map_err(|e| e.to_string())?;

        let sponsor_class = if sponsor_did.starts_with("did:key:") {
            "EOA"
        } else {
            "CA"
        };
        out_buf.push_str(&format!(
            "[PETRI] ✅ [KENOTIC] Sponsor: {} ({})\n",
            sponsor_did, sponsor_class
        ));
        eprintln!(
            "[PETRI] ✅ [KENOTIC] Sponsor: {} ({})",
            sponsor_did, sponsor_class
        );

        current_marking_hash = init_marking_hash;
    }

    let mut fire_count = 0;
    let mut deadlocked = false;
    let mut cumulative_fires = vec![0; trans_count];
    let mut previous_metrics: Option<EpiplexityMetrics> = None;

    let is_visual = env::var("CLM_PETRI_VISUAL").unwrap_or_default() == "1";
    let is_repl_trace = env::var("CLM_REPL_TRACE").unwrap_or_default() == "1";

    loop {
        if env::var("CLM_PETRI_HALT").unwrap_or_default() == "true" {
            break;
        }

        if net.halt_after >= 0 && fire_count >= net.halt_after {
            break;
        }

        let mut found_enabled = false;

        for (ti, t) in net.transitions.iter().enumerate() {
            let mut enabled = true;
            for inp in &t.inputs {
                let cur = place_markings.get(inp).cloned().unwrap_or(0);
                if cur < 1 {
                    enabled = false;
                    break;
                }
            }

            if !enabled {
                continue;
            }

            if is_kenotic {
                let consensus_passed =
                    check_consensus(&db_conn, &t.id, &t.inputs, &place_colors, clm_root)?;
                if !consensus_passed {
                    continue;
                }
            }

            found_enabled = true;

            let per_trans_agent_did = t.agent_did.clone().unwrap_or_else(|| {
                env::var("ACTIVE_AGENT_DID")
                    .or_else(|_| env::var("CLM_AGENT_DID"))
                    .unwrap_or_else(|_| "did:clm:bootstrap".to_string())
            });

            if is_kenotic
                && !check_transition_acl(
                    &t.id,
                    &per_trans_agent_did,
                    t.required_agent_class.as_deref(),
                    net.required_agent_class.as_deref(),
                )
            {
                return Err(format!("ACL check failed for transition {}", t.id));
            }

            // Threshold signature gate: if the transition declares a
            // required_threshold, verify that M-of-N guardian signatures
            // are present before allowing the transition to fire.
            let mut threshold_sig_hex: Option<String> = None;
            let mut threshold_guardian_dids: Option<Vec<String>> = None;
            if let Some(ref tc) = t.required_threshold {
                let config = crate::tss::ThresholdConfig {
                    m: tc.m,
                    n: tc.n,
                    guardian_dids: tc.guardian_dids.clone(),
                };
                config.validate().map_err(|e| {
                    format!("[NOETHER_SIG_ERR] Invalid threshold config for {}: {}", t.id, e)
                })?;

                // In the current single-node implementation we auto-collect
                // signatures from the local EphemeralCA. A production
                // implementation would network-request signatures from
                // remote guardian nodes via the challenge-response handshake.
                let (vk, shares) = crate::tss::generate_threshold_keypair(tc.m, tc.n)
                    .map_err(|e| format!("[NOETHER_SIG_ERR] Key generation failed: {}", e))?;
                let message = format!("threshold:{}:{}", t.id, pcard_hash_placeholder(&t.id));
                let sig = crate::tss::threshold_sign(&shares[..tc.m as usize], message.as_bytes())
                    .map_err(|e| format!("[NOETHER_SIG_ERR] Threshold signing failed: {}", e))?;
                if !crate::tss::threshold_verify(&vk, &sig, message.as_bytes()) {
                    return Err(format!(
                        "[NOETHER_SIG_ERR] Threshold signature verification failed for transition {}",
                        t.id
                    ));
                }
                threshold_sig_hex = Some(hex::encode(sig.to_bytes()));
                threshold_guardian_dids = Some(config.guardian_dids);
            }

            let mut input_color = t
                .content
                .clone()
                .unwrap_or_else(|| format!("output_{}", t.id));
            if let Some(first_inp) = t.inputs.first()
                && let Some(col) = place_colors.get(first_inp)
                    && !col.is_empty() {
                        input_color = col.clone();
                    }

            let pre_markings = place_markings.clone();

            let mut input_token_hashes = Vec::new();
            for inp in &t.inputs {
                if let Some(col) = place_colors.get(inp)
                    && !col.is_empty() && col != "null" {
                        input_token_hashes.push(col.clone());
                    }
            }

            for inp in &t.inputs {
                if let Some(cur) = place_markings.get_mut(inp) {
                    *cur -= 1;
                }
            }
            sync_sqlite(&place_markings, &place_colors)?;

            let pcard_hash = serialize_pcard(
                &db_conn,
                &format!("{}_{}", run_id, t.id),
                "shell",
                &crate::hash::prefixed(&t.id),
                &[],
                &chrono::Local::now()
                    .format("%Y-%m-%dT%H:%M:%S%z")
                    .to_string(),
                clm_root,
            )?;

            let (exec_exit_code, _exec_output, dp_hash, final_content, metrics) =
                execute_pcard_binding(
                    &db_conn,
                    t,
                    clm_root,
                    &per_trans_agent_did,
                    &sponsor_did,
                    &pcard_hash,
                    &input_color,
                    previous_metrics.as_ref(),
                    threshold_sig_hex.as_deref(),
                    threshold_guardian_dids.as_deref(),
                )?;
            previous_metrics = Some(metrics);

            if exec_exit_code == 0 {
                let _state_hash =
                    emit_state_token(&db_conn, &pcard_hash, &dp_hash, &final_content, clm_root)?;

                // Post-transition sheaf gluing check: verify that
                // concurrent writes to overlapping output places are
                // cohomologically consistent. If the transition's output
                // places overlap with places that already have markings
                // from a prior concurrent transition, detect conflicts.
                if t.outputs.len() > 1 {
                    let output_open_set = crate::sheaf::OpenSet::from_places(
                        t.outputs.iter().map(|id| crate::sheaf::Place::new(id.clone())),
                    );
                    let mut output_marking = crate::sheaf::Marking::new();
                    for outp in &t.outputs {
                        if let Some(col) = place_colors.get(outp)
                            && !col.is_empty() {
                                output_marking = output_marking.with_token(outp, col);
                            }
                    }
                    let new_section = crate::sheaf::Section::new(
                        output_open_set.clone(),
                        output_marking.with_token(&t.outputs[0], &final_content),
                    );

                    // Build a section from the current place markings for
                    // the same output places (the "prior" state).
                    let mut prior_marking = crate::sheaf::Marking::new();
                    for outp in &t.outputs {
                        if let Some(col) = place_colors.get(outp)
                            && !col.is_empty() && col != &final_content {
                                prior_marking = prior_marking.with_token(outp, col);
                            }
                    }
                    if !prior_marking.tokens.is_empty() {
                        let prior_section = crate::sheaf::Section::new(
                            output_open_set.clone(),
                            prior_marking,
                        );
                        let sheaf = crate::sheaf::Sheaf::new();
                        let cover = vec![output_open_set.clone(), output_open_set.clone()];
                        if let Err(ref e) = sheaf.gluing_check(
                            &[prior_section.clone(), new_section.clone()],
                            &cover,
                        ) {
                            let report = crate::sheaf::CohomologyConflictReport::from_error(
                                e,
                                vec![per_trans_agent_did.clone()],
                            );
                            if let Some(ref r) = report {
                                let _ = crate::sheaf::store_conflict_report(r, &db_conn);
                                eprintln!("[VM] COHOMOLOGICAL_OBSTRUCTION: {}", r.to_yaml());
                            }
                            return Err(format!(
                                "COHOMOLOGICAL_OBSTRUCTION: transition {} produced inconsistent state on overlapping places",
                                t.id
                            ));
                        }
                    }
                }

                if final_content.contains("vcard_witness:") {
                    out_buf.push_str(&final_content);
                    if !final_content.ends_with('\n') {
                        out_buf.push('\n');
                    }

                    // Persist the witness to the content_memory pillar. The
                    // validate_postcondition binding emits `vcard_witness: "<hash>"`,
                    // but its own DB write routes through a shell->daemon round-trip
                    // that does not reliably persist under the native VM. db_conn
                    // here targets execution_log, whereas witness consumers (witness
                    // verification, dispatcher witness_yaml resolution) read
                    // content_memory — so commit there under the emitted hash.
                    for line in final_content.lines() {
                        let trimmed = line.trim();
                        if let Some(rest) = trimmed.strip_prefix("vcard_witness:") {
                            let witness_hash = rest.trim().trim_matches('"').to_string();
                            if !witness_hash.is_empty()
                                && let Ok(cm_conn) =
                                    crate::db::get_connection("content_memory", clm_root)
                                {
                                    let ts = chrono::Local::now()
                                        .format("%Y-%m-%dT%H:%M:%S%z")
                                        .to_string();
                                    match cm_conn.execute(
                                        "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?, ?, ?)",
                                        rusqlite::params![witness_hash, final_content, ts],
                                    ) {
                                        Ok(updated) => eprintln!("[VM] ✅ Witness persisted: {} (rows: {})", witness_hash, updated),
                                        Err(e) => eprintln!("[VM] ❌ Witness persistence failed: {} - Error: {}", witness_hash, e),
                                    }
                                }
                            break;
                        }
                    }
                }

                for outp in &t.outputs {
                    if let Some(cur) = place_markings.get_mut(outp) {
                        *cur += 1;
                    }
                    place_colors.insert(outp.clone(), final_content.clone());
                }
                sync_sqlite(&place_markings, &place_colors)?;

                for outp in &t.outputs {
                    let tok = place_markings.get(outp).cloned().unwrap_or(0);
                    write_marking_dir(&marking_dir, outp, tok, Some(&final_content));
                }

                if is_kenotic {
                    let topo_hash = hash_string(&topo_content);
                    let post_marking_json = build_marking_json(
                        &topo_hash,
                        &net.places,
                        &place_markings,
                        &place_colors,
                        &sponsor_did,
                        &per_trans_agent_did,
                        &current_marking_hash,
                        Some(&t.id),
                    );
                    let post_marking_str = post_marking_json.to_string();
                    let post_marking_hash = hash_string(&post_marking_str);

                    crate::db::handle_register_batch(
                        "execution_log",
                        clm_root,
                        &format!("run:{}:marking", run_id),
                        &post_marking_hash,
                        &post_marking_str,
                    )
                    .map_err(|e| e.to_string())?;

                    current_marking_hash = post_marking_hash.clone();
                    crate::utils::set_env_var("CLM_KENOTIC_CURRENT_MARKING_HASH", &post_marking_hash);

                    let mut vcards = Vec::new();
                    let mut sigs = Vec::new();
                    for h in &input_token_hashes {
                        let mut token_yaml = String::new();
                        if let Ok(Some(content)) = crate::db::resolve_handle_content(
                            "content_memory",
                            clm_root,
                            h,
                        ) {
                            token_yaml = content;
                        } else if let Ok(Some(content)) = crate::db::resolve_handle_content(
                            "execution_log",
                            clm_root,
                            h,
                        ) {
                            token_yaml = content;
                        } else {
                            let card_content: Option<String> = db_conn
                                .query_row(
                                    "SELECT content FROM card WHERE hash = ?",
                                    rusqlite::params![h],
                                    |row| row.get(0),
                                )
                                .ok();
                            if let Some(c) = card_content {
                                token_yaml = c;
                            }
                        }

                        if !token_yaml.is_empty()
                            && let Ok(v) =
                                serde_yaml::from_str::<serde_json::Value>(&token_yaml)
                                && let Some(vcard) = v.get("vcard_token") {
                                    let agent = vcard
                                        .get("agent_did")
                                        .and_then(|d| d.as_str())
                                        .or_else(|| {
                                            vcard.get("signer_did").and_then(|d| d.as_str())
                                        })
                                        .unwrap_or("");
                                    let sig = vcard
                                        .get("signature")
                                        .and_then(|s| s.as_str())
                                        .unwrap_or(h);
                                    vcards.push(serde_json::json!({
                                        "agent": agent,
                                        "vcard": h
                                    }));
                                    sigs.push(sig.to_string());
                                }
                    }

                    let multi_sig = if sigs.is_empty() {
                        "none".to_string()
                    } else {
                        format!("multi:{}", sigs.join(":"))
                    };

                    let cert_json = serde_json::json!({
                        "@type": "TransitionCertificate",
                        "run_id": run_id,
                        "transition": t.id,
                        "pcard_hash": pcard_hash,
                        "vcard_hash": dp_hash,
                        "exit_code": exec_exit_code,
                        "marking_hash": current_marking_hash,
                        "agent_did": per_trans_agent_did,
                        "session_did": env::var("CLM_SESSION_DELEGATION").unwrap_or_default(),
                        "sponsor_did": env::var("CLM_KENOTIC_SPONSOR_DID").unwrap_or_default(),
                        "execution_locale_hash": env::var("CLM_EXECUTION_LOCALE_HASH").unwrap_or_default(),
                        "transport_ref": env::var("CLM_TRANSPORT_REF").unwrap_or_else(|_| "local".to_string()),
                        "timestamp": crate::utils::now_iso8601(),
                        "vcards": vcards,
                        "multi_signature": multi_sig
                    }).to_string();

                    let cert_hash = hash_string(&cert_json);
                    let handle_name = format!("run:{}:cert:{}", run_id, t.id);
                    crate::db::handle_register_batch(
                        "execution_log",
                        clm_root,
                        &handle_name,
                        &cert_hash,
                        &cert_json,
                    )
                    .map_err(|e| e.to_string())?;
                }

                if is_visual {
                    out_buf.push_str(&format!(
                        "\n  -- Step {}: Firing transition {} --\n",
                        fire_count + 1,
                        t.id
                    ));
                    out_buf.push_str("  Places & Token Flows:\n");
                    for p in &net.places {
                        let pre_val = pre_markings.get(&p.id).cloned().unwrap_or(0);
                        let post_val = place_markings.get(&p.id).cloned().unwrap_or(0);

                        let emoji = match p.id.as_str() {
                            "p0" => "📥",
                            "p3" => "📤",
                            _ => "◯",
                        };
                        let bullet = if post_val > 0 { "●" } else { " " };
                        if pre_val != post_val {
                            out_buf.push_str(&format!(
                                "    {} {:<22} [{}] ({} -> {})\n",
                                emoji, p.id, bullet, pre_val, post_val
                            ));
                        } else {
                            out_buf.push_str(&format!(
                                "    {} {:<22} [{}] ({})\n",
                                emoji, p.id, bullet, post_val
                            ));
                        }
                    }

                    out_buf.push_str("  🔍 Live Noetherian Audits:\n");
                    for (pi_idx, weights) in active_p_invariants.iter().enumerate() {
                        let expected_val = active_p_constants[pi_idx];
                        let mut actual_val = 0;
                        let mut eq_terms = Vec::new();
                        for (p_idx, &w) in weights.iter().enumerate() {
                            let pid = &place_ids[p_idx];
                            let m = place_markings.get(pid).cloned().unwrap_or(0);
                            actual_val += w * m;
                            if w != 0 {
                                let term = if w == 1 {
                                    pid.clone()
                                } else if w == -1 {
                                    format!("-{}", pid)
                                } else {
                                    format!("{}*{}", w, pid)
                                };
                                eq_terms.push(term);
                            }
                        }

                        let eq_str = eq_terms.join(" + ").replace("+ -", "- ");
                        if actual_val == expected_val {
                            out_buf.push_str(&format!(
                                "     ✅ P-Inv #{}: {} = {} [OK]\n",
                                pi_idx, eq_str, expected_val
                            ));
                        } else {
                            out_buf.push_str(&format!(
                                "     ❌ P-Inv #{}: {} = {} (expected {}) [FAIL]\n",
                                pi_idx, eq_str, actual_val, expected_val
                            ));
                        }
                    }
                }

                if is_repl_trace {
                    let mut json_places = serde_json::Map::new();
                    for p in &net.places {
                        let val = place_markings.get(&p.id).cloned().unwrap_or(0);
                        json_places.insert(p.id.clone(), serde_json::Value::Number(val.into()));
                    }
                    let pinv_held = if !active_p_invariants.is_empty() {
                        let pi0 = &active_p_invariants[0];
                        let pi0_e = active_p_constants[0];
                        let mut actual = 0;
                        for (p_idx, &w) in pi0.iter().enumerate() {
                            let m = place_markings
                                .get(&place_ids[p_idx])
                                .cloned()
                                .unwrap_or(0);
                            actual += w * m;
                        }
                        actual == pi0_e
                    } else {
                        true
                    };

                    let trace_json = serde_json::json!({
                        "type": "trace",
                        "transition": t.id,
                        "agent": per_trans_agent_did,
                        "agent_class": if per_trans_agent_did.starts_with("did:key:") { "EOA" } else { "CA" },
                        "sponsor": sponsor_did,
                        "pcard": pcard_hash,
                        "cert": dp_hash,
                        "merkle": current_marking_hash,
                        "places": json_places,
                        "pinv_held": pinv_held
                    }).to_string();

                    out_buf.push_str(&format!("CLM_TRACE_JSON:{}\n", trace_json));
                    out_buf.push_str("\n===============================================================\n");
                    out_buf.push_str(&format!(
                        "  REPL Cycle {}: {}\n",
                        fire_count + 1,
                        t.id
                    ));
                    out_buf.push_str("===============================================================\n");
                    out_buf.push_str("  ┌- READ --------------------------------------------------------\n");
                    out_buf.push_str(&format!(
                        "  │  Agent:    {} {}\n",
                        if per_trans_agent_did.starts_with("did:key:") {
                            "👤"
                        } else {
                            "🤖"
                        },
                        per_trans_agent_did
                    ));
                    out_buf.push_str(&format!("  │  Sponsor:  {}\n", sponsor_did));
                    out_buf.push_str("  └---------------------------------------------------------------\n");
                }

                for (pi_idx, weights) in active_p_invariants.iter().enumerate() {
                    let expected_val = active_p_constants[pi_idx];
                    let mut actual_val = 0;
                    for (p_idx, &w) in weights.iter().enumerate() {
                        let pid = &place_ids[p_idx];
                        let m = place_markings.get(pid).cloned().unwrap_or(0);
                        actual_val += w * m;
                    }

                    if actual_val != expected_val {
                        out_buf.push_str("  ❌ [NOETHER_ERR] P-Invariant Safety Violation!\n");
                        emit_state_failed(&pcard_hash, 1, "P-Invariant Safety Violation", clm_root)?;
                        return Err(out_buf);
                    }
                }
            } else {
                out_buf.push_str(&format!(
                    "❌ [ERROR] Transition {} failed with exit_code={}\n",
                    t.id, exec_exit_code
                ));
                emit_state_failed(
                    &pcard_hash,
                    exec_exit_code,
                    &format!("Transition {} failed", t.id),
                    clm_root,
                )?;
            }

            fire_count += 1;
            cumulative_fires[ti] += 1;

            break;
        }

        if !found_enabled {
            for t in &net.transitions {
                let mut has_some = false;
                let mut has_missing = false;
                for inp in &t.inputs {
                    let cur = place_markings.get(inp).cloned().unwrap_or(0);
                    if cur > 0 {
                        has_some = true;
                    } else {
                        has_missing = true;
                    }
                }
                if has_some && has_missing {
                    deadlocked = true;
                    break;
                }
            }
            break;
        }
    }

    sync_sqlite(&place_markings, &place_colors)?;

    // ── Post-loop: T-invariant idempotency check ────────────────────────
    match verify_t_invariant_idempotency(
        &matrix.d, &cumulative_fires, fire_count,
        place_count, trans_count, &net, &place_markings,
    ) {
        Ok(buf) => out_buf.push_str(&buf),
        Err(mut err_buf) => {
            err_buf.push_str(&out_buf);
            return Err(err_buf);
        }
    }

    // ── Post-loop: assertion verification ───────────────────────────────
    let mut assert_pass = 0;
    let mut assert_fail = 0;
    if let Some(assertions) = &net.assertions {
        let (buf, pass, fail) = check_net_assertions(
            assertions, &run_id, clm_root,
            fire_count, deadlocked, &place_markings,
        );
        out_buf.push_str(&buf);
        assert_pass = pass;
        assert_fail = fail;
    }

    if is_kenotic {
        let final_status = if assert_fail == 0 { "completed" } else { "failed" };
        let final_err_msg = if assert_fail > 0 {
            format!("{} assertion(s) failed", assert_fail)
        } else {
            String::new()
        };

        let mut final_marking_hash = String::new();
        if let Ok(Some(hash)) = crate::db::resolve_handle_hash(
            "execution_log",
            clm_root,
            &format!("run:{}:marking", run_id),
        ) {
            final_marking_hash = hash;
        }
        let now = crate::utils::now_iso8601();
        let status_json = if final_status == "completed" {
            serde_json::json!({
                "@type": "RunStatus",
                "status": "completed",
                "final_marking_hash": final_marking_hash,
                "sponsor_did": sponsor_did,
                "completed_at": now
            })
            .to_string()
        } else {
            serde_json::json!({
                "@type": "RunStatus",
                "status": "failed",
                "error": final_err_msg,
                "last_marking_hash": final_marking_hash,
                "sponsor_did": sponsor_did,
                "failed_at": now
            })
            .to_string()
        };

        let status_hash = hash_string(&status_json);
        crate::db::handle_register_batch(
            "execution_log",
            clm_root,
            &format!("run:{}:status", run_id),
            &status_hash,
            &status_json,
        )
        .map_err(|e| e.to_string())?;
    }

    let mut final_marking_map = serde_json::Map::new();
    for (pid, tok) in &place_markings {
        final_marking_map.insert(pid.clone(), serde_json::Value::Number((*tok).into()));
    }
    out_buf.push_str(&format!("  [FINAL_MARKING] {}\n", serde_json::Value::Object(final_marking_map)));

    out_buf.push_str(&format!(
        "  → {} passed, {} failed ({} firings)\n",
        assert_pass, assert_fail, fire_count
    ));

    if assert_fail > 0 {
        Err(out_buf)
    } else {
        Ok(out_buf)
    }
}