use std::collections::BTreeMap;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use sha2::{Digest, Sha256};
use crate::error::RustyError;
use crate::llm::Usage;
pub const CURRENT_FORMAT_VERSION: u32 = 1;
pub const INLINE_PAYLOAD_MAX_BYTES: usize = 4096;
pub fn sha256_hex(bytes: &[u8]) -> String {
let mut hasher = Sha256::new();
hasher.update(bytes);
let digest = hasher.finalize();
let mut out = String::with_capacity(digest.len() * 2);
for byte in digest {
use std::fmt::Write as _;
let _ = write!(out, "{byte:02x}");
}
out
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Effect {
Pure,
ReadOnly,
Idempotent,
Compensatable,
NonIdempotent,
}
impl Effect {
pub fn is_freely_repeatable(self) -> bool {
matches!(self, Effect::Pure | Effect::ReadOnly | Effect::Idempotent)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct PolicyVersion(pub String);
impl PolicyVersion {
pub const STATIC_V0: &'static str = "static-v0";
pub fn new(version: impl Into<String>) -> Self {
Self(version.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl Default for PolicyVersion {
fn default() -> Self {
Self(Self::STATIC_V0.to_owned())
}
}
impl std::fmt::Display for PolicyVersion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArtifactRef {
pub sha256: String,
pub bytes: u64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
pub enum PayloadRef {
Inline(Value),
Artifact(ArtifactRef),
}
impl PayloadRef {
pub fn inline(value: Value) -> Self {
PayloadRef::Inline(value)
}
pub fn content_hash(&self) -> Result<String, serde_json::Error> {
match self {
PayloadRef::Inline(value) => {
let bytes = serde_json::to_vec(&canonicalize_value(value))?;
Ok(sha256_hex(&bytes))
}
PayloadRef::Artifact(reference) => Ok(reference.sha256.clone()),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EffectReceipt {
pub provider: String,
pub provider_id: String,
pub idempotency_key: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub task_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub effect_id: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EventStatus {
Ok,
Error,
Interrupted,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RunEventKind {
SuperStepStart,
SuperStepEnd,
NodeInput,
NodeOutput,
ModelCall,
ToolCall,
RemoteCall,
WasmCall,
Interrupt,
Resume,
RoutingDecision,
CheckpointWritten,
EffectReceipt,
AgentSpawn,
AgentExit,
MailboxSend,
MailboxReceive,
SupervisionEvent,
CoordinationStart,
CoordinationEnd,
MemoryRead,
MemoryWrite,
MemoryForget,
CandidateCreated,
CandidateEvaluated,
CandidatePromoted,
CandidateRolledBack,
PolicyDecision,
CapsuleResolved,
CapsuleCall,
CapsuleDenied,
SigningKeyRotated,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RunEvent {
pub id: String,
pub run_id: String,
pub thread_id: String,
pub node_id: Option<String>,
pub seq: u64,
pub kind: RunEventKind,
pub effect: Effect,
pub input: Option<PayloadRef>,
pub output: Option<PayloadRef>,
pub latency_ms: Option<u64>,
pub tokens: Option<Usage>,
pub cost_usd: Option<f64>,
pub status: EventStatus,
pub parent: Option<String>,
pub recorded_at: DateTime<Utc>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DecisionFamily {
Retry,
Timeout,
WorkerPlacement,
Concurrency,
CheckpointPlacement,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "action", rename_all = "snake_case")]
pub enum DecisionAction {
Retry {
attempt: u32,
},
Abort,
SetTimeout {
millis: u64,
},
SelectWorker {
worker: String,
},
SetConcurrency {
limit: u32,
},
WriteCheckpoint,
SkipCheckpoint,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DecisionOutcome {
Success,
Failure,
Cancelled,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DecisionRole {
Acting,
Shadow,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DecisionEvent {
pub id: String,
pub run_id: String,
pub thread_id: String,
pub seq: u64,
pub family: DecisionFamily,
pub features: Map<String, Value>,
pub legal_actions: Vec<DecisionAction>,
pub selected: DecisionAction,
pub propensity: f64,
pub policy_version: PolicyVersion,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub role: Option<DecisionRole>,
pub outcome: Option<DecisionOutcome>,
pub decided_at: DateTime<Utc>,
}
pub const POLICY_MAX_DELAY_ENVELOPE_MS: u64 = 3_600_000;
pub const POLICY_MAX_ATTEMPTS_ENVELOPE: u32 = 10;
pub const MIN_TIMEOUT_RUNG_MS: u64 = 100;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct BackoffParameters {
pub base_delay_ms: u64,
pub max_delay_ms: u64,
pub max_attempts: u32,
}
impl BackoffParameters {
pub fn validate(&self) -> crate::error::Result<()> {
let invalid = |message: String| RustyError::InvalidUpdate(message);
if self.base_delay_ms == 0 {
return Err(invalid(
"backoff base_delay_ms must be positive — a zero base retries immediately, \
a retry storm by another name"
.to_owned(),
));
}
if self.base_delay_ms > self.max_delay_ms {
return Err(invalid(format!(
"backoff base_delay_ms {} exceeds max_delay_ms {} — the schedule would clamp \
to the cap from the first retry, an exponential in name only",
self.base_delay_ms, self.max_delay_ms
)));
}
if self.max_delay_ms > POLICY_MAX_DELAY_ENVELOPE_MS {
return Err(invalid(format!(
"backoff max_delay_ms {} exceeds the {POLICY_MAX_DELAY_ENVELOPE_MS} ms \
envelope",
self.max_delay_ms
)));
}
if self.max_attempts > POLICY_MAX_ATTEMPTS_ENVELOPE {
return Err(invalid(format!(
"backoff max_attempts {} exceeds the {POLICY_MAX_ATTEMPTS_ENVELOPE}-attempt \
envelope",
self.max_attempts
)));
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RetryPolicyParameters {
pub base_delay_ms: u64,
pub max_delay_ms: u64,
pub max_attempts: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub per_class: Option<BTreeMap<crate::durable::ErrorClass, BackoffParameters>>,
}
impl RetryPolicyParameters {
pub fn flat(&self) -> BackoffParameters {
BackoffParameters {
base_delay_ms: self.base_delay_ms,
max_delay_ms: self.max_delay_ms,
max_attempts: self.max_attempts,
}
}
pub fn validate(&self) -> crate::error::Result<()> {
self.flat().validate()?;
if let Some(per_class) = &self.per_class {
for (class, schedule) in per_class {
schedule.validate().map_err(|e| {
RustyError::InvalidUpdate(format!("per-class backoff for {class:?}: {e}"))
})?;
}
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TimeoutPolicyParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub default_millis: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_millis: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub per_callee: Option<BTreeMap<String, u64>>,
}
impl TimeoutPolicyParameters {
pub fn validate(&self) -> crate::error::Result<()> {
let invalid = |message: String| RustyError::InvalidUpdate(message);
let check_floor = |what: &str, millis: u64| -> crate::error::Result<()> {
if millis < MIN_TIMEOUT_RUNG_MS {
return Err(invalid(format!(
"timeout {what} {millis} ms is below the {MIN_TIMEOUT_RUNG_MS} ms minimum \
rung — below it ordinary work aborts early, a correctness hazard no \
policy may cross"
)));
}
Ok(())
};
if let Some(default) = self.default_millis {
check_floor("default_millis", default)?;
}
if let Some(max) = self.max_millis {
check_floor("max_millis", max)?;
}
if let (Some(default), Some(max)) = (self.default_millis, self.max_millis) {
if default > max {
return Err(invalid(format!(
"timeout default_millis {default} exceeds max_millis {max} — the default \
bound would sit above its own ceiling"
)));
}
}
if let Some(per_callee) = &self.per_callee {
for (callee, millis) in per_callee {
check_floor(&format!("per_callee[{callee}]"), *millis)?;
if let Some(max) = self.max_millis {
if *millis > max {
return Err(invalid(format!(
"timeout per_callee[{callee}] {millis} ms exceeds max_millis \
{max} — a learned bound may only narrow the declared ceiling"
)));
}
}
}
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConcurrencyPolicyParameters {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_parallel: Option<u32>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExecutorPolicy {
pub retry: RetryPolicyParameters,
pub timeout: TimeoutPolicyParameters,
pub concurrency: ConcurrencyPolicyParameters,
}
impl ExecutorPolicy {
pub fn static_v0() -> Self {
Self {
retry: RetryPolicyParameters {
base_delay_ms: crate::durable::BASE_RETRY_DELAY_MS,
max_delay_ms: crate::durable::MAX_RETRY_DELAY_MS,
max_attempts: 3,
per_class: None,
},
timeout: TimeoutPolicyParameters {
default_millis: None,
max_millis: None,
per_callee: None,
},
concurrency: ConcurrencyPolicyParameters { max_parallel: None },
}
}
pub fn is_static_floor(&self) -> bool {
self == &Self::static_v0()
}
pub fn validate(&self) -> crate::error::Result<()> {
self.retry.validate()?;
self.timeout.validate()?;
if let Some(0) = self.concurrency.max_parallel {
return Err(RustyError::InvalidUpdate(
"concurrency max_parallel 0 admits no work at all — a policy that halts the \
fleet is not a learning outcome, it is an outage"
.to_owned(),
));
}
Ok(())
}
pub fn with_family_parameters(
&self,
family: DecisionFamily,
parameters: serde_json::Value,
) -> crate::error::Result<Self> {
let mut policy = self.clone();
match family {
DecisionFamily::Retry => {
policy.retry = serde_json::from_value(parameters).map_err(|e| {
RustyError::InvalidUpdate(format!(
"retry policy parameters do not match the contract: {e}"
))
})?;
policy.retry.validate().map_err(|e| {
RustyError::InvalidUpdate(format!(
"retry policy parameters fall outside the envelope: {e}"
))
})?;
}
DecisionFamily::Timeout => {
policy.timeout = serde_json::from_value(parameters).map_err(|e| {
RustyError::InvalidUpdate(format!(
"timeout policy parameters do not match the contract: {e}"
))
})?;
policy.timeout.validate().map_err(|e| {
RustyError::InvalidUpdate(format!(
"timeout policy parameters fall outside the envelope: {e}"
))
})?;
}
DecisionFamily::Concurrency => {
policy.concurrency = serde_json::from_value(parameters).map_err(|e| {
RustyError::InvalidUpdate(format!(
"concurrency policy parameters do not match the contract: {e}"
))
})?;
if let Some(0) = policy.concurrency.max_parallel {
return Err(RustyError::InvalidUpdate(
"concurrency policy parameters fall outside the envelope: \
max_parallel 0 admits no work at all"
.to_owned(),
));
}
}
other => {
return Err(RustyError::InvalidUpdate(format!(
"decision family `{other:?}` has no executor-policy parameter contract \
in this version"
)));
}
}
Ok(policy)
}
}
pub fn derive_policy_version(policy: &ExecutorPolicy) -> crate::error::Result<PolicyVersion> {
let bytes = serde_json::to_vec(policy)?;
let hash = sha256_hex(&bytes);
Ok(PolicyVersion::new(format!("policy-{}", &hash[..12])))
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct CapsuleVersion(pub String);
impl CapsuleVersion {
pub fn new(version: impl Into<String>) -> Self {
Self(version.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl std::fmt::Display for CapsuleVersion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct RunManifest {
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub prompts: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub tool_schemas: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub model: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub model_params: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub memory_schema: Option<String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub capsules: BTreeMap<String, CapsuleVersion>,
}
impl RunManifest {
pub fn new() -> Self {
Self::default()
}
pub fn pin_prompt(mut self, name: impl Into<String>, prompt: &str) -> Self {
self.prompts
.insert(name.into(), sha256_hex(prompt.as_bytes()));
self
}
pub fn pin_tool_schema(mut self, name: impl Into<String>, schema: &Value) -> Self {
self.tool_schemas
.insert(name.into(), canonical_json_digest(schema));
self
}
pub fn pin_model(mut self, model: impl Into<String>, parameters: &Value) -> Self {
self.model = Some(model.into());
self.model_params = Some(canonical_json_digest(parameters));
self
}
pub fn with_memory_schema(mut self, version: impl Into<String>) -> Self {
self.memory_schema = Some(version.into());
self
}
pub fn pin_capsule(mut self, name: impl Into<String>, version: CapsuleVersion) -> Self {
self.capsules.insert(name.into(), version);
self
}
}
pub(crate) fn canonicalize_value(value: &Value) -> Value {
match value {
Value::Object(map) => {
let mut entries: Vec<(&String, &Value)> = map.iter().collect();
entries.sort_by_key(|(key, _)| *key);
Value::Object(
entries
.into_iter()
.map(|(key, item)| (key.clone(), canonicalize_value(item)))
.collect(),
)
}
Value::Array(items) => Value::Array(items.iter().map(canonicalize_value).collect()),
scalar => scalar.clone(),
}
}
fn canonical_json_digest(value: &Value) -> String {
let bytes = serde_json::to_vec(&canonicalize_value(value))
.expect("a serde_json::Value always serializes");
sha256_hex(&bytes)
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CheckpointHeader {
pub format_version: u32,
pub graph_version: String,
pub graph_hash: String,
pub policy_version: PolicyVersion,
pub logical_clock: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub manifest: Option<RunManifest>,
}
impl Default for CheckpointHeader {
fn default() -> Self {
Self {
format_version: CURRENT_FORMAT_VERSION,
graph_version: "unversioned".to_owned(),
graph_hash: String::new(),
policy_version: PolicyVersion::default(),
logical_clock: 0,
manifest: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct JournalRef {
pub events: u64,
pub sha256: String,
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn sha256_hex_is_stable_and_lowercase() {
assert_eq!(
sha256_hex(b""),
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
);
assert_eq!(sha256_hex(b"abc").len(), 64);
}
#[test]
fn policy_version_default_is_static_floor() {
assert_eq!(PolicyVersion::default().as_str(), PolicyVersion::STATIC_V0);
assert_eq!(
serde_json::to_value(PolicyVersion::default()).unwrap(),
json!("static-v0")
);
}
#[test]
fn executor_policy_static_floor_mirrors_the_durable_constants() {
let floor = ExecutorPolicy::static_v0();
assert_eq!(
floor.retry.base_delay_ms,
crate::durable::BASE_RETRY_DELAY_MS
);
assert_eq!(floor.retry.max_delay_ms, crate::durable::MAX_RETRY_DELAY_MS);
assert_eq!(floor.retry.max_attempts, 3);
assert!(floor.timeout.default_millis.is_none());
assert!(floor.timeout.max_millis.is_none());
assert!(floor.concurrency.max_parallel.is_none());
let wire = serde_json::to_value(floor).unwrap();
assert_eq!(wire["timeout"], json!({}));
assert_eq!(wire["concurrency"], json!({}));
}
#[test]
fn derive_policy_version_is_content_addressed() {
let policy = ExecutorPolicy::static_v0()
.with_family_parameters(
DecisionFamily::Retry,
json!({"base_delay_ms": 500, "max_delay_ms": 60_000, "max_attempts": 5}),
)
.unwrap();
let first = derive_policy_version(&policy).unwrap();
let again = derive_policy_version(&policy).unwrap();
assert_eq!(first, again, "version derivation must be deterministic");
assert!(
first.as_str().starts_with("policy-"),
"derived versions carry the policy- prefix: {first}"
);
assert_eq!(first.as_str().len(), "policy-".len() + 12);
let changed = policy
.with_family_parameters(
DecisionFamily::Retry,
json!({"base_delay_ms": 500, "max_delay_ms": 60_000, "max_attempts": 6}),
)
.unwrap();
assert_ne!(first, derive_policy_version(&changed).unwrap());
}
#[test]
fn with_family_parameters_validates_and_overlays() {
let base = ExecutorPolicy::static_v0();
let with_timeout = base
.with_family_parameters(
DecisionFamily::Timeout,
json!({"default_millis": 30_000, "max_millis": 120_000}),
)
.unwrap();
assert_eq!(with_timeout.timeout.default_millis, Some(30_000));
assert_eq!(with_timeout.timeout.max_millis, Some(120_000));
assert_eq!(with_timeout.retry, base.retry);
let with_concurrency = base
.with_family_parameters(DecisionFamily::Concurrency, json!({"max_parallel": 8}))
.unwrap();
assert_eq!(with_concurrency.concurrency.max_parallel, Some(8));
let err = base
.with_family_parameters(DecisionFamily::Retry, json!({"base_delay_ms": "fast"}))
.unwrap_err();
assert!(err.to_string().contains("retry policy parameters"), "{err}");
for family in [
DecisionFamily::WorkerPlacement,
DecisionFamily::CheckpointPlacement,
] {
let err = base.with_family_parameters(family, json!({})).unwrap_err();
assert!(
err.to_string().contains("no executor-policy parameter"),
"{err}"
);
}
}
#[test]
fn payload_ref_content_hash_agrees_across_representations() {
let value = json!({"b": 1, "a": [2, 3]});
let bytes = serde_json::to_vec(&value).unwrap();
let inline = PayloadRef::inline(value);
let referenced = PayloadRef::Artifact(ArtifactRef {
sha256: sha256_hex(&bytes),
bytes: bytes.len() as u64,
});
assert_eq!(
inline.content_hash().unwrap(),
referenced.content_hash().unwrap()
);
}
#[test]
fn effect_repeatability_ladder() {
assert!(Effect::Pure.is_freely_repeatable());
assert!(Effect::ReadOnly.is_freely_repeatable());
assert!(Effect::Idempotent.is_freely_repeatable());
assert!(!Effect::Compensatable.is_freely_repeatable());
assert!(!Effect::NonIdempotent.is_freely_repeatable());
}
#[test]
fn contracts_serde_roundtrip() {
let event = RunEvent {
id: "r1:7".into(),
run_id: "r1".into(),
thread_id: "t1".into(),
node_id: Some("agent".into()),
seq: 7,
kind: RunEventKind::ModelCall,
effect: Effect::NonIdempotent,
input: Some(PayloadRef::inline(json!({"messages": []}))),
output: Some(PayloadRef::Artifact(ArtifactRef {
sha256: sha256_hex(b"response"),
bytes: 8,
})),
latency_ms: Some(42),
tokens: Some(Usage {
prompt_tokens: 10,
completion_tokens: 5,
total_tokens: 15,
}),
cost_usd: Some(0.0001),
status: EventStatus::Ok,
parent: Some("r1:3".into()),
recorded_at: DateTime::<Utc>::from_timestamp_millis(1_000).unwrap(),
};
let back: RunEvent = serde_json::from_str(&serde_json::to_string(&event).unwrap()).unwrap();
assert_eq!(event, back);
let decision = DecisionEvent {
id: "r1:d0".into(),
run_id: "r1".into(),
thread_id: "t1".into(),
seq: 0,
family: DecisionFamily::Retry,
features: Map::from_iter([("failure_class".to_owned(), json!("timeout"))]),
legal_actions: vec![DecisionAction::Retry { attempt: 1 }, DecisionAction::Abort],
selected: DecisionAction::Retry { attempt: 1 },
propensity: 0.75,
policy_version: PolicyVersion::default(),
role: None,
outcome: None,
decided_at: DateTime::<Utc>::from_timestamp_millis(1_000).unwrap(),
};
let back: DecisionEvent =
serde_json::from_str(&serde_json::to_string(&decision).unwrap()).unwrap();
assert_eq!(decision, back);
}
#[test]
fn checkpoint_header_default_matches_pre_r05_fallback() {
let header = CheckpointHeader::default();
assert_eq!(header.format_version, CURRENT_FORMAT_VERSION);
assert_eq!(header.graph_version, "unversioned");
assert_eq!(header.policy_version, PolicyVersion::default());
assert_eq!(header.logical_clock, 0);
assert_eq!(header.manifest, None);
}
#[test]
fn manifest_digests_are_stable_content_addresses() {
let manifest = RunManifest::new()
.pin_prompt("system", "You are a careful research agent.")
.pin_tool_schema(
"search",
&json!({"type": "object", "properties": {"query": {"type": "string"}}}),
)
.pin_model(
"gpt-5.2-2026-06-01",
&json!({"temperature": 0, "seed": 42, "max_tokens": 512}),
)
.with_memory_schema("memory-v1")
.pin_capsule("researcher", CapsuleVersion::new("1.4.0"));
assert_eq!(
manifest.prompts["system"],
"edff20fbc61c032a9206bdc94aec3b70e05ab953383972b267b83957d9ba7bfe"
);
assert_eq!(
manifest.tool_schemas["search"],
"094ec29d007cce150c65abf0756d79ad5b62a1acfdb6e0841f69f1377ef41761"
);
assert_eq!(
manifest.model_params.as_deref(),
Some("fc004364a674799b07f8e4e6323ad74398745607ae3bd955e0d9c1d7529a0762")
);
assert_eq!(manifest.model.as_deref(), Some("gpt-5.2-2026-06-01"));
assert_eq!(manifest.memory_schema.as_deref(), Some("memory-v1"));
assert_eq!(manifest.capsules["researcher"].as_str(), "1.4.0");
let reordered = RunManifest::new().pin_tool_schema(
"search",
&json!({"properties": {"query": {"type": "string"}}, "type": "object"}),
);
assert_eq!(manifest.tool_schemas, reordered.tool_schemas);
}
#[test]
fn manifest_serde_roundtrip_and_sparse_wire_shape() {
let manifest = RunManifest::new()
.pin_prompt("system", "Be brief.")
.pin_model("model-x", &json!({"temperature": 0.5}));
let back: RunManifest =
serde_json::from_str(&serde_json::to_string(&manifest).unwrap()).unwrap();
assert_eq!(manifest, back);
let value = serde_json::to_value(&manifest).unwrap();
assert!(value.get("tool_schemas").is_none());
assert!(value.get("memory_schema").is_none());
assert!(value.get("capsules").is_none());
assert!(value.get("prompts").is_some());
assert_eq!(serde_json::to_value(RunManifest::new()).unwrap(), json!({}));
let header = CheckpointHeader::default();
assert!(serde_json::to_value(&header)
.unwrap()
.get("manifest")
.is_none());
}
#[test]
fn r05_header_without_manifest_still_loads() {
let r05_shape = json!({
"format_version": 1,
"graph_version": "react-v3",
"graph_hash": "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae",
"policy_version": "static-v0",
"logical_clock": 1750000000000u64,
});
let header: CheckpointHeader = serde_json::from_value(r05_shape).unwrap();
assert_eq!(header.manifest, None);
assert_eq!(header.format_version, CURRENT_FORMAT_VERSION);
let extended = CheckpointHeader {
manifest: Some(RunManifest::new().with_memory_schema("memory-v1")),
..header
};
let back: CheckpointHeader =
serde_json::from_str(&serde_json::to_string(&extended).unwrap()).unwrap();
assert_eq!(extended, back);
}
#[test]
fn effect_receipt_effect_id_is_additive() {
let receipt = EffectReceipt {
provider: "stripe".into(),
provider_id: "ch_3PKd".into(),
idempotency_key: "run-1:charge:7".into(),
task_id: None,
effect_id: None,
};
let value = serde_json::to_value(&receipt).unwrap();
assert!(value.get("effect_id").is_none());
let with_id = EffectReceipt {
effect_id: Some(
"9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673ca7".into(),
),
..receipt
};
let back: EffectReceipt =
serde_json::from_str(&serde_json::to_string(&with_id).unwrap()).unwrap();
assert_eq!(with_id, back);
}
}