#![allow(unused_imports)]
use crate::layer0::vocabulary::{HASH_PREFIX_BLAKE3};
use super::*;
const STATUS_COMMITTED: &str = "committed";
const WITNESS_POST_ROLLBACK: &str = "post_rollback_witness";
const GATE_PAYLOAD_NONEMPTY: &str = "gate:payload_nonempty";
const GATE_UNNAMED: &str = "gate";
impl CoreDispatchRegistry {
pub fn list_core_op_ids(&self) -> Vec<String> {
let st = self.state.lock().unwrap();
st.core_entries.keys().cloned().collect()
}
pub fn list_all_op_ids(&self) -> Vec<String> {
let st = self.state.lock().unwrap();
let mut keys: Vec<String> = st
.core_entries
.keys()
.chain(st.plugin_entries.keys())
.cloned()
.collect();
keys.sort();
keys.dedup();
keys
}
pub fn export_canonical_catalog_json(&self) -> String {
let st = self.state.lock().unwrap();
let entries: Vec<DispatchCatalogEntry> = st.core_entries.values().cloned().collect();
let doc = DispatchCatalogDoc {
catalog_version: CATALOG_VERSION.to_string(),
entries,
schema: CATALOG_SCHEMA_REF.to_string(),
};
let mut out = serde_json::to_string_pretty(&doc).expect("serialize catalog");
out.push('\n');
out
}
pub fn catalog_blake3_hash(&self) -> String {
let json = self.export_canonical_catalog_json();
format!("{HASH_PREFIX_BLAKE3}{}", blake3::hash(json.as_bytes()).to_hex())
}
pub fn dispatch_legacy_route(
&self,
route: &str,
payload: &str,
ctx: &CLMContext,
) -> LegacyDispatchResult {
let bound = self.resolve_entry(route)
.ok_or_else(|| DispatchError::NotFound(route.to_string()))
.and_then(|entry| self.bound_handler(&entry.op_id));
let handler = match bound {
Ok(handler) => handler,
Err(error) => {
return LegacyDispatchResult { exit_code: error.exit_code(), output: String::new(), error: Some(error.to_string()) };
}
};
let output = handler(ctx, payload);
LegacyDispatchResult {
exit_code: ClmExitCode::Ok as i32,
output,
error: None,
}
}
#[allow(clippy::too_many_arguments)]
pub fn dispatch_with_hoare(
&self,
op_id_or_route: &str,
payload: &str,
ctx: &CLMContext,
stores: Option<Vec<(&str, Arc<Mutex<Connection>>)>>,
simulate_post_failure: bool,
receipt_id: &str,
idempotency_key: &str,
g_time: &str,
) -> Result<HoareDispatchResult, DispatchError> {
let entry = self.resolve_entry(op_id_or_route).ok_or_else(|| DispatchError::NotFound(op_id_or_route.to_string()))?;
let handler = self.bound_handler(&entry.op_id)?;
let input_hash = format!("{HASH_PREFIX_BLAKE3}{}", blake3::hash(payload.as_bytes()).to_hex());
if entry.verification_policy != "required" {
let output = handler(ctx, payload);
let output_hash = Some(format!(
"{HASH_PREFIX_BLAKE3}{}",
blake3::hash(output.as_bytes()).to_hex()
));
let receipt = ExecutionReceipt::build(ExecutionReceiptWithoutHash {
agent_did: ctx.agent_did().to_string(),
dispatch_catalog_hash: None,
error: None,
exit_code: ClmExitCode::Ok as i32,
g_time: g_time.to_string(),
handler_key: entry.handler_key,
idempotency_key: idempotency_key.to_string(),
input_hash,
op_id: entry.op_id,
output_hash,
parameter_context_hash: None,
receipt_id: receipt_id.to_string(),
schema_version: RECEIPT_SCHEMA_VERSION.to_string(),
status: STATUS_COMMITTED.to_string(),
witness_policy: "none".to_string(),
});
return Ok(HoareDispatchResult {
exit_code: ClmExitCode::Ok as i32,
output,
handler_called: true,
receipt,
});
}
let sp_name = format!("sp_hoare_{}", receipt_id.replace('-', "_"));
let mut guard = match stores.as_ref() {
Some(conns) => Some(TriDbSavepointGuard::with_connections(
&sp_name,
conns.clone(),
)?),
None => None,
};
if entry.pre_gate.as_deref() == Some(GATE_PAYLOAD_NONEMPTY) && payload.trim().is_empty()
{
if let Some(mut g) = guard.take() {
let _ = g.rollback();
}
let receipt = ExecutionReceipt::build(ExecutionReceiptWithoutHash {
agent_did: ctx.agent_did().to_string(),
dispatch_catalog_hash: None,
error: Some(ReceiptError {
code: ClmExitCode::PreconditionOrBoundaryViolation as i32,
message: format!(
"Precondition {} failed: empty payload",
entry.pre_gate.as_deref().unwrap_or(GATE_UNNAMED)
),
phase: "precondition".to_string(),
}),
exit_code: ClmExitCode::PreconditionOrBoundaryViolation as i32,
g_time: g_time.to_string(),
handler_key: entry.handler_key,
idempotency_key: idempotency_key.to_string(),
input_hash,
op_id: entry.op_id,
output_hash: None,
parameter_context_hash: None,
receipt_id: receipt_id.to_string(),
schema_version: RECEIPT_SCHEMA_VERSION.to_string(),
status: "precondition_failed".to_string(),
witness_policy: WITNESS_POST_ROLLBACK.to_string(),
});
if let Some(ref conns) = stores {
for (label, conn) in conns {
if *label == crate::layer0::vocabulary_env::PILLAR_EXECUTION_LOG {
let c = conn.lock().unwrap();
let _ = c.execute(
"INSERT OR REPLACE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3);",
params![
format!("witness:{}", receipt.receipt_id),
serde_json::to_vec(&receipt).unwrap_or_default(),
g_time
],
);
}
}
}
return Ok(HoareDispatchResult {
exit_code: ClmExitCode::PreconditionOrBoundaryViolation as i32,
output: String::new(),
handler_called: false,
receipt,
});
}
let output = handler(ctx, payload);
if let Some(ref conns) = stores {
for (label, conn) in conns {
if *label == crate::layer0::vocabulary_env::PILLAR_CONTENT_MEMORY {
let c = conn.lock().unwrap();
let _ = c.execute(
"INSERT OR REPLACE INTO card (hash, content, g_time) VALUES ('card_memorized', ?1, ?2);",
params![output.as_bytes(), g_time],
);
} else if *label == crate::layer0::vocabulary_env::PILLAR_EXECUTION_LOG {
let c = conn.lock().unwrap();
let _ = c.execute(
"INSERT OR REPLACE INTO card (hash, content, g_time) VALUES ('log_in_tx', ?1, ?2);",
params![output.as_bytes(), g_time],
);
}
}
}
if simulate_post_failure
|| (entry.post_gate.as_deref() == Some(GATE_PAYLOAD_NONEMPTY)
&& output.trim().is_empty())
{
if let Some(mut g) = guard.take() {
let _ = g.rollback();
}
let receipt = ExecutionReceipt::build(ExecutionReceiptWithoutHash {
agent_did: ctx.agent_did().to_string(),
dispatch_catalog_hash: None,
error: Some(ReceiptError {
code: ClmExitCode::PostconditionOrCycleViolation as i32,
message: format!(
"Postcondition {} failed: digest mismatch",
entry.post_gate.as_deref().unwrap_or(GATE_UNNAMED)
),
phase: "postcondition".to_string(),
}),
exit_code: ClmExitCode::PostconditionOrCycleViolation as i32,
g_time: g_time.to_string(),
handler_key: entry.handler_key,
idempotency_key: idempotency_key.to_string(),
input_hash,
op_id: entry.op_id,
output_hash: None,
parameter_context_hash: None,
receipt_id: receipt_id.to_string(),
schema_version: RECEIPT_SCHEMA_VERSION.to_string(),
status: "postcondition_failed".to_string(),
witness_policy: WITNESS_POST_ROLLBACK.to_string(),
});
if let Some(ref conns) = stores {
for (label, conn) in conns {
if *label == crate::layer0::vocabulary_env::PILLAR_EXECUTION_LOG {
let c = conn.lock().unwrap();
let _ = c.execute(
"INSERT OR REPLACE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3);",
params![
format!("witness:{}", receipt.receipt_id),
serde_json::to_vec(&receipt).unwrap_or_default(),
g_time
],
);
}
}
}
return Ok(HoareDispatchResult {
exit_code: ClmExitCode::PostconditionOrCycleViolation as i32,
output: String::new(),
handler_called: true,
receipt,
});
}
let output_hash = Some(format!(
"{HASH_PREFIX_BLAKE3}{}",
blake3::hash(output.as_bytes()).to_hex()
));
let receipt = ExecutionReceipt::build(ExecutionReceiptWithoutHash {
agent_did: ctx.agent_did().to_string(),
dispatch_catalog_hash: None,
error: None,
exit_code: ClmExitCode::Ok as i32,
g_time: g_time.to_string(),
handler_key: entry.handler_key,
idempotency_key: idempotency_key.to_string(),
input_hash,
op_id: entry.op_id,
output_hash,
parameter_context_hash: None,
receipt_id: receipt_id.to_string(),
schema_version: RECEIPT_SCHEMA_VERSION.to_string(),
status: STATUS_COMMITTED.to_string(),
witness_policy: "in_transaction".to_string(),
});
if let Some(ref conns) = stores {
for (label, conn) in conns {
if *label == crate::layer0::vocabulary_env::PILLAR_EXECUTION_LOG {
let c = conn.lock().unwrap();
let _ = c.execute(
"INSERT OR REPLACE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3);",
params![
format!("receipt:{}", receipt.idempotency_key),
serde_json::to_vec(&receipt).unwrap_or_default(),
g_time
],
);
}
}
}
if let Some(mut g) = guard.take() {
g.commit()?;
}
Ok(HoareDispatchResult {
exit_code: ClmExitCode::Ok as i32,
output,
handler_called: true,
receipt,
})
}
}