use super::types::pcard_hash_placeholder;
use super::invariants::{build_incidence_matrix, compute_invariants, verify_t_invariant_idempotency};
use super::zta::{check_consensus, check_transition_acl};
use super::token_ops::{write_marking_dir, serialize_pcard};
use super::binding::execute_pcard_binding;
use super::transition_post::{handle_post_transition, PostTransitionArgs};
use super::assertions::evaluate_engine_assertions;
use super::engine_init::{parse_topology, resolve_run_paths, format_invariants_banner, sync_sqlite_markings, init_kenotic_state};
use crate::epiplexity::EpiplexityMetrics;
use std::collections::HashMap;
use std::fs;
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 = crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_CLM_PETRI_KENOTIC).unwrap_or_default() == "true";
let (run_id, marking_dir, zero_fs, log_path) = resolve_run_paths(clm_root, &net.name);
let mut scoped_vars = HashMap::new();
scoped_vars.insert(crate::layer0::vocabulary_env::ENV_CLM_RUN_ID.to_string(), run_id.clone());
scoped_vars.insert(crate::layer0::vocabulary_env::ENV_CLM_EVENT_LOG_PATH.to_string(), log_path.clone());
if !marking_dir.is_empty() {
scoped_vars.insert(crate::layer0::vocabulary_env::ENV_CLM_PETRI_MARKING_DIR.to_string(), marking_dir.clone());
}
let mut vm_ctx = crate::cross_cutting::context::CLMContext::current().with_child_scope(
crate::cross_cutting::context::CLMContextOverrides {
run_id: Some(run_id.clone()),
scoped_vars,
..Default::default()
},
);
let _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, trans_count) = (matrix.place_count, matrix.trans_count);
let inv = compute_invariants(&net, &matrix, &place_ids, &place_markings);
let (active_p_invariants, active_p_constants, active_t_invariants) =
(inv.p_invariants, inv.p_constants, inv.t_invariants);
let mut out_buf = format_invariants_banner(&active_p_invariants, &active_p_constants, &active_t_invariants);
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(crate::layer0::vocabulary_env::PILLAR_EXECUTION_LOG, clm_root)
.map_err(|e| format!("Failed to connect to execution_log DB: {}", e))?;
let sync_sqlite = |pm: &HashMap<String, i64>, pc: &HashMap<String, String>| {
sync_sqlite_markings(&net.places, pm, pc, &run_id, clm_root)
};
sync_sqlite(&place_markings, &place_colors)?;
let mut current_marking_hash = String::new();
let sponsor_did = crate::layer0::environment::var("ACTIVE_AGENT_DID")
.or_else(|_| crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_CLM_AGENT_DID))
.unwrap_or_else(|_| crate::layer0::vocabulary_identities::DID_CLM_BOOTSTRAP.to_string());
let mut _kenotic_guard = None;
if is_kenotic {
let init_marking_hash = init_kenotic_state(
&net, &topo_content, &place_markings, &place_colors,
&run_id, clm_root, &sponsor_did, &mut vm_ctx,
)?;
_kenotic_guard = Some(vm_ctx.enter_scope());
let sponsor_class = if sponsor_did.starts_with(crate::layer0::vocabulary_identities::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 = crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_CLM_PETRI_VISUAL).unwrap_or_default() == "1";
let is_repl_trace = crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_CLM_REPL_TRACE).unwrap_or_default() == "1";
loop {
if crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_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(|| {
crate::layer0::environment::var("ACTIVE_AGENT_DID")
.or_else(|_| crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_CLM_AGENT_DID))
.unwrap_or_else(|_| crate::layer0::vocabulary_identities::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);
let post_args = PostTransitionArgs {
exec_exit_code,
db_conn: &db_conn,
pcard_hash: &pcard_hash,
dp_hash: &dp_hash,
final_content: &final_content,
clm_root,
t,
place_markings: &mut place_markings,
place_colors: &mut place_colors,
per_trans_agent_did: &per_trans_agent_did,
is_kenotic,
topo_content: &topo_content,
net: &net,
sponsor_did: &sponsor_did,
current_marking_hash: &mut current_marking_hash,
vm_ctx: &mut vm_ctx,
run_id: &run_id,
input_token_hashes: &input_token_hashes,
is_visual,
fire_count,
pre_markings: &pre_markings,
active_p_invariants: &active_p_invariants,
active_p_constants: &active_p_constants,
place_ids: &place_ids,
is_repl_trace,
marking_dir: &marking_dir,
};
handle_post_transition(post_args, sync_sqlite, &mut out_buf)?;
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)?;
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);
}
}
evaluate_engine_assertions(
&net,
&run_id,
clm_root,
fire_count,
deadlocked,
&place_markings,
is_kenotic,
&sponsor_did,
out_buf,
)
}