use std::sync::{Arc, Mutex};
use clm_rust_core::cross_cutting::context::CLMContext;
use clm_rust_core::evaluator::dispatch::catalog::{CoreDispatchRegistry, DispatchError};
use clm_rust_core::evaluator::dispatch::catalog_ids::{OP_BALDWIN_SPLIT, OP_CORE_BALDWIN_APPLY, OP_CORE_CPN_SIMULATE};
use clm_rust_core::layer0::runtime_contract::SQLITE_DDL_V3_1;
use rusqlite::Connection;
fn store() -> Arc<Mutex<Connection>> {
let conn = Connection::open_in_memory().expect("memory");
conn.execute_batch(SQLITE_DDL_V3_1).expect("ddl");
Arc::new(Mutex::new(conn))
}
fn rows(conn: &Arc<Mutex<Connection>>) -> i64 {
conn.lock().unwrap().query_row("SELECT COUNT(*) FROM card", [], |row| row.get(0)).expect("count")
}
#[test]
fn dispatch_unbound_halts_before_any_receipt_or_store_write() {
let (content, log) = (store(), store());
let stores = vec![("content_memory", content.clone()), ("execution_log", log.clone())];
let result = CoreDispatchRegistry::from_canonical_catalog().dispatch_with_hoare(
OP_CORE_BALDWIN_APPLY, "payload", &CLMContext::for_test_sandbox(), Some(stores), false, "rcpt-unbound", "idem:unbound", "blake3|1|t",
);
let Err(error) = result else { panic!("unbound id dispatched") };
assert_eq!(error, DispatchError::Unbound(OP_CORE_BALDWIN_APPLY.to_string()));
assert_eq!(error.exit_code(), 2);
assert_eq!((rows(&content), rows(&log)), (0, 0));
}
#[test]
fn dispatch_unbound_legacy_route_reports_content_missing() {
let result = CoreDispatchRegistry::from_canonical_catalog().dispatch_legacy_route(
"clm_rust_core::baldwin::split", "x", &CLMContext::for_test_sandbox(),
);
assert_eq!(result.exit_code, 2);
assert_eq!(result.error, Some(format!("UnboundDispatchError: {OP_BALDWIN_SPLIT}")));
}
#[test]
fn dispatch_unbound_binding_a_handler_makes_the_id_dispatchable() {
let registry = CoreDispatchRegistry::from_canonical_catalog();
registry.bind_handler("cpn:simulate", Arc::new(|_ctx, payload| payload.to_uppercase())).expect("bind");
let result = registry.dispatch_legacy_route(OP_CORE_CPN_SIMULATE, "net", &CLMContext::for_test_sandbox());
assert_eq!((result.exit_code, result.output.as_str()), (0, "NET"));
}
#[test]
fn dispatch_unbound_memorize_returns_the_content_address() {
let result = CoreDispatchRegistry::from_canonical_catalog().dispatch_legacy_route("memorize:file", "hello", &CLMContext::for_test_sandbox());
assert_eq!(result.output, format!("blake3:{}", blake3::hash(b"hello").to_hex()));
}