Skip to main content

rusty_agent_runtime/
record.rs

1//! Flight Recorder contracts: the canonical, serde-versioned evidence schema.
2//!
3//! This module freezes the wire shapes that every later wave of the Flight
4//! Recorder (replay engine, server API, Studio UI, executor learning) builds
5//! on. Nothing here performs I/O or execution — these are pure data
6//! contracts plus the small hashing helpers they need.
7//!
8//! The four pillars:
9//!
10//! - [`Effect`] — the effect taxonomy. Every journaled event declares which
11//!   class of side effect produced it; the class is what later lets the
12//!   runtime decide whether an effect may be retried, served from a journal
13//!   during exact replay, or must be re-executed.
14//! - [`RunEvent`] — one recorded fact about a run (a super-step boundary, a
15//!   node input/output, a model/tool/remote/WASM call, an interrupt, a
16//!   routing decision, a checkpoint write), with causal parentage.
17//! - [`DecisionEvent`] — one policy decision with the context needed for
18//!   offline learning: features, the closed legal-action set, the selected
19//!   action, its propensity, and the policy version that made the choice.
20//!   Executor learning lands in R0.8+; the contract freezes now so R0.5
21//!   journals are already learnable evidence.
22//! - [`CheckpointHeader`] — format version, graph version/hash, active
23//!   policy version, and logical clock, carried by every checkpoint so old
24//!   snapshots can be interpreted and replayed faithfully.
25//!
26//! Golden-file tests under `tests/golden/` pin these serialized shapes;
27//! any accidental contract drift fails CI.
28
29use std::collections::BTreeMap;
30
31use chrono::{DateTime, Utc};
32use serde::{Deserialize, Serialize};
33use serde_json::{Map, Value};
34use sha2::{Digest, Sha256};
35
36use crate::error::RustyError;
37use crate::llm::Usage;
38
39/// The current on-disk format version of [`CheckpointHeader`].
40///
41/// Bump only on a breaking change to the checkpoint envelope; additive
42/// evolution uses serde defaults instead so previously written checkpoints
43/// keep deserializing.
44pub const CURRENT_FORMAT_VERSION: u32 = 1;
45
46/// Payloads at or below this many serialized bytes travel inline in a
47/// [`RunEvent`]; larger ones are content-addressed as [`ArtifactRef`]s.
48///
49/// The journal keeps the artifact bytes itself (in-memory impl), so a
50/// journal snapshot is always self-contained — the reference is a size and
51/// dedup optimization, not a pointer to external storage.
52pub const INLINE_PAYLOAD_MAX_BYTES: usize = 4096;
53
54/// Lowercase hex SHA-256 digest of `bytes`. The one hashing primitive shared
55/// by artifact references, journal heads, and graph topology hashes.
56pub fn sha256_hex(bytes: &[u8]) -> String {
57    let mut hasher = Sha256::new();
58    hasher.update(bytes);
59    let digest = hasher.finalize();
60    let mut out = String::with_capacity(digest.len() * 2);
61    for byte in digest {
62        use std::fmt::Write as _;
63        let _ = write!(out, "{byte:02x}");
64    }
65    out
66}
67
68/// The effect taxonomy: what a journaled event did to the world outside the
69/// run's own state.
70///
71/// The classification is declared by the producer (node/model/tool traits
72/// carry a default with an override point) and recorded on every
73/// [`RunEvent`]. It is the input to three later policies:
74///
75/// - **Retry** (R0.6): which failed effects may be re-attempted at all, and
76///   under what key.
77/// - **Replay** (R0.5 later waves): which effects exact replay may serve
78///   from the journal versus must re-execute.
79/// - **Capsules** (R0.9): which effects a sandboxed capsule may perform at
80///   all under its capability grants.
81///
82/// The order of variants is a severity ladder: each class permits strictly
83/// less automation freedom than the one before. The `Ord` derive is that
84/// ladder made mechanical (declaration order), which is what capsule
85/// manifests (R0.9) compare declared effects against grant-implied minima
86/// with.
87#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
88#[serde(rename_all = "snake_case")]
89pub enum Effect {
90    /// No observable effect beyond its return value: a deterministic function
91    /// of its inputs. Re-execution is always safe and always equivalent, so
92    /// replay may either re-run it or reuse the journaled output, and retries
93    /// are unconstrained. Default for plain compute nodes.
94    Pure,
95
96    /// Reads external state but writes nothing (a GET, a file read, a
97    /// lookup). Re-execution is safe but **not** necessarily equivalent — the
98    /// world may have changed — so exact replay serves the journaled output
99    /// while live replay re-reads. Retries are unconstrained.
100    ReadOnly,
101
102    /// Writes external state, but repeating the same call with the same
103    /// idempotency key has the same effect as calling once (PUT semantics,
104    /// upserts). Safe to retry under a stable key; exact replay may serve
105    /// the journaled receipt instead of re-sending.
106    Idempotent,
107
108    /// Writes external state and repeating it duplicates the effect, but a
109    /// declared compensating action can logically undo it (charge/refund).
110    /// Retry only with care; replay and rollback policy must pair the effect
111    /// with its compensation. v1 records the classification only —
112    /// compensation registration arrives with durable work (R0.6).
113    Compensatable,
114
115    /// Writes external state with no safe automatic repetition (send an
116    /// email, charge a card, POST without a key). Never silently retried,
117    /// never served from a journal in any replay mode that claims fidelity —
118    /// re-execution is an explicit, caller-approved decision. Default for
119    /// model and tool calls, which the runtime cannot prove otherwise.
120    NonIdempotent,
121}
122
123impl Effect {
124    /// Whether re-executing this effect during replay or retry is
125    /// unconditionally safe (no duplication risk). `Compensatable` and
126    /// `NonIdempotent` are the only classes requiring human or policy
127    /// approval before re-execution.
128    pub fn is_freely_repeatable(self) -> bool {
129        matches!(self, Effect::Pure | Effect::ReadOnly | Effect::Idempotent)
130    }
131}
132
133/// A versioned identity for the executor policy that was active during a
134/// run or made a [`DecisionEvent`].
135///
136/// Newtype over `String` so the type system — not convention — keeps policy
137/// versions distinct from graph versions, model names, and other strings.
138/// The default is the static, no-learning floor: every run before the
139/// policy plane lands (R0.8) records this version.
140#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
141#[serde(transparent)]
142pub struct PolicyVersion(pub String);
143
144impl PolicyVersion {
145    /// The static default policy: no learned behavior, fixed executor
146    /// constants. This is the floor that learned policies (R0.10) are
147    /// evaluated against and the version every pre-learning run records.
148    pub const STATIC_V0: &'static str = "static-v0";
149
150    /// Wrap a version string.
151    pub fn new(version: impl Into<String>) -> Self {
152        Self(version.into())
153    }
154
155    /// The version string.
156    pub fn as_str(&self) -> &str {
157        &self.0
158    }
159}
160
161impl Default for PolicyVersion {
162    fn default() -> Self {
163        Self(Self::STATIC_V0.to_owned())
164    }
165}
166
167impl std::fmt::Display for PolicyVersion {
168    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
169        f.write_str(&self.0)
170    }
171}
172
173/// A content-addressed reference to a payload too large to travel inline in
174/// an event (see [`INLINE_PAYLOAD_MAX_BYTES`]).
175///
176/// The hash is the identity: two events referencing the same `sha256`
177/// reference the same bytes. Consumers resolve references through the
178/// journal snapshot's artifact map; nothing here points outside the
179/// snapshot.
180#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
181pub struct ArtifactRef {
182    /// Lowercase hex SHA-256 of the canonical JSON serialization of the
183    /// payload.
184    pub sha256: String,
185
186    /// Serialized size of the payload in bytes.
187    pub bytes: u64,
188}
189
190/// How an event's input or output payload is carried.
191///
192/// Small values are embedded ([`PayloadRef::Inline`]); large values are
193/// content-addressed ([`PayloadRef::Artifact`]) with their bytes held in the
194/// journal's artifact map. The split keeps events cheap to scan (sequences,
195/// causal links, statuses) without forcing payloads out of the snapshot.
196///
197/// Serialized with adjacent tagging (`{"kind": "inline", "value": …}`):
198/// payloads are arbitrary JSON, so the tag must not be flattened into the
199/// payload the way internal tagging would require.
200#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
201#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
202pub enum PayloadRef {
203    /// The payload itself, embedded in the event.
204    Inline(Value),
205
206    /// A content hash of the payload; bytes live in the journal snapshot's
207    /// artifact map under the same hash.
208    Artifact(ArtifactRef),
209}
210
211impl PayloadRef {
212    /// Always-inline reference (test convenience and small-value paths).
213    pub fn inline(value: Value) -> Self {
214        PayloadRef::Inline(value)
215    }
216
217    /// The content hash of the payload, whether inline or referenced.
218    ///
219    /// Hashing is over the canonical `serde_json` serialization (object keys
220    /// sort deterministically — see `canonicalize_value`), so equal
221    /// payloads hash equal regardless of which representation carried them.
222    pub fn content_hash(&self) -> Result<String, serde_json::Error> {
223        match self {
224            PayloadRef::Inline(value) => {
225                let bytes = serde_json::to_vec(&canonicalize_value(value))?;
226                Ok(sha256_hex(&bytes))
227            }
228            PayloadRef::Artifact(reference) => Ok(reference.sha256.clone()),
229        }
230    }
231}
232
233/// The effect's own confirmation of an `Idempotent` side effect, journaled
234/// as the output payload of a [`RunEventKind::EffectReceipt`] event (R0.6
235/// Durable Work).
236///
237/// A receipt is the proof the *provider* accepted the effect exactly once:
238/// its own confirmation id, under the idempotency key the caller supplied.
239/// Two consumers depend on it:
240///
241/// - **Operators** auditing a run can trace every effect to the provider's
242///   record of it (`provider` + `provider_id`).
243/// - **Exact replay** serves the journaled receipt instead of re-sending the
244///   effect — the same rule the Flight Recorder applies to journaled model
245///   and tool calls, extended across the crash boundary between a run and
246///   its queue-dispatched tasks. The replay lookup is keyed on
247///   [`EffectReceipt::idempotency_key`] (see
248///   [`crate::journal::JournalSnapshot::find_effect_receipt`]), not on event
249///   sequence: a task completes outside the run's super-step order.
250///
251/// Serialized inside the event's output [`PayloadRef`], so the event
252/// envelope stays unchanged and old journals keep deserializing.
253#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
254pub struct EffectReceipt {
255    /// The system that confirmed the effect (a provider name — `stripe`,
256    /// `sendgrid` — or any store with idempotent-put semantics).
257    pub provider: String,
258
259    /// The provider's own confirmation id (charge id, message id, version
260    /// stamp) — the handle an audit uses to find the effect at the provider.
261    pub provider_id: String,
262
263    /// The idempotency key the effect was performed under — the key the task
264    /// envelope carried and the recipient passed to the provider. This is
265    /// the replay lookup key: a re-driven run asks "did this key already
266    /// land?" and the journal answers with this receipt.
267    pub idempotency_key: String,
268
269    /// The durable task whose completion produced this receipt, when the
270    /// effect was queue-dispatched. `None` for effects a run performed
271    /// in-process.
272    #[serde(default, skip_serializing_if = "Option::is_none")]
273    pub task_id: Option<String>,
274
275    /// The deterministic effect id (R0.7 effect kernel) of the effect this
276    /// receipt confirms — [`crate::effects::derive_effect_id`] over the
277    /// run scope, effect kind, input hash, and idempotency key. Recovery
278    /// re-derives the id of the effect it is about to perform and looks the
279    /// receipt up by it (see
280    /// [`crate::journal::JournalSnapshot::find_effect_receipt_by_effect_id`]),
281    /// which is how "did this exact effect already commit?" becomes
282    /// answerable without re-execution.
283    ///
284    /// Additive like `task_id`: absent (not null) on the wire when unset, so
285    /// pre-R0.7 receipts and consumers see no shape change. `None` is honest
286    /// for receipts journaled by writers that predate the typed kernel; the
287    /// [`EffectReceipt::idempotency_key`] lookup keeps serving them.
288    #[serde(default, skip_serializing_if = "Option::is_none")]
289    pub effect_id: Option<String>,
290}
291
292/// The outcome status of a journaled event.
293#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
294#[serde(rename_all = "snake_case")]
295pub enum EventStatus {
296    /// Completed normally.
297    Ok,
298    /// Failed. The error description travels in the event's output payload.
299    Error,
300    /// Suspended the run (a node called `interrupt()`). Control flow, not a
301    /// failure — the payload is the interrupt value.
302    Interrupted,
303}
304
305/// What a [`RunEvent`] records. Closed set; replay and analysis code matches
306/// exhaustively on it.
307#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
308#[serde(rename_all = "snake_case")]
309pub enum RunEventKind {
310    /// A super-step began; input lists the activated node set.
311    SuperStepStart,
312    /// A super-step merged at the barrier; output carries the post-reducer
313    /// channel values (the reducer result for the step).
314    SuperStepEnd,
315    /// A node invocation was scheduled; input is its (scoped) state snapshot.
316    NodeInput,
317    /// A node invocation finished; output is its partial updates plus any
318    /// routing command, with the measured latency.
319    NodeOutput,
320    /// A chat-model call; input is the request (messages + tool schemas),
321    /// output the response, with model identity, token usage, and cost where
322    /// reported.
323    ModelCall,
324    /// A tool invocation; input is the arguments, output the result.
325    ToolCall,
326    /// A remote-node call to a worker over the wire protocol; input is the
327    /// `NodeTask`, output the `NodeTaskResponse` payload.
328    RemoteCall,
329    /// A WASM guest-module invocation; input is the guest input, output the
330    /// guest output.
331    WasmCall,
332    /// A node suspended the run; input is the interrupt payload.
333    Interrupt,
334    /// The run resumed from a checkpoint; input carries the checkpoint id
335    /// and, when present, the resume value.
336    Resume,
337    /// The routing phase selected the next active set; output describes the
338    /// planned invocations (including `Send` fan-outs).
339    RoutingDecision,
340    /// A checkpoint was persisted; output carries the checkpoint id, step,
341    /// and journal head reference stamped into it.
342    CheckpointWritten,
343    /// An `Idempotent` effect's own confirmation, journaled by the effect's
344    /// recipient (R0.6 Durable Work): output carries the [`EffectReceipt`] —
345    /// the provider's confirmation id plus the idempotency key the effect
346    /// ran under. Exact replay serves the receipt instead of re-sending the
347    /// effect: the same journaled-output rule model and tool calls follow,
348    /// extended across the crash boundary between a run and its durable
349    /// tasks.
350    EffectReceipt,
351
352    /// An agent was spawned (R0.7 Agent Fabric): input carries the agent id,
353    /// its pinned [`crate::agents::CapabilityManifest`], and the declared
354    /// [`crate::agents::StateScope`]s — the manifest's scopes are journaled
355    /// with the spawn so later access checks replay against the same
356    /// declaration. Wave 1 lands the variant as an inert contract; the agent
357    /// host emits it.
358    AgentSpawn,
359
360    /// An agent terminated (R0.7): output carries the terminal disposition
361    /// (completed, failed, cancelled) and the final checkpoint reference.
362    /// Wired in wave 2 for the cancellation tree: the server journals it
363    /// into the agent's supervision journal when an agent/team cancel
364    /// actually touches work. Host-emitted terminal exits land with the
365    /// agent host.
366    AgentExit,
367
368    /// A mailbox message was submitted to an agent's mailbox (R0.7): output
369    /// carries the recipient (`agent:{agent_id}`), the message kind, and the
370    /// task id the queue assigned. The sender-side half of the mailbox
371    /// journal pair; the envelope's `parent` links it into the team's causal
372    /// tree. Wired in wave 3: the coordination runtime journals it into the
373    /// pattern's journal for every member task it submits. Host-emitted
374    /// sends land with the agent host.
375    MailboxSend,
376
377    /// An agent's activation began a turn on a mailbox message (R0.7): input
378    /// carries the task id and idempotency key the turn is processing.
379    /// The recipient-side half of the mailbox pair. Wired in wave 3 as the
380    /// settlement observation: the coordination runtime journals it when a
381    /// member task settles, with the terminal status and result — the
382    /// pattern's evidence half of the pair. Host-emitted turn begins land
383    /// with the agent host.
384    MailboxReceive,
385
386    /// A supervision decision was made (R0.7 wave 2): output carries the
387    /// policy (`permanent` / `transient` / `temporary`), the triggering
388    /// failure's [`EventStatus`] / error class, and the restart ordinal —
389    /// the journaled decision record that makes "no restart without a
390    /// journaled decision" auditable. Wired in wave 2: the server journals
391    /// it into the agent's supervision journal on restart / escalate /
392    /// manual-restart decisions.
393    SupervisionEvent,
394
395    /// A coordination pattern (delegate / fan-out / race / quorum) began
396    /// (R0.7 wave 3): output carries the pattern's typed contract — members,
397    /// thresholds, effect declarations. The team's causal root for every
398    /// event the pattern spawns. Wired in wave 3: the coordination runtime
399    /// journals it on the pattern's first drive, before any member task
400    /// exists.
401    CoordinationStart,
402
403    /// A coordination pattern settled (R0.7 wave 3): output carries the
404    /// result reference and the per-member dispositions (completed, failed,
405    /// cancelled) — the fan-in evidence record. Wired in wave 3: the
406    /// coordination runtime journals it exactly once, as the pattern's
407    /// terminal fact.
408    CoordinationEnd,
409
410    /// A governed memory retrieval was performed (R0.8 Rusty Learn, wave 1):
411    /// input is the canonical request — the resolved
412    /// [`crate::memory::MemoryQuery`] (with `as_of` stamped through the
413    /// run's clock) plus the [`crate::memory::ContextBudget`] — and output
414    /// is the journaled [`crate::memory::MemoryAssembly`]: the record ids
415    /// and their order, the packed records, and the token accounting.
416    /// Declared [`Effect::ReadOnly`]: exact replay serves the journaled
417    /// assembly instead of re-querying the store — the same
418    /// journaled-output rule model and tool calls follow, applied to the
419    /// memory seam so candidate evaluation is reproducible.
420    MemoryRead,
421
422    /// A governed memory write landed (R0.8 wave 1): an
423    /// [`Effect::Idempotent`] effect under the derived key
424    /// `memory:{scope}:{memory_id}` (see [`crate::memory::memory_effect_key`]),
425    /// so retried submissions converge. Input carries the effect key and the
426    /// memory id; output carries the stored
427    /// [`crate::memory::MemoryRecord`] with its provenance — the write's
428    /// attribution is journaled, not implied.
429    MemoryWrite,
430
431    /// A memory record was forgotten (R0.8 wave 2): real deletion of
432    /// derived state, with the journaled tombstone as the erasure receipt.
433    /// An [`Effect::Idempotent`] effect under the derived key
434    /// `memory_forget:{scope}:{memory_id}` (see
435    /// [`crate::memory::memory_forget_effect_key`]), so retried erasures
436    /// converge. Input carries the effect key and the memory id; output
437    /// carries the [`crate::memory::MemoryForgetTombstone`] — the id, scope,
438    /// reason, and dependent invalidations, metadata by construction:
439    /// the tombstone has no content field, so the forgotten bytes cannot
440    /// leak through the receipt of their erasure. Corrections are not a
441    /// separate variant: they journal through `MemoryWrite` with the
442    /// correction's attribution in the derived record's provenance.
443    MemoryForget,
444
445    /// A learning candidate was created (R0.8 wave 3): a distiller's
446    /// proposed change landed as an immutable, content-addressed
447    /// [`crate::learn::Candidate`] — identity is integrity, so two
448    /// distillations of the same change converge on one id and a tampered
449    /// candidate fails its own address. An [`Effect::Idempotent`] effect
450    /// under the derived key `candidate:{candidate_id}` (see
451    /// [`crate::learn::candidate_effect_key`]), so retried submissions
452    /// converge. Input carries the effect key and the candidate id; output
453    /// carries the candidate itself — the distiller's identity and the
454    /// evidence span it read are journaled with it, not implied.
455    CandidateCreated,
456
457    /// A candidate was evaluated against recorded evidence (R0.8 wave 3):
458    /// replay re-drove recorded runs with the candidate applied, the
459    /// experiment runner graded it over the versioned dataset, and the
460    /// comparison diffed it against the baseline. An
461    /// [`Effect::Idempotent`] effect under the derived key
462    /// `evaluation:{candidate_id}:{dataset_version}` (see
463    /// [`crate::learn::evaluation_effect_key`]): re-evaluation against the
464    /// same dataset version converges; a new dataset version is a new
465    /// evaluation. Output carries the journaled
466    /// [`crate::learn::CandidateEvaluation`] — the replay divergence
467    /// summary, the report pair, the dataset version, and the verdict.
468    /// The evaluation is evidence, not a log line.
469    CandidateEvaluated,
470
471    /// A candidate was promoted (R0.8 wave 3): the active-version pointer
472    /// for its production surface moved. An [`Effect::Idempotent`] effect
473    /// under the derived key `promotion:{candidate_id}` (see
474    /// [`crate::learn::promotion_effect_key`]) — retried promotions
475    /// converge, and recovery re-derives the same key. Output carries the
476    /// [`crate::learn::PromotionReceipt`]: the pointer's previous value
477    /// and the promotion's authority — the envelope version (the standing
478    /// approval) or the approval token's `approved_by` for an
479    /// out-of-envelope promotion.
480    CandidatePromoted,
481
482    /// A promoted candidate was rolled back (R0.8 wave 3): the surface's
483    /// active-version pointer re-pointed to the previous candidate.
484    /// Byte-exact because candidates are content-addressed and immutable —
485    /// the restored version is the one that previously served, not a
486    /// reconstruction. An [`Effect::Idempotent`] effect under the derived
487    /// key `rollback:{surface}:{candidate_id}` (see
488    /// [`crate::learn::rollback_effect_key`]). Output carries the
489    /// [`crate::learn::RollbackReceipt`]: from, to, and the causing
490    /// evidence. New runs bind the re-pointed version at admission;
491    /// in-flight runs keep the version their checkpoint header pins.
492    CandidateRolledBack,
493
494    /// An executor policy decision was made and recorded (R0.8 wave 4): the
495    /// policy plane emitted a [`DecisionEvent`] at a decision point — v1
496    /// wires the retry classifier (`crate::durable::classify_retry`). An
497    /// [`Effect::Pure`] record: the decision was already applied by the
498    /// scheduler that emitted it; this event is the *evidence* of why, not a
499    /// command to apply it again. Output carries the journaled
500    /// [`DecisionEvent`] — features, the closed legal-action set, the
501    /// selected action, the propensity, and the policy version that decided.
502    PolicyDecision,
503
504    /// A run manifest's capsule version pin was resolved to a content
505    /// address (R0.9 Rusty Capsules, wave 1): the server's capsule registry
506    /// mapped `(identity, version)` →
507    /// [`crate::capsule::CapsuleId`] at admission and journaled the
508    /// resolution, so the full chain — header pin → journaled resolution →
509    /// receipt — reaches the manifest digest. An [`Effect::ReadOnly`]
510    /// record (a registry lookup): output carries the journaled
511    /// [`crate::capsule::CapsuleResolution`] — the pin name, the version
512    /// string, the resolved capsule id, and the build digest the registry
513    /// holds for it. A pin that resolves to a manifest failing its own
514    /// content address fails admission instead — tampering is an admission
515    /// error, never a journaled resolution.
516    CapsuleResolved,
517
518    /// A granted capsule capability was exercised (R0.9 wave 1): the guest
519    /// called a linked import and the host performed (or attempted) the
520    /// operation. The capsule rule's "every use is journaled" half: output
521    /// carries the journaled [`crate::capsule::CapsuleUse`] — the capsule
522    /// id, the capability kind, the operation, and the request/response
523    /// summaries. The effect class is the operation's own (a `GET` fetch
524    /// records [`Effect::ReadOnly`]; a writing method records
525    /// [`Effect::NonIdempotent`]), and a failed operation is journaled with
526    /// [`EventStatus::Error`] — a granted call that fails is still a use.
527    CapsuleCall,
528
529    /// A capsule capability attempt was refused (R0.9 wave 1): either the
530    /// guest probed an import its manifest's grants never linked (the
531    /// structural denial — the import does not exist), or it called a
532    /// granted import outside the grant's scope (a `network` grant naming
533    /// host A, a fetch attempted against host B). An [`Effect::Pure`]
534    /// record: nothing executed, so there is no external effect to
535    /// classify — the event is the evidence that nothing happened. Output
536    /// carries the journaled [`crate::capsule::CapsuleDenial`] — the
537    /// capsule id, the requested capability, and **the manifest grant that
538    /// was absent** (the grant that would have permitted the attempt), so
539    /// the denial is attributable to a declaration, not to a stack trace.
540    CapsuleDenied,
541
542    /// The deployment's receipt signing key changed (R0.9 wave 3): a
543    /// rotation was performed (or a host with no local secret joined a
544    /// shared store) and the server journaled the new key id into the
545    /// deployment's receipts journal — the run id
546    /// `receipt-keys`, not any tenant's run. An [`Effect::Pure`] record:
547    /// the key operation is local key material, so there is no external
548    /// effect to classify — the event is the lineage evidence. Output
549    /// carries the journaled [`crate::receipt::SigningKeyRotation`] — the
550    /// previous key id (`None` on genesis), the new key id, its public
551    /// half, and the rotation instant — so "which key signed what, from
552    /// when" is a chained fact, and old receipts keep verifying against
553    /// the key history the journal attests.
554    SigningKeyRotated,
555}
556
557/// One recorded fact about a run: the Flight Recorder's atomic evidence.
558///
559/// Events form a causal chain via `parent` (the event that caused this one —
560/// e.g. a node input's parent is its super-step start), and a total order
561/// via `seq`, a monotonic sequence number assigned by the journal at record
562/// time. `seq` — not wall time — is the ordering guarantee: recorded runs
563/// re-driven against a seeded clock reproduce the same sequence.
564///
565/// Event ids are `{run_id}:{seq}` — deterministic for a given journal, so a
566/// re-driven run with the same seed mints the same ids.
567#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
568pub struct RunEvent {
569    /// Deterministic event id (`{run_id}:{seq}`).
570    pub id: String,
571
572    /// The run this event belongs to. One `Executor::run` call = one run id.
573    pub run_id: String,
574
575    /// The thread (session) the run belongs to.
576    pub thread_id: String,
577
578    /// The node this event is about, where applicable (`None` for run-wide
579    /// events such as super-step boundaries and checkpoint writes).
580    pub node_id: Option<String>,
581
582    /// Monotonic sequence number within the journal, assigned at record
583    /// time. The total order of the run's evidence.
584    pub seq: u64,
585
586    /// What happened.
587    pub kind: RunEventKind,
588
589    /// The declared effect classification of whatever produced this event.
590    pub effect: Effect,
591
592    /// Input payload (arguments, request, snapshot), inline or referenced.
593    pub input: Option<PayloadRef>,
594
595    /// Output payload (result, response, updates), inline or referenced.
596    pub output: Option<PayloadRef>,
597
598    /// Wall/logical latency of the recorded operation in milliseconds, when
599    /// measured. Sourced from the run's clock, so a logical clock yields
600    /// reproducible values.
601    pub latency_ms: Option<u64>,
602
603    /// Token usage for model calls, when the provider reported it.
604    pub tokens: Option<Usage>,
605
606    /// Monetary cost in USD for the recorded operation, when known. `f64`
607    /// micro-costs are fine here: this is evidence, not accounting — the
608    /// ledger aggregates elsewhere.
609    pub cost_usd: Option<f64>,
610
611    /// How the event ended.
612    pub status: EventStatus,
613
614    /// The id of the event that caused this one, when there is one. A node
615    /// input's parent is its super-step start; a tool call's parent is the
616    /// node that invoked it; a checkpoint write's parent is the routing
617    /// decision that ended the step.
618    pub parent: Option<String>,
619
620    /// When the event was recorded, read from the run's clock (system wall
621    /// clock by default; the configured logical clock for seeded runs).
622    pub recorded_at: DateTime<Utc>,
623}
624
625/// The family a [`DecisionEvent`] belongs to: the closed set of executor
626/// decisions a policy may learn.
627///
628/// The set mirrors the R0.10 priority order. Deliberately absent: model and
629/// agent selection (a governed semantic policy, not an automatic one) and
630/// interrupt policy (the prevented-error counterfactual is unobservable).
631#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
632#[serde(rename_all = "snake_case")]
633pub enum DecisionFamily {
634    /// Whether to re-attempt a failed effect, and with what backoff.
635    Retry,
636    /// What timeout/stopping bound to apply to an operation.
637    Timeout,
638    /// Which equivalent worker a remote execution is placed on.
639    WorkerPlacement,
640    /// Concurrency/backpressure limits for parallel execution.
641    Concurrency,
642    /// Whether a checkpoint is written at a given boundary (headroom gated
643    /// on the R0.5 experiment: mandatory after non-idempotent effects).
644    CheckpointPlacement,
645}
646
647/// One action in a [`DecisionEvent`]'s legal set. Closed enum: learned
648/// policies choose among declared actions, never free-form outputs — that is
649/// what keeps the learning problem mechanical (dense signals, closed spaces)
650/// instead of semantic.
651#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
652#[serde(tag = "action", rename_all = "snake_case")]
653pub enum DecisionAction {
654    /// Re-attempt the failed operation; `attempt` is the 1-based retry
655    /// ordinal.
656    Retry {
657        /// The 1-based retry ordinal being taken.
658        attempt: u32,
659    },
660    /// Give up on the operation and fail the run/step.
661    Abort,
662    /// Apply a timeout of `millis` to the operation.
663    SetTimeout {
664        /// The timeout bound in milliseconds.
665        millis: u64,
666    },
667    /// Place a remote execution on worker `worker`.
668    SelectWorker {
669        /// The chosen worker's identity.
670        worker: String,
671    },
672    /// Cap concurrent executions at `limit`.
673    SetConcurrency {
674        /// The maximum number of concurrent executions.
675        limit: u32,
676    },
677    /// Persist a checkpoint at this boundary.
678    WriteCheckpoint,
679    /// Skip the checkpoint at this boundary.
680    SkipCheckpoint,
681}
682
683/// How a decided action turned out, filled in when the affected operation
684/// completes. `None` on the wire until then — decisions and outcomes are
685/// recorded separately so in-flight decisions are visible.
686#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
687#[serde(rename_all = "snake_case")]
688pub enum DecisionOutcome {
689    /// The selected action led to completion.
690    Success,
691    /// The selected action did not lead to completion.
692    Failure,
693    /// The run was cancelled or superseded before the outcome materialized.
694    Cancelled,
695}
696
697/// The role a [`DecisionEvent`] played in its run (R0.10 wave 2, the runtime
698/// digital twin).
699///
700/// Additive to the R0.8 contract: absent from the wire when `None`, so every
701/// pre-twin decision — all of which were made by the policy whose action
702/// executed — keeps its exact shape. The twin is the first emitter that
703/// records *two* decisions at one decision point (the shadow pair), which is
704/// what makes the marker necessary: without it, off-policy evaluation cannot
705/// tell the decision that bound the world from the one that merely scored
706/// the same features.
707#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
708#[serde(rename_all = "snake_case")]
709pub enum DecisionRole {
710    /// The decision whose selected action executed (the floor's, in a twin
711    /// shadow run).
712    Acting,
713    /// A candidate policy's decision over the same features, journaled for
714    /// off-policy evidence but never executed. Well-posed evidence requires
715    /// the shadow's true propensity; a shadow exploring by seeded draw is a
716    /// stochastic policy with known propensities by construction.
717    Shadow,
718}
719
720/// One executor policy decision with everything offline learning needs to
721/// evaluate it.
722///
723/// The learning contract (R0.8+): given `features` and `legal_actions`, the
724/// policy named by `policy_version` chose `selected` with probability
725/// `propensity`. Propensity is assigned **at decision time**, never
726/// reconstructed — without it, off-policy evaluation (comparing a candidate
727/// policy against the recorded one) is impossible. `outcome` is `None`
728/// until the affected operation completes.
729///
730/// v1 froze this contract without emitters; R0.8 wave 4 wires the first
731/// emission point (the retry classifier, see
732/// [`crate::durable::retry_decision_event`]), journaled as
733/// [`RunEventKind::PolicyDecision`].
734#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
735pub struct DecisionEvent {
736    /// Deterministic decision id (`{run_id}:d{n}` — a separate sequence from
737    /// [`RunEvent`], so decision ids stay stable if event kinds are added).
738    pub id: String,
739
740    /// The run the decision was made in.
741    pub run_id: String,
742
743    /// The thread (session) the run belongs to.
744    pub thread_id: String,
745
746    /// Sequence number within the decision stream of this run.
747    pub seq: u64,
748
749    /// Which executor decision this is.
750    pub family: DecisionFamily,
751
752    /// The observation the policy decided from (latency percentiles, failure
753    /// class, queue depth, ...). Free-form JSON: the feature schema evolves
754    /// with the policy, but the envelope does not.
755    pub features: Map<String, Value>,
756
757    /// Every action that was legal at decision time. Off-policy evaluation
758    /// needs the full set, not just the chosen one.
759    pub legal_actions: Vec<DecisionAction>,
760
761    /// The action the policy took. Must be a member of `legal_actions`
762    /// (enforced by the policy plane, not by this type).
763    pub selected: DecisionAction,
764
765    /// The probability the active policy assigned to `selected` at decision
766    /// time, in `(0, 1]`. First-class because learning correctness depends
767    /// on it: importance weighting divides by the propensity.
768    pub propensity: f64,
769
770    /// The policy that made the decision.
771    pub policy_version: PolicyVersion,
772
773    /// Whether this decision's action executed or only scored the features
774    /// (R0.10 wave 2 shadow pairs; see [`DecisionRole`]). `None` — every
775    /// decision recorded before the twin — means acting: the only decisions
776    /// that existed were the ones that bound the world.
777    #[serde(default, skip_serializing_if = "Option::is_none")]
778    pub role: Option<DecisionRole>,
779
780    /// The result of the decision, `None` until completion.
781    pub outcome: Option<DecisionOutcome>,
782
783    /// When the decision was made, read from the run's clock.
784    pub decided_at: DateTime<Utc>,
785}
786
787/// The envelope any learned backoff cap must stay within, in milliseconds
788/// (one hour). The floor's own cap is [`crate::durable::MAX_RETRY_DELAY_MS`];
789/// a learned policy may widen the schedule, but never past the envelope —
790/// beyond it a stuck dependency parks work for longer than any operator
791/// would accept discovering by surprise.
792pub const POLICY_MAX_DELAY_ENVELOPE_MS: u64 = 3_600_000;
793
794/// The envelope any learned attempt budget must stay within. Ten attempts
795/// is already generous past the floor's three; beyond the envelope a
796/// policy is re-trying as a substitute for fixing the cause.
797pub const POLICY_MAX_ATTEMPTS_ENVELOPE: u32 = 10;
798
799/// The minimum timeout bound any policy may impose, in milliseconds.
800/// Below it ordinary work aborts early — a correctness hazard no policy
801/// may cross (the same floor the Wave 1 headroom experiment
802/// pre-registered). The twin's ladder shares this constant
803/// ([`crate::twin::MIN_TIMEOUT_RUNG_MS`] re-exports it) so the evaluation
804/// harness and the production contract enforce one bound.
805pub const MIN_TIMEOUT_RUNG_MS: u64 = 100;
806
807/// One backoff schedule: the numbers a retry decision is made with.
808///
809/// This is the shape both the flat policy-wide schedule and each per-class
810/// override take (R0.10 wave 3): the backoff draws from
811/// `[0, base_delay_ms * 2^(attempt-1)]` capped at `max_delay_ms`, and a
812/// retryable failure dead-letters once `attempt >= max_attempts`.
813#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
814pub struct BackoffParameters {
815    /// Base of the exponential backoff schedule, in milliseconds.
816    pub base_delay_ms: u64,
817
818    /// Cap of the backoff schedule, in milliseconds.
819    pub max_delay_ms: u64,
820
821    /// Attempt budget: the number of attempts counting the initial one.
822    /// `0` means no retries at all — every retryable failure dead-letters.
823    pub max_attempts: u32,
824}
825
826impl BackoffParameters {
827    /// The contract every backoff schedule — flat or per-class — must
828    /// satisfy: a positive base no larger than the cap, a cap inside the
829    /// declared envelope, and a budget inside the declared envelope.
830    /// Anything else is rejected (`Err`), so an out-of-envelope parameter
831    /// set can never become an active policy — the gate fails closed.
832    pub fn validate(&self) -> crate::error::Result<()> {
833        let invalid = |message: String| RustyError::InvalidUpdate(message);
834        if self.base_delay_ms == 0 {
835            return Err(invalid(
836                "backoff base_delay_ms must be positive — a zero base retries immediately, \
837                 a retry storm by another name"
838                    .to_owned(),
839            ));
840        }
841        if self.base_delay_ms > self.max_delay_ms {
842            return Err(invalid(format!(
843                "backoff base_delay_ms {} exceeds max_delay_ms {} — the schedule would clamp \
844                 to the cap from the first retry, an exponential in name only",
845                self.base_delay_ms, self.max_delay_ms
846            )));
847        }
848        if self.max_delay_ms > POLICY_MAX_DELAY_ENVELOPE_MS {
849            return Err(invalid(format!(
850                "backoff max_delay_ms {} exceeds the {POLICY_MAX_DELAY_ENVELOPE_MS} ms \
851                 envelope",
852                self.max_delay_ms
853            )));
854        }
855        if self.max_attempts > POLICY_MAX_ATTEMPTS_ENVELOPE {
856            return Err(invalid(format!(
857                "backoff max_attempts {} exceeds the {POLICY_MAX_ATTEMPTS_ENVELOPE}-attempt \
858                 envelope",
859                self.max_attempts
860            )));
861        }
862        Ok(())
863    }
864}
865
866/// The retry family's parameters of an [`ExecutorPolicy`].
867///
868/// The flat schedule is the default every class falls back to. `per_class`
869/// (R0.10 wave 3) carries learned per-[`crate::durable::ErrorClass`]
870/// overrides: a class with an entry decides by that schedule (its budget
871/// narrowing the task's declared budget, never widening it); a class
872/// without one decides by the flat schedule. Absent from the wire when
873/// `None`, so the floor's serialized shape is unchanged from v1.
874#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
875pub struct RetryPolicyParameters {
876    /// Base of the exponential backoff schedule, in milliseconds.
877    pub base_delay_ms: u64,
878
879    /// Cap of the backoff schedule, in milliseconds.
880    pub max_delay_ms: u64,
881
882    /// Attempt budget: the number of attempts counting the initial one.
883    /// `0` means no retries at all — every retryable failure dead-letters.
884    pub max_attempts: u32,
885
886    /// Learned per-error-class schedules (R0.10 wave 3). `None` — every
887    /// pre-learning policy — means the flat schedule decides for all
888    /// classes, exactly the v1 behavior.
889    #[serde(default, skip_serializing_if = "Option::is_none")]
890    pub per_class: Option<BTreeMap<crate::durable::ErrorClass, BackoffParameters>>,
891}
892
893impl RetryPolicyParameters {
894    /// The flat schedule as [`BackoffParameters`].
895    pub fn flat(&self) -> BackoffParameters {
896        BackoffParameters {
897            base_delay_ms: self.base_delay_ms,
898            max_delay_ms: self.max_delay_ms,
899            max_attempts: self.max_attempts,
900        }
901    }
902
903    /// The family's contract: the flat schedule validates, and every
904    /// per-class entry validates. One bad entry condemns the whole set —
905    /// there is no "apply the valid half" path, because half-applied
906    /// policy is how a deployment drifts from what was evaluated.
907    pub fn validate(&self) -> crate::error::Result<()> {
908        self.flat().validate()?;
909        if let Some(per_class) = &self.per_class {
910            for (class, schedule) in per_class {
911                schedule.validate().map_err(|e| {
912                    RustyError::InvalidUpdate(format!("per-class backoff for {class:?}: {e}"))
913                })?;
914            }
915        }
916        Ok(())
917    }
918}
919
920/// The timeout family's parameters of an [`ExecutorPolicy`].
921///
922/// `None` means uncapped — the honest encoding of "no timeout policy
923/// is in force", distinct from any concrete millisecond bound.
924/// `per_callee` (R0.10 wave 3) carries learned per-callee bounds: the
925/// bound that applies to an operation is its callee's entry when one
926/// exists, the default otherwise, and no bound at all under the floor.
927#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
928pub struct TimeoutPolicyParameters {
929    /// Default timeout applied to operations without their own bound, in
930    /// milliseconds. `None` means no default is imposed.
931    #[serde(default, skip_serializing_if = "Option::is_none")]
932    pub default_millis: Option<u64>,
933
934    /// Hard ceiling any operation timeout must stay under, in milliseconds.
935    /// `None` means uncapped.
936    #[serde(default, skip_serializing_if = "Option::is_none")]
937    pub max_millis: Option<u64>,
938
939    /// Learned per-callee bounds in milliseconds (R0.10 wave 3), keyed by
940    /// the callee identity the decision point journals (a tool name, a
941    /// node id). `None` — every pre-learning policy — means no per-callee
942    /// bounds, exactly the v1 behavior.
943    #[serde(default, skip_serializing_if = "Option::is_none")]
944    pub per_callee: Option<BTreeMap<String, u64>>,
945}
946
947impl TimeoutPolicyParameters {
948    /// The family's contract: every bound respects the minimum rung (below
949    /// it ordinary work aborts early — a correctness hazard), the default
950    /// stays under the ceiling, and every per-callee entry stays under the
951    /// ceiling when one is declared. One bad bound condemns the whole set.
952    pub fn validate(&self) -> crate::error::Result<()> {
953        let invalid = |message: String| RustyError::InvalidUpdate(message);
954        let check_floor = |what: &str, millis: u64| -> crate::error::Result<()> {
955            if millis < MIN_TIMEOUT_RUNG_MS {
956                return Err(invalid(format!(
957                    "timeout {what} {millis} ms is below the {MIN_TIMEOUT_RUNG_MS} ms minimum \
958                     rung — below it ordinary work aborts early, a correctness hazard no \
959                     policy may cross"
960                )));
961            }
962            Ok(())
963        };
964        if let Some(default) = self.default_millis {
965            check_floor("default_millis", default)?;
966        }
967        if let Some(max) = self.max_millis {
968            check_floor("max_millis", max)?;
969        }
970        if let (Some(default), Some(max)) = (self.default_millis, self.max_millis) {
971            if default > max {
972                return Err(invalid(format!(
973                    "timeout default_millis {default} exceeds max_millis {max} — the default \
974                     bound would sit above its own ceiling"
975                )));
976            }
977        }
978        if let Some(per_callee) = &self.per_callee {
979            for (callee, millis) in per_callee {
980                check_floor(&format!("per_callee[{callee}]"), *millis)?;
981                if let Some(max) = self.max_millis {
982                    if *millis > max {
983                        return Err(invalid(format!(
984                            "timeout per_callee[{callee}] {millis} ms exceeds max_millis \
985                             {max} — a learned bound may only narrow the declared ceiling"
986                        )));
987                    }
988                }
989            }
990        }
991        Ok(())
992    }
993}
994
995/// The concurrency family's parameters of an [`ExecutorPolicy`].
996///
997/// v1 pins the shape only: no executor decision point consumes these values
998/// yet. `None` means unlimited — the honest encoding of "no concurrency
999/// policy is in force".
1000#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1001pub struct ConcurrencyPolicyParameters {
1002    /// Maximum number of parallel executions. `None` means unlimited.
1003    #[serde(default, skip_serializing_if = "Option::is_none")]
1004    pub max_parallel: Option<u32>,
1005}
1006
1007/// The executor policy contract (R0.8 wave 4): one versioned bundle of the
1008/// parameters the executor's mechanical decision points agree to decide
1009/// with.
1010///
1011/// An `ExecutorPolicy` is what a [`PolicyVersion`] *names*: the registry
1012/// (server side) stores immutable policy bodies under content-derived
1013/// versions, runs bind the active version at admission, and every
1014/// [`DecisionEvent`] records which version decided. Because the version is
1015/// derived from the content ([`derive_policy_version`]), two registries that
1016/// agree on a version string agree on the exact parameters — promotion and
1017/// rollback move versions, never mutate bodies.
1018///
1019/// v1 wires versions into admission binding and decision evidence; R0.10
1020/// wave 3 adds the application loop: the retry classifier and the timeout
1021/// decision point read the bound version's parameters through
1022/// [`crate::durable::resolve_retry_parameters`] and
1023/// [`crate::durable::resolve_timeout_bound_ms`], with the static floor's
1024/// constants as the read path when the version names no override (or names
1025/// an invalid one — invalid parameters fail closed to the floor).
1026/// The static floor ([`ExecutorPolicy::static_v0`]) is the behavior every
1027/// pre-learning run already had: the retry constants of
1028/// [`crate::durable::classify_retry`], no timeout bound, no concurrency
1029/// limit.
1030#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1031pub struct ExecutorPolicy {
1032    /// Retry parameters — the family v1 actually emits decisions for.
1033    pub retry: RetryPolicyParameters,
1034
1035    /// Timeout parameters (shape pinned; unconsumed in v1).
1036    pub timeout: TimeoutPolicyParameters,
1037
1038    /// Concurrency parameters (shape pinned; unconsumed in v1).
1039    pub concurrency: ConcurrencyPolicyParameters,
1040}
1041
1042impl ExecutorPolicy {
1043    /// The static floor: the fixed behavior of every run before the policy
1044    /// plane landed, named by [`PolicyVersion::STATIC_V0`].
1045    ///
1046    /// The retry parameters mirror the `crate::durable` backoff constants and
1047    /// the server's default attempt budget (`DEFAULT_MAX_ATTEMPTS = 3`); the
1048    /// timeout and concurrency families are uncapped, matching the executor's
1049    /// behavior when no policy is in force.
1050    pub fn static_v0() -> Self {
1051        Self {
1052            retry: RetryPolicyParameters {
1053                base_delay_ms: crate::durable::BASE_RETRY_DELAY_MS,
1054                max_delay_ms: crate::durable::MAX_RETRY_DELAY_MS,
1055                max_attempts: 3,
1056                per_class: None,
1057            },
1058            timeout: TimeoutPolicyParameters {
1059                default_millis: None,
1060                max_millis: None,
1061                per_callee: None,
1062            },
1063            concurrency: ConcurrencyPolicyParameters { max_parallel: None },
1064        }
1065    }
1066
1067    /// `true` when this policy is exactly the static floor — the read path
1068    /// every decision point falls back to. Compared by value, not by
1069    /// version name: a registered body identical to the floor *is* the
1070    /// floor's behavior, whatever string names it.
1071    pub fn is_static_floor(&self) -> bool {
1072        self == &Self::static_v0()
1073    }
1074
1075    /// The whole bundle's contract: every family's parameters validate.
1076    /// Decision points call this (or the per-family equivalents) before
1077    /// reading parameters into a decision — an invalid bundle steers
1078    /// nothing; the floor decides instead.
1079    pub fn validate(&self) -> crate::error::Result<()> {
1080        self.retry.validate()?;
1081        self.timeout.validate()?;
1082        if let Some(0) = self.concurrency.max_parallel {
1083            return Err(RustyError::InvalidUpdate(
1084                "concurrency max_parallel 0 admits no work at all — a policy that halts the \
1085                 fleet is not a learning outcome, it is an outage"
1086                    .to_owned(),
1087            ));
1088        }
1089        Ok(())
1090    }
1091
1092    /// This policy with one family's parameters replaced by `parameters`
1093    /// (parsed as that family's parameter type).
1094    ///
1095    /// This is how a promoted policy candidate — whose content is a family
1096    /// plus a free-form parameter value — becomes a concrete
1097    /// `ExecutorPolicy`: the candidate's parameters are parsed against the
1098    /// family's contract and checked against the family's declared envelope
1099    /// (R0.10 wave 3), then overlaid onto the policy that was active (the
1100    /// floor when nothing was promoted yet). Out-of-envelope parameters are
1101    /// rejected — a malformed candidate can never become an active policy.
1102    /// Families without a parameter contract
1103    /// ([`DecisionFamily::WorkerPlacement`],
1104    /// [`DecisionFamily::CheckpointPlacement`]) are rejected: those families
1105    /// are shadow-only, and a shadow family's parameters cannot activate.
1106    pub fn with_family_parameters(
1107        &self,
1108        family: DecisionFamily,
1109        parameters: serde_json::Value,
1110    ) -> crate::error::Result<Self> {
1111        let mut policy = self.clone();
1112        match family {
1113            DecisionFamily::Retry => {
1114                policy.retry = serde_json::from_value(parameters).map_err(|e| {
1115                    RustyError::InvalidUpdate(format!(
1116                        "retry policy parameters do not match the contract: {e}"
1117                    ))
1118                })?;
1119                policy.retry.validate().map_err(|e| {
1120                    RustyError::InvalidUpdate(format!(
1121                        "retry policy parameters fall outside the envelope: {e}"
1122                    ))
1123                })?;
1124            }
1125            DecisionFamily::Timeout => {
1126                policy.timeout = serde_json::from_value(parameters).map_err(|e| {
1127                    RustyError::InvalidUpdate(format!(
1128                        "timeout policy parameters do not match the contract: {e}"
1129                    ))
1130                })?;
1131                policy.timeout.validate().map_err(|e| {
1132                    RustyError::InvalidUpdate(format!(
1133                        "timeout policy parameters fall outside the envelope: {e}"
1134                    ))
1135                })?;
1136            }
1137            DecisionFamily::Concurrency => {
1138                policy.concurrency = serde_json::from_value(parameters).map_err(|e| {
1139                    RustyError::InvalidUpdate(format!(
1140                        "concurrency policy parameters do not match the contract: {e}"
1141                    ))
1142                })?;
1143                if let Some(0) = policy.concurrency.max_parallel {
1144                    return Err(RustyError::InvalidUpdate(
1145                        "concurrency policy parameters fall outside the envelope: \
1146                         max_parallel 0 admits no work at all"
1147                            .to_owned(),
1148                    ));
1149                }
1150            }
1151            other => {
1152                return Err(RustyError::InvalidUpdate(format!(
1153                    "decision family `{other:?}` has no executor-policy parameter contract \
1154                     in this version"
1155                )));
1156            }
1157        }
1158        Ok(policy)
1159    }
1160}
1161
1162/// Derive the content-addressed version of an [`ExecutorPolicy`]:
1163/// `policy-{first 12 hex of sha256(canonical_json(policy))}`.
1164///
1165/// Content addressing is what makes the registry's immutability enforceable:
1166/// a version string *is* a commitment to one exact parameter set, so
1167/// "register a different body under an existing version" is detectable as a
1168/// conflict rather than silently overwriting behavior. The static floor is
1169/// exempt — it keeps its human-readable [`PolicyVersion::STATIC_V0`] name
1170/// because it predates the registry and never needs registration.
1171pub fn derive_policy_version(policy: &ExecutorPolicy) -> crate::error::Result<PolicyVersion> {
1172    let bytes = serde_json::to_vec(policy)?;
1173    let hash = sha256_hex(&bytes);
1174    Ok(PolicyVersion::new(format!("policy-{}", &hash[..12])))
1175}
1176
1177/// A capsule version pin — the R0.7 placeholder for R0.9's capsule manifest
1178/// identity.
1179///
1180/// R0.9 gives capsules a full manifest (build digest, declared interface,
1181/// capability grants); R0.7 pins only the version string so a run's manifest
1182/// can already record *which* capsule build influenced it. Typing it now —
1183/// rather than storing a bare string — localizes the R0.9 evolution to one
1184/// type instead of every consumer of the manifest map. Transparent over
1185/// `String`: the wire shape is the version string itself.
1186#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
1187#[serde(transparent)]
1188pub struct CapsuleVersion(pub String);
1189
1190impl CapsuleVersion {
1191    /// Wrap a version string.
1192    pub fn new(version: impl Into<String>) -> Self {
1193        Self(version.into())
1194    }
1195
1196    /// The version string.
1197    pub fn as_str(&self) -> &str {
1198        &self.0
1199    }
1200}
1201
1202impl std::fmt::Display for CapsuleVersion {
1203    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1204        f.write_str(&self.0)
1205    }
1206}
1207
1208/// The versioned run manifest (R0.7): everything beyond the graph itself
1209/// that can influence a run, pinned at checkpoint time.
1210///
1211/// The R0.5 header pins the checkpoint format, the graph version and
1212/// topology, and the executor policy — but a run's behavior is also shaped
1213/// by its prompts, its tools' schemas, its model and parameters, and (as
1214/// they land) its memory schema and capsule builds. The manifest pins all of
1215/// them by content address (lowercase hex SHA-256, the one hashing primitive
1216/// shared with artifact references and journal heads), so a checkpoint
1217/// answers not just "which graph produced this?" but "which *configuration
1218/// of everything else* produced this?".
1219///
1220/// **Upgrade safety.** Pinning is what lets long-running agents survive
1221/// platform upgrades: a run resumed from a checkpoint keeps executing
1222/// against the versions its manifest pins, while new versions shadow for new
1223/// runs. An absent field means *unpinned*, never a default — consumers must
1224/// not invent one. Migration contracts between pinned versions (when a run
1225/// may move from pin A to pin B, and how) are R1.0's stability work,
1226/// deliberately: this wave records the evidence migrations will be judged
1227/// against.
1228///
1229/// Every field is optional and omitted from the wire when unset
1230/// (`skip_serializing_if`), so a header carrying no manifest — or a manifest
1231/// carrying only some pins — produces no shape change for pre-R0.7 readers.
1232#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
1233pub struct RunManifest {
1234    /// Prompt digests: prompt name → SHA-256 of the exact prompt text
1235    /// (`sha256_hex` over its UTF-8 bytes). Prompt text, not a name alone,
1236    /// because an edited prompt under an unchanged name is exactly the drift
1237    /// the manifest exists to catch.
1238    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1239    pub prompts: BTreeMap<String, String>,
1240
1241    /// Tool schema digests: tool name → SHA-256 of the canonical
1242    /// `serde_json` serialization of its parameters schema (the same
1243    /// canonicalization [`PayloadRef::content_hash`] relies on: object keys
1244    /// sort deterministically, so equal schemas hash equal).
1245    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1246    pub tool_schemas: BTreeMap<String, String>,
1247
1248    /// The model identifier the run pinned (a provider-precise string such
1249    /// as `gpt-5.2-2026-06-01`, not a floating alias like `gpt-5.2-latest` —
1250    /// an alias is not a pin).
1251    #[serde(default, skip_serializing_if = "Option::is_none")]
1252    pub model: Option<String>,
1253
1254    /// SHA-256 digest of the canonical JSON of the model parameters
1255    /// (temperature, seed, token limits, ...) the run pinned. A digest
1256    /// rather than the parameters themselves: the header stays cheap to scan
1257    /// and parameter sets with secrets-adjacent values never land in
1258    /// evidence verbatim.
1259    #[serde(default, skip_serializing_if = "Option::is_none")]
1260    pub model_params: Option<String>,
1261
1262    /// The memory schema version the run pinned (R0.8's memory record
1263    /// model). Declared in R0.7 so runs that outlive the R0.8 upgrade can
1264    /// still be interpreted against the schema their memories were written
1265    /// under.
1266    #[serde(default, skip_serializing_if = "Option::is_none")]
1267    pub memory_schema: Option<String>,
1268
1269    /// Capsule version pins: capsule name → [`CapsuleVersion`] (placeholder
1270    /// for R0.9's capsule manifests — see that type's docs).
1271    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1272    pub capsules: BTreeMap<String, CapsuleVersion>,
1273}
1274
1275impl RunManifest {
1276    /// An empty manifest: nothing pinned. Equivalent to [`Default`].
1277    pub fn new() -> Self {
1278        Self::default()
1279    }
1280
1281    /// Pin a prompt by content: records the SHA-256 of its exact UTF-8 text
1282    /// under `name`.
1283    pub fn pin_prompt(mut self, name: impl Into<String>, prompt: &str) -> Self {
1284        self.prompts
1285            .insert(name.into(), sha256_hex(prompt.as_bytes()));
1286        self
1287    }
1288
1289    /// Pin a tool's parameters schema by content: records the SHA-256 of its
1290    /// canonical `serde_json` serialization under `name`.
1291    pub fn pin_tool_schema(mut self, name: impl Into<String>, schema: &Value) -> Self {
1292        self.tool_schemas
1293            .insert(name.into(), canonical_json_digest(schema));
1294        self
1295    }
1296
1297    /// Pin the model identifier and the content digest of its parameters.
1298    pub fn pin_model(mut self, model: impl Into<String>, parameters: &Value) -> Self {
1299        self.model = Some(model.into());
1300        self.model_params = Some(canonical_json_digest(parameters));
1301        self
1302    }
1303
1304    /// Pin the memory schema version (R0.8's record model; see the field
1305    /// docs).
1306    pub fn with_memory_schema(mut self, version: impl Into<String>) -> Self {
1307        self.memory_schema = Some(version.into());
1308        self
1309    }
1310
1311    /// Pin a capsule version (R0.9 placeholder; see [`CapsuleVersion`]).
1312    pub fn pin_capsule(mut self, name: impl Into<String>, version: CapsuleVersion) -> Self {
1313        self.capsules.insert(name.into(), version);
1314        self
1315    }
1316}
1317
1318/// The value with every object map rebuilt in sorted key order,
1319/// recursively — the canonical form every content hash in this crate
1320/// covers.
1321///
1322/// `serde_json`'s default map is BTreeMap-backed, so serializing a `Value`
1323/// already emits object keys sorted; under the default backend this
1324/// transform is an identity and every pre-existing hash is preserved
1325/// byte-for-byte. The hazard is serde_json's `preserve_order` feature,
1326/// which `cedar-policy-core` (R0.9's Cedar engine, behind the server's
1327/// `capsules` feature) enables unconditionally: feature unification then
1328/// swaps the workspace-wide map for an insertion-ordered IndexMap, and
1329/// the same logical payload serializes — and hashes — differently
1330/// depending on the order its keys happened to be inserted. Routing every
1331/// hash through this canonical form keeps content addresses stable across
1332/// both map backends and across builds with and without the feature.
1333pub(crate) fn canonicalize_value(value: &Value) -> Value {
1334    match value {
1335        Value::Object(map) => {
1336            let mut entries: Vec<(&String, &Value)> = map.iter().collect();
1337            entries.sort_by_key(|(key, _)| *key);
1338            Value::Object(
1339                entries
1340                    .into_iter()
1341                    .map(|(key, item)| (key.clone(), canonicalize_value(item)))
1342                    .collect(),
1343            )
1344        }
1345        Value::Array(items) => Value::Array(items.iter().map(canonicalize_value).collect()),
1346        scalar => scalar.clone(),
1347    }
1348}
1349
1350/// SHA-256 of the canonical `serde_json` serialization of `value` — the
1351/// digest convention shared by every manifest pin over JSON content.
1352fn canonical_json_digest(value: &Value) -> String {
1353    // Serializing a `Value` is infallible in practice (its maps always have
1354    // string keys); `PayloadRef::content_hash` documents why the result is
1355    // canonical.
1356    let bytes = serde_json::to_vec(&canonicalize_value(value))
1357        .expect("a serde_json::Value always serializes");
1358    sha256_hex(&bytes)
1359}
1360
1361/// The provenance header stamped into every checkpoint.
1362///
1363/// Answers, for any stored checkpoint: which checkpoint format wrote it
1364/// (`format_version`), which graph produced it (`graph_version` +
1365/// `graph_hash`), under which policy (`policy_version`), and where it sits
1366/// on the run's logical clock. Without this, a checkpoint is data; with it,
1367/// a checkpoint is interpretable evidence — replay can refuse (or migrate)
1368/// checkpoints whose format or graph no longer matches.
1369///
1370/// Added to `Checkpoint` with serde defaults: checkpoints written before
1371/// R0.5 (no header) deserialize into [`CheckpointHeader::default`]. R0.7
1372/// extends the header additively with the [`RunManifest`] pin set — same
1373/// rule: unset fields stay absent from the wire and old headers keep
1374/// deserializing.
1375#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1376pub struct CheckpointHeader {
1377    /// Checkpoint envelope format version; [`CURRENT_FORMAT_VERSION`] for
1378    /// anything written now.
1379    pub format_version: u32,
1380
1381    /// Application-declared graph version (via `RunConfig::with_graph_version`),
1382    /// or `"unversioned"` when the application does not version its graph.
1383    pub graph_version: String,
1384
1385    /// SHA-256 content hash of the compiled graph topology (node names and
1386    /// edge shape — see `Graph::topology_hash`). Detects graph drift between
1387    /// a checkpoint and the code about to resume it; semantic node-body
1388    /// changes are the application's responsibility via `graph_version`.
1389    pub graph_hash: String,
1390
1391    /// The executor policy active when the checkpoint was written.
1392    pub policy_version: PolicyVersion,
1393
1394    /// The run's logical clock value (milliseconds) at creation. Under the
1395    /// default system clock this is epoch milliseconds; under a logical
1396    /// clock it is the deterministic tick — either way it is the ordering
1397    /// and replay handle, not wall time.
1398    pub logical_clock: u64,
1399
1400    /// The versioned run manifest (R0.7): prompts, tool schemas, model and
1401    /// parameters, memory schema, and capsule versions pinned for the run —
1402    /// see [`RunManifest`] for the upgrade-safety contract. Stamped from
1403    /// `RunConfig::with_manifest` at checkpoint time.
1404    ///
1405    /// Additive: `None` (the default) is absent from the wire, so headers
1406    /// written before R0.7 — and headers of runs that pin nothing — keep
1407    /// their exact R0.5 shape.
1408    #[serde(default, skip_serializing_if = "Option::is_none")]
1409    pub manifest: Option<RunManifest>,
1410}
1411
1412impl Default for CheckpointHeader {
1413    /// The header for a checkpoint written without run context: current
1414    /// format, unversioned/empty graph identity, static policy, clock zero,
1415    /// no manifest. Also the deserialization fallback for pre-R0.5
1416    /// checkpoints.
1417    fn default() -> Self {
1418        Self {
1419            format_version: CURRENT_FORMAT_VERSION,
1420            graph_version: "unversioned".to_owned(),
1421            graph_hash: String::new(),
1422            policy_version: PolicyVersion::default(),
1423            logical_clock: 0,
1424            manifest: None,
1425        }
1426    }
1427}
1428
1429/// A reference to the journal head at a checkpoint boundary, stamped into
1430/// the checkpoint so evidence and state travel together.
1431///
1432/// The hash is the journal's running head hash (chained SHA-256 over
1433/// recorded events), so a checkpoint pins not just *how many* events existed
1434/// but *which* events — tamper-evident linkage between state and evidence.
1435#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1436pub struct JournalRef {
1437    /// Number of events in the journal at the boundary.
1438    pub events: u64,
1439
1440    /// Journal head hash (chained SHA-256) at the boundary.
1441    pub sha256: String,
1442}
1443
1444#[cfg(test)]
1445mod tests {
1446    use super::*;
1447    use serde_json::json;
1448
1449    #[test]
1450    fn sha256_hex_is_stable_and_lowercase() {
1451        // SHA-256 of the empty input, pinned against the published digest.
1452        assert_eq!(
1453            sha256_hex(b""),
1454            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
1455        );
1456        assert_eq!(sha256_hex(b"abc").len(), 64);
1457    }
1458
1459    #[test]
1460    fn policy_version_default_is_static_floor() {
1461        assert_eq!(PolicyVersion::default().as_str(), PolicyVersion::STATIC_V0);
1462        // Transparent newtype: serializes as a bare string.
1463        assert_eq!(
1464            serde_json::to_value(PolicyVersion::default()).unwrap(),
1465            json!("static-v0")
1466        );
1467    }
1468
1469    #[test]
1470    fn executor_policy_static_floor_mirrors_the_durable_constants() {
1471        let floor = ExecutorPolicy::static_v0();
1472        assert_eq!(
1473            floor.retry.base_delay_ms,
1474            crate::durable::BASE_RETRY_DELAY_MS
1475        );
1476        assert_eq!(floor.retry.max_delay_ms, crate::durable::MAX_RETRY_DELAY_MS);
1477        // The floor pins the server's default attempt budget; timeout and
1478        // concurrency are uncapped — the honest encoding of "no policy".
1479        assert_eq!(floor.retry.max_attempts, 3);
1480        assert!(floor.timeout.default_millis.is_none());
1481        assert!(floor.timeout.max_millis.is_none());
1482        assert!(floor.concurrency.max_parallel.is_none());
1483        // Unset options stay absent from the wire.
1484        let wire = serde_json::to_value(floor).unwrap();
1485        assert_eq!(wire["timeout"], json!({}));
1486        assert_eq!(wire["concurrency"], json!({}));
1487    }
1488
1489    #[test]
1490    fn derive_policy_version_is_content_addressed() {
1491        let policy = ExecutorPolicy::static_v0()
1492            .with_family_parameters(
1493                DecisionFamily::Retry,
1494                json!({"base_delay_ms": 500, "max_delay_ms": 60_000, "max_attempts": 5}),
1495            )
1496            .unwrap();
1497        let first = derive_policy_version(&policy).unwrap();
1498        let again = derive_policy_version(&policy).unwrap();
1499        assert_eq!(first, again, "version derivation must be deterministic");
1500        assert!(
1501            first.as_str().starts_with("policy-"),
1502            "derived versions carry the policy- prefix: {first}"
1503        );
1504        assert_eq!(first.as_str().len(), "policy-".len() + 12);
1505
1506        // Any parameter change is a different version — that is what makes
1507        // registry immutability enforceable.
1508        let changed = policy
1509            .with_family_parameters(
1510                DecisionFamily::Retry,
1511                json!({"base_delay_ms": 500, "max_delay_ms": 60_000, "max_attempts": 6}),
1512            )
1513            .unwrap();
1514        assert_ne!(first, derive_policy_version(&changed).unwrap());
1515    }
1516
1517    #[test]
1518    fn with_family_parameters_validates_and_overlays() {
1519        let base = ExecutorPolicy::static_v0();
1520
1521        // Timeout and concurrency families parse their own contracts.
1522        let with_timeout = base
1523            .with_family_parameters(
1524                DecisionFamily::Timeout,
1525                json!({"default_millis": 30_000, "max_millis": 120_000}),
1526            )
1527            .unwrap();
1528        assert_eq!(with_timeout.timeout.default_millis, Some(30_000));
1529        assert_eq!(with_timeout.timeout.max_millis, Some(120_000));
1530        // Untouched families keep the base values.
1531        assert_eq!(with_timeout.retry, base.retry);
1532
1533        let with_concurrency = base
1534            .with_family_parameters(DecisionFamily::Concurrency, json!({"max_parallel": 8}))
1535            .unwrap();
1536        assert_eq!(with_concurrency.concurrency.max_parallel, Some(8));
1537
1538        // A malformed body is rejected with the family named.
1539        let err = base
1540            .with_family_parameters(DecisionFamily::Retry, json!({"base_delay_ms": "fast"}))
1541            .unwrap_err();
1542        assert!(err.to_string().contains("retry policy parameters"), "{err}");
1543
1544        // Families without a v1 parameter contract are rejected.
1545        for family in [
1546            DecisionFamily::WorkerPlacement,
1547            DecisionFamily::CheckpointPlacement,
1548        ] {
1549            let err = base.with_family_parameters(family, json!({})).unwrap_err();
1550            assert!(
1551                err.to_string().contains("no executor-policy parameter"),
1552                "{err}"
1553            );
1554        }
1555    }
1556
1557    #[test]
1558    fn payload_ref_content_hash_agrees_across_representations() {
1559        let value = json!({"b": 1, "a": [2, 3]});
1560        let bytes = serde_json::to_vec(&value).unwrap();
1561        let inline = PayloadRef::inline(value);
1562        let referenced = PayloadRef::Artifact(ArtifactRef {
1563            sha256: sha256_hex(&bytes),
1564            bytes: bytes.len() as u64,
1565        });
1566        assert_eq!(
1567            inline.content_hash().unwrap(),
1568            referenced.content_hash().unwrap()
1569        );
1570    }
1571
1572    #[test]
1573    fn effect_repeatability_ladder() {
1574        assert!(Effect::Pure.is_freely_repeatable());
1575        assert!(Effect::ReadOnly.is_freely_repeatable());
1576        assert!(Effect::Idempotent.is_freely_repeatable());
1577        assert!(!Effect::Compensatable.is_freely_repeatable());
1578        assert!(!Effect::NonIdempotent.is_freely_repeatable());
1579    }
1580
1581    #[test]
1582    fn contracts_serde_roundtrip() {
1583        let event = RunEvent {
1584            id: "r1:7".into(),
1585            run_id: "r1".into(),
1586            thread_id: "t1".into(),
1587            node_id: Some("agent".into()),
1588            seq: 7,
1589            kind: RunEventKind::ModelCall,
1590            effect: Effect::NonIdempotent,
1591            input: Some(PayloadRef::inline(json!({"messages": []}))),
1592            output: Some(PayloadRef::Artifact(ArtifactRef {
1593                sha256: sha256_hex(b"response"),
1594                bytes: 8,
1595            })),
1596            latency_ms: Some(42),
1597            tokens: Some(Usage {
1598                prompt_tokens: 10,
1599                completion_tokens: 5,
1600                total_tokens: 15,
1601            }),
1602            cost_usd: Some(0.0001),
1603            status: EventStatus::Ok,
1604            parent: Some("r1:3".into()),
1605            recorded_at: DateTime::<Utc>::from_timestamp_millis(1_000).unwrap(),
1606        };
1607        let back: RunEvent = serde_json::from_str(&serde_json::to_string(&event).unwrap()).unwrap();
1608        assert_eq!(event, back);
1609
1610        let decision = DecisionEvent {
1611            id: "r1:d0".into(),
1612            run_id: "r1".into(),
1613            thread_id: "t1".into(),
1614            seq: 0,
1615            family: DecisionFamily::Retry,
1616            features: Map::from_iter([("failure_class".to_owned(), json!("timeout"))]),
1617            legal_actions: vec![DecisionAction::Retry { attempt: 1 }, DecisionAction::Abort],
1618            selected: DecisionAction::Retry { attempt: 1 },
1619            propensity: 0.75,
1620            policy_version: PolicyVersion::default(),
1621            role: None,
1622            outcome: None,
1623            decided_at: DateTime::<Utc>::from_timestamp_millis(1_000).unwrap(),
1624        };
1625        let back: DecisionEvent =
1626            serde_json::from_str(&serde_json::to_string(&decision).unwrap()).unwrap();
1627        assert_eq!(decision, back);
1628    }
1629
1630    #[test]
1631    fn checkpoint_header_default_matches_pre_r05_fallback() {
1632        let header = CheckpointHeader::default();
1633        assert_eq!(header.format_version, CURRENT_FORMAT_VERSION);
1634        assert_eq!(header.graph_version, "unversioned");
1635        assert_eq!(header.policy_version, PolicyVersion::default());
1636        assert_eq!(header.logical_clock, 0);
1637        assert_eq!(header.manifest, None);
1638    }
1639
1640    #[test]
1641    fn manifest_digests_are_stable_content_addresses() {
1642        // Constants computed independently (SHA-256 of the exact bytes): the
1643        // pins are content addresses, so their stability across releases is
1644        // the contract — a drifting digest would silently split runs from
1645        // their own evidence.
1646        let manifest = RunManifest::new()
1647            .pin_prompt("system", "You are a careful research agent.")
1648            .pin_tool_schema(
1649                "search",
1650                &json!({"type": "object", "properties": {"query": {"type": "string"}}}),
1651            )
1652            .pin_model(
1653                "gpt-5.2-2026-06-01",
1654                &json!({"temperature": 0, "seed": 42, "max_tokens": 512}),
1655            )
1656            .with_memory_schema("memory-v1")
1657            .pin_capsule("researcher", CapsuleVersion::new("1.4.0"));
1658
1659        assert_eq!(
1660            manifest.prompts["system"],
1661            "edff20fbc61c032a9206bdc94aec3b70e05ab953383972b267b83957d9ba7bfe"
1662        );
1663        assert_eq!(
1664            manifest.tool_schemas["search"],
1665            "094ec29d007cce150c65abf0756d79ad5b62a1acfdb6e0841f69f1377ef41761"
1666        );
1667        assert_eq!(
1668            manifest.model_params.as_deref(),
1669            Some("fc004364a674799b07f8e4e6323ad74398745607ae3bd955e0d9c1d7529a0762")
1670        );
1671        assert_eq!(manifest.model.as_deref(), Some("gpt-5.2-2026-06-01"));
1672        assert_eq!(manifest.memory_schema.as_deref(), Some("memory-v1"));
1673        assert_eq!(manifest.capsules["researcher"].as_str(), "1.4.0");
1674
1675        // Key order in the source JSON must not matter: canonicalization
1676        // sorts object keys, so semantically equal schemas pin equal.
1677        let reordered = RunManifest::new().pin_tool_schema(
1678            "search",
1679            &json!({"properties": {"query": {"type": "string"}}, "type": "object"}),
1680        );
1681        assert_eq!(manifest.tool_schemas, reordered.tool_schemas);
1682    }
1683
1684    #[test]
1685    fn manifest_serde_roundtrip_and_sparse_wire_shape() {
1686        let manifest = RunManifest::new()
1687            .pin_prompt("system", "Be brief.")
1688            .pin_model("model-x", &json!({"temperature": 0.5}));
1689        let back: RunManifest =
1690            serde_json::from_str(&serde_json::to_string(&manifest).unwrap()).unwrap();
1691        assert_eq!(manifest, back);
1692
1693        // Sparse pins stay sparse on the wire: unset fields are absent, not
1694        // null or empty — pre-R0.7 readers see no new keys at all.
1695        let value = serde_json::to_value(&manifest).unwrap();
1696        assert!(value.get("tool_schemas").is_none());
1697        assert!(value.get("memory_schema").is_none());
1698        assert!(value.get("capsules").is_none());
1699        assert!(value.get("prompts").is_some());
1700
1701        // An empty manifest serializes to an empty object, and a header that
1702        // carries no manifest omits the field entirely.
1703        assert_eq!(serde_json::to_value(RunManifest::new()).unwrap(), json!({}));
1704        let header = CheckpointHeader::default();
1705        assert!(serde_json::to_value(&header)
1706            .unwrap()
1707            .get("manifest")
1708            .is_none());
1709    }
1710
1711    #[test]
1712    fn r05_header_without_manifest_still_loads() {
1713        // The R0.5 shape — exactly what the golden file pins — deserializes
1714        // into the extended header with the manifest unset.
1715        let r05_shape = json!({
1716            "format_version": 1,
1717            "graph_version": "react-v3",
1718            "graph_hash": "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae",
1719            "policy_version": "static-v0",
1720            "logical_clock": 1750000000000u64,
1721        });
1722        let header: CheckpointHeader = serde_json::from_value(r05_shape).unwrap();
1723        assert_eq!(header.manifest, None);
1724        assert_eq!(header.format_version, CURRENT_FORMAT_VERSION);
1725
1726        // And a header carrying a manifest round-trips it.
1727        let extended = CheckpointHeader {
1728            manifest: Some(RunManifest::new().with_memory_schema("memory-v1")),
1729            ..header
1730        };
1731        let back: CheckpointHeader =
1732            serde_json::from_str(&serde_json::to_string(&extended).unwrap()).unwrap();
1733        assert_eq!(extended, back);
1734    }
1735
1736    #[test]
1737    fn effect_receipt_effect_id_is_additive() {
1738        let receipt = EffectReceipt {
1739            provider: "stripe".into(),
1740            provider_id: "ch_3PKd".into(),
1741            idempotency_key: "run-1:charge:7".into(),
1742            task_id: None,
1743            effect_id: None,
1744        };
1745        // Unset: absent on the wire — pre-R0.7 receipts see no shape change.
1746        let value = serde_json::to_value(&receipt).unwrap();
1747        assert!(value.get("effect_id").is_none());
1748
1749        // Set: carried as a bare digest string, surviving the round-trip.
1750        let with_id = EffectReceipt {
1751            effect_id: Some(
1752                "9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673ca7".into(),
1753            ),
1754            ..receipt
1755        };
1756        let back: EffectReceipt =
1757            serde_json::from_str(&serde_json::to_string(&with_id).unwrap()).unwrap();
1758        assert_eq!(with_id, back);
1759    }
1760}