use super::*;
#[derive(Debug, Clone)]
pub struct SeedFile {
pub path: String,
pub content: Option<Vec<u8>>,
pub source_preimage: Option<Vec<u8>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DurableSeedFile {
pub path: String,
pub content_artifact: Option<String>,
pub source_preimage_artifact: Option<String>,
}
#[derive(Debug, Clone)]
pub struct EffectOutcome {
pub output: String,
pub mutated: bool,
pub completed: bool,
}
#[derive(Debug, Clone)]
pub struct CandidateCheckpoint {
pub id: String,
pub witness: CandidateStateWitness,
}
#[async_trait::async_trait]
pub trait EffectExecutor: Send + Sync {
async fn checkpoint(&self, scope: &[String]) -> Result<CandidateCheckpoint>;
async fn apply(&self, call: &ProviderToolCall, entry: &ToolEntry) -> Result<EffectOutcome>;
async fn restore(&self, checkpoint: &CandidateCheckpoint) -> Result<()>;
async fn state_witness(&self) -> Result<CandidateStateWitness>;
async fn export_accepted(&self) -> Result<Vec<SeedFile>> {
Ok(Vec::new())
}
}
#[derive(Debug, Clone, Default)]
pub struct Measured {
pub hard_pass: bool,
pub energy: f64,
pub residuals: Vec<ResidualEvent>,
pub correction: Option<CorrectionDirection>,
pub packet: Option<perspt_sdk::CorrectionPacket>,
}
#[async_trait::async_trait]
pub trait CandidateMeasurer: Send + Sync {
async fn measure(&self) -> Result<Measured>;
async fn measure_incremental(&self) -> Result<Measured> {
self.measure().await
}
}
#[derive(Debug, Clone, Default)]
pub struct PromptEnvelope {
pub text: String,
pub invocation_digest: String,
pub manifest_digest: String,
pub stage: Option<perspt_core::prompts::PlatformStage>,
pub domain_sections: Vec<perspt_sdk::prompt::RenderedSection>,
pub invocation: Option<perspt_sdk::prompt::CompiledPromptInvocation>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "event", rename_all = "snake_case")]
pub enum LoopEvent {
ConversationSeeded {
seed: perspt_sdk::ConversationSeeded,
},
ConversationDelta {
record: perspt_sdk::ConversationDeltaRecord,
},
TurnObserved {
turn: u32,
#[serde(default)]
actor: String,
output: TurnOutput,
},
ToolCallObserved {
call: ProviderToolCall,
},
ProposalObserved {
call_id: String,
proposal: EffectProposal,
},
ProposalChecked {
call_id: String,
proposal: EffectProposal,
witness: Box<FullAdmissibilityWitness>,
},
EffectApplied {
call_id: String,
mutated: bool,
output: String,
},
ToolBatchConflict {
call_id: String,
conflicts_with: String,
resources: Vec<String>,
},
EffectDenied {
call_id: String,
reason: String,
#[serde(default = "default_denial_class")]
class: perspt_sdk::ResidualClass,
},
CandidateMeasured {
node_id: String,
generation: u32,
#[serde(default)]
candidate_id: String,
energy: f64,
hard_pass: bool,
residuals: Vec<ResidualEvent>,
},
GateDecisionRecorded {
node_id: String,
generation: u32,
#[serde(default)]
candidate_id: String,
decision: GateDecision,
#[serde(default)]
observed_energy: Option<f64>,
#[serde(default)]
best_accepted_before: Option<f64>,
},
DecisionBoundRefused {
node_id: String,
generation: u32,
bound: u64,
decisions_used: u64,
},
CandidateRestored {
checkpoint_id: String,
},
EffectBoundaryMeasured {
call_id: String,
node_id: String,
generation: u32,
energy: f64,
hard_pass: bool,
residuals: Vec<ResidualEvent>,
},
ContextCheckpointCreated {
checkpoint: ContextCheckpoint,
},
DurableCandidateCheckpoint {
#[serde(default)]
candidate_id: String,
state_root: String,
control: ControlFrame,
conversation: Conversation,
#[serde(default)]
birth_deps: Vec<perspt_sdk::prompt::StateDependency>,
canonical_scope: Vec<String>,
files: Vec<DurableSeedFile>,
},
RecoveryControlGranted {
failure: FailureKind,
level: perspt_sdk::CascadeLevel,
forced_escalation: bool,
model: ModelId,
},
RouteFailover {
from_model: ModelId,
to_model: ModelId,
cause: String,
},
RecoveryContained {
reason: String,
restored_checkpoint_id: String,
},
SearchOpened {
forest_id: String,
node_id: String,
generation: u32,
accepted_root: String,
limits: perspt_sdk::SearchLimits,
#[serde(default, skip_serializing_if = "Option::is_none")]
resumed_from: Option<String>,
},
SearchUsageSnapshot {
forest_id: String,
epoch: u64,
usage: perspt_sdk::SearchUsage,
},
BranchForked {
forest_id: String,
branch_id: String,
#[serde(default)]
parent_branch: Option<String>,
seed_checkpoint: String,
seed_witness: perspt_sdk::WitnessRef,
},
BranchStrategySelected {
forest_id: String,
branch_id: String,
strategy_id: String,
},
BranchObservation {
forest_id: String,
branch_id: String,
observation: String,
},
BranchCandidateMeasured {
forest_id: String,
branch_id: String,
candidate_id: String,
measurement: perspt_sdk::BranchMeasurement,
},
PartialCheckpointed {
forest_id: String,
branch_id: String,
checkpoint: perspt_sdk::PartialCheckpointRef,
},
FrontierEpochStarted {
forest_id: String,
epoch: u64,
forest_digest: String,
},
FrontierEntryServed {
forest_id: String,
branch_id: String,
epoch: u64,
},
BranchIneligible {
forest_id: String,
branch_id: String,
reason: String,
},
BranchNotSelected {
forest_id: String,
branch_id: String,
},
BranchAbandoned {
forest_id: String,
branch_id: String,
reason: String,
},
BranchSelected {
forest_id: String,
branch_id: String,
candidate_id: String,
},
BranchCommitted {
forest_id: String,
branch_id: String,
candidate_id: String,
decision: GateDecision,
},
NoGoodRecorded {
forest_id: String,
branch_id: String,
key: String,
evidence_hash: String,
#[serde(default)]
support_kind: String,
},
SearchClosed {
forest_id: String,
usage: perspt_sdk::SearchUsage,
},
ContextWorkingSet {
#[serde(default)]
forest_id: String,
#[serde(default)]
branch_id: String,
turn: u32,
page_ids: Vec<String>,
},
ContextPagesSelected {
#[serde(default)]
forest_id: String,
#[serde(default)]
branch_id: String,
turn: u32,
resident_digest: String,
page_ids: Vec<String>,
},
ContextMiss {
#[serde(default)]
forest_id: String,
#[serde(default)]
branch_id: String,
turn: u32,
key: String,
},
ContextPageRecalled {
#[serde(default)]
forest_id: String,
#[serde(default)]
branch_id: String,
turn: u32,
page_id: String,
},
ContextInfeasible {
#[serde(default)]
forest_id: String,
#[serde(default)]
branch_id: String,
turn: u32,
required: u64,
allowance: u64,
},
ContextCompacted {
#[serde(default)]
forest_id: String,
#[serde(default)]
branch_id: String,
summary_page: String,
source_pages: Vec<String>,
},
PromptProgramCompiled {
turn: u32,
program: perspt_sdk::prompt::CompiledPromptProgram,
},
PromptProgramInvoked {
turn: u32,
invocation_digest: String,
platform_digest: String,
domain_digest: String,
tool_spec_hash: String,
#[serde(default)]
resident_context_digest: String,
},
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoopEventEnvelopeV1 {
pub schema_version: u16,
pub body: LoopEvent,
}
impl LoopEventEnvelopeV1 {
pub fn new(body: LoopEvent) -> Self {
Self {
schema_version: 1,
body,
}
}
}
fn default_denial_class() -> perspt_sdk::ResidualClass {
perspt_sdk::ResidualClass::CapabilityDenied
}
#[derive(Debug, Default)]
pub struct EventLog {
retained: Vec<LoopEvent>,
retain: bool,
count: u64,
chain_root: String,
}
impl EventLog {
pub(super) fn new(retain: bool) -> Self {
Self {
retain,
..Self::default()
}
}
pub(super) fn push(&mut self, event: &LoopEvent) -> Result<()> {
let hashed = perspt_sdk::ledger::content_hash(&serde_json::to_vec(event)?);
self.chain_root =
perspt_sdk::ledger::content_hash(format!("{}:{hashed}", self.chain_root).as_bytes());
self.count += 1;
if self.retain {
self.retained.push(event.clone());
}
Ok(())
}
pub fn count(&self) -> u64 {
self.count
}
pub fn chain_root(&self) -> &str {
&self.chain_root
}
pub fn events(&self) -> &[LoopEvent] {
&self.retained
}
pub(super) fn into_events(self) -> Vec<LoopEvent> {
self.retained
}
}
pub trait LoopRecorder: Send + Sync {
fn record(&self, event: &LoopEvent) -> Result<()>;
fn external_intent(&self, _key: &str, _intent: &serde_json::Value) -> Result<()> {
Ok(())
}
fn external_result(&self, _key: &str, _result: &serde_json::Value) -> Result<()> {
Ok(())
}
fn record_artifact(&self, content: &[u8], _media_type: &str) -> Result<String> {
Ok(perspt_sdk::ledger::content_hash(content))
}
fn fetch_artifact(&self, _handle: &str) -> Result<Option<Vec<u8>>> {
Ok(None)
}
}
#[derive(Debug)]
pub struct LoopOutcome {
pub outcome: NodeTerminalOutcome,
pub trajectory: AcceptedTrajectory,
pub events: Vec<LoopEvent>,
pub projection: ProjectionMismatch,
pub turns_used: u32,
pub recovery_spent: u32,
pub contained_by_transport: bool,
}