clm-kernel 0.0.7

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
{
            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)
                                {
                                    // Canonical coordinate rather than a bare ISO timestamp (charter L2).
                                    let ts = crate::fs_utils::compute_g_time();
                                    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();
                    vm_ctx.set_var("CLM_KENOTIC_CURRENT_MARKING_HASH", &post_marking_hash);
                    _vm_ctx_guard = vm_ctx.enter_scope();

                    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;
}