use anyhow::Result;
use perspt_sdk::ledger::{tool_loop_body, ToolLoopBody};
use super::contract::{LoopEvent, LoopEventEnvelopeV1};
#[derive(Debug, Clone)]
pub struct DecodedLoopEvent {
pub version: u16,
pub event: LoopEvent,
}
pub(crate) fn is_legacy_variant(event: &LoopEvent) -> bool {
match event {
LoopEvent::ConversationSeeded { .. }
| LoopEvent::ConversationDelta { .. }
| LoopEvent::TurnObserved { .. }
| LoopEvent::ToolCallObserved { .. }
| LoopEvent::ProposalObserved { .. }
| LoopEvent::ProposalChecked { .. }
| LoopEvent::EffectApplied { .. }
| LoopEvent::ToolBatchConflict { .. }
| LoopEvent::EffectDenied { .. }
| LoopEvent::CandidateMeasured { .. }
| LoopEvent::GateDecisionRecorded { .. }
| LoopEvent::DecisionBoundRefused { .. }
| LoopEvent::CandidateRestored { .. }
| LoopEvent::EffectBoundaryMeasured { .. }
| LoopEvent::ContextCheckpointCreated { .. }
| LoopEvent::DurableCandidateCheckpoint { .. }
| LoopEvent::RecoveryControlGranted { .. }
| LoopEvent::RouteFailover { .. }
| LoopEvent::RecoveryContained { .. } => true,
LoopEvent::SearchOpened { .. }
| LoopEvent::SearchUsageSnapshot { .. }
| LoopEvent::BranchForked { .. }
| LoopEvent::BranchStrategySelected { .. }
| LoopEvent::BranchObservation { .. }
| LoopEvent::BranchCandidateMeasured { .. }
| LoopEvent::PartialCheckpointed { .. }
| LoopEvent::FrontierEpochStarted { .. }
| LoopEvent::FrontierEntryServed { .. }
| LoopEvent::BranchIneligible { .. }
| LoopEvent::BranchNotSelected { .. }
| LoopEvent::BranchAbandoned { .. }
| LoopEvent::BranchSelected { .. }
| LoopEvent::BranchCommitted { .. }
| LoopEvent::NoGoodRecorded { .. }
| LoopEvent::SearchClosed { .. }
| LoopEvent::ContextWorkingSet { .. }
| LoopEvent::ContextPagesSelected { .. }
| LoopEvent::ContextMiss { .. }
| LoopEvent::ContextPageRecalled { .. }
| LoopEvent::ContextInfeasible { .. }
| LoopEvent::PromptProgramCompiled { .. }
| LoopEvent::PromptProgramInvoked { .. }
| LoopEvent::ContextCompacted { .. } => false,
}
}
pub fn decode_tool_loop(payload: &serde_json::Value) -> Result<DecodedLoopEvent> {
match tool_loop_body(payload).map_err(|e| anyhow::anyhow!("{e}"))? {
ToolLoopBody::Legacy(body) => {
let event: LoopEvent = serde_json::from_value(body.clone())?;
anyhow::ensure!(
is_legacy_variant(&event),
"a PSP-10 event appeared in an unversioned legacy row; refusing"
);
Ok(DecodedLoopEvent { version: 0, event })
}
ToolLoopBody::V1(_) => {
let envelope: LoopEventEnvelopeV1 = serde_json::from_value(payload.clone())?;
anyhow::ensure!(
envelope.schema_version == 1,
"envelope version {} is not 1",
envelope.schema_version
);
Ok(DecodedLoopEvent {
version: 1,
event: envelope.body,
})
}
}
}