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;
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 mut vm_ctx = crate::cross_cutting::context::CLMContext::current();
let run_id = crate::cross_cutting::context::CLMContext::get_scoped_or_env("CLM_RUN_ID").unwrap_or_else(|| {
let ts = chrono::Utc::now().timestamp();
let generated = format!("pn_{}_{}_{}", net.name, ts, std::process::id());
vm_ctx.set_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();
vm_ctx.set_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();
vm_ctx.set_var("CLM_PETRI_MARKING_DIR", &marking_dir);
}
let mut _vm_ctx_guard = vm_ctx.enter_scope();
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());
}
let matrix = build_incidence_matrix(&net);
let place_count = matrix.place_count;
let trans_count = matrix.trans_count;
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));
}
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)
})?;
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),
&[],
&crate::utils::now_iso8601(),
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);
include!("engine_transition_post.rs");
}
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)?;
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);
}
}
include!("engine_assertions.rs")
}