use crate::fiber::{EventBus, Fiber, FiberState};
use super::element::{SatoriElement, SatoriMessage};
use std::sync::{Arc, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MaxwellReceipt {
pub verified: bool,
pub cohomology_h1: u32,
pub lagrangian_delta: i64,
pub hash: String,
pub rejection_reason: Option<String>,
}
pub fn audit_maxwell_demon(msg: &SatoriMessage) -> Result<MaxwellReceipt, String> {
if !msg.user_did.starts_with("did:") {
return Ok(MaxwellReceipt {
verified: false,
cohomology_h1: 1, lagrangian_delta: -1,
hash: msg.content_hash(),
rejection_reason: Some(format!(
"Cohomology Class H^1 != 0: Un-grounded DID contributor identity '{}'",
msg.user_did
)),
});
}
if msg.elements.is_empty() {
return Ok(MaxwellReceipt {
verified: false,
cohomology_h1: 1,
lagrangian_delta: -1,
hash: msg.content_hash(),
rejection_reason: Some(
"Cohomology Class H^1 != 0: Empty message section cannot glue into Data Harness".to_string(),
),
});
}
for elem in &msg.elements {
if let SatoriElement::Text { text } = elem
&& (text.contains("[HALLUCINATED]") || text.contains("<hallucination>")) {
return Ok(MaxwellReceipt {
verified: false,
cohomology_h1: 1,
lagrangian_delta: -1,
hash: msg.content_hash(),
rejection_reason: Some(
"Cohomology Class H^1 != 0: Detected ungrounded hallucinated tokens in execution section".to_string(),
),
});
}
}
let hash = msg.content_hash();
if hash.is_empty() {
return Err("Failed to compute BLAKE3 content hash".to_string());
}
Ok(MaxwellReceipt {
verified: true,
cohomology_h1: 0,
lagrangian_delta: 1, hash,
rejection_reason: None,
})
}
pub struct DelimitedContinuation {
pub fiber_id: String,
pub channel_id: String,
pub topic: String,
pub prompt: String,
pub ttl_ms: u64,
pub created_at: u64,
pub resumed_message: Arc<Mutex<Option<SatoriMessage>>>,
}
impl DelimitedContinuation {
pub fn new(
fiber_id: impl Into<String>,
channel_id: impl Into<String>,
prompt: impl Into<String>,
ttl_ms: u64,
) -> Self {
let channel = channel_id.into();
let topic = format!("message:received:{}", channel);
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
Self {
fiber_id: fiber_id.into(),
channel_id: channel,
topic,
prompt: prompt.into(),
ttl_ms,
created_at: now,
resumed_message: Arc::new(Mutex::new(None)),
}
}
}
pub fn park_fiber_continuation(
fiber: &Arc<Fiber>,
event_bus: &EventBus,
continuation: &DelimitedContinuation,
) -> Result<Box<dyn FnOnce() -> Result<(), String> + Send>, String> {
if fiber.get_state() != FiberState::Active {
return Err(format!(
"Cannot park fiber in state {:?}",
fiber.get_state()
));
}
fiber.suspend()?;
let fiber_ref = Arc::downgrade(fiber);
let msg_storage = continuation.resumed_message.clone();
let unregister = event_bus.subscribe(&continuation.topic, move |payload| {
if let Ok(msg) = serde_json::from_value::<SatoriMessage>(payload.clone()) {
if let Ok(receipt) = audit_maxwell_demon(&msg)
&& receipt.verified {
let mut stored = msg_storage.lock().unwrap();
*stored = Some(msg);
if let Some(f) = fiber_ref.upgrade() {
let _ = f.resume();
}
return Ok(serde_json::to_value(receipt).unwrap_or(payload));
}
}
Ok(payload)
});
Ok(unregister)
}
pub fn resume_continuation(
fiber: &Fiber,
continuation: &DelimitedContinuation,
msg: SatoriMessage,
) -> Result<MaxwellReceipt, String> {
let receipt = audit_maxwell_demon(&msg)?;
if !receipt.verified {
return Err(receipt.rejection_reason.unwrap_or_else(|| "Maxwell's Demon rejected message".to_string()));
}
{
let mut stored = continuation.resumed_message.lock().unwrap();
*stored = Some(msg);
}
fiber.resume()?;
Ok(receipt)
}
pub fn timeout_continuation(fiber: &Fiber) -> Result<(), String> {
fiber
.transition_to(FiberState::Unloading)
.map_err(|e| format!("Failed to transition to Unloading: {}", e))?;
let unwind_res = fiber.unwind_disposables();
fiber
.transition_to(FiberState::Failed("Continuation timeout: disposables unwound".to_string()))
.map_err(|e| format!("Failed to set Failed state: {}", e))?;
match unwind_res {
Ok(()) => Ok(()),
Err(errors) => Err(format!("Errors during timeout disposal: {:?}", errors)),
}
}