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/// One executor policy decision with everything offline learning needs to
698/// evaluate it.
699///
700/// The learning contract (R0.8+): given `features` and `legal_actions`, the
701/// policy named by `policy_version` chose `selected` with probability
702/// `propensity`. Propensity is assigned **at decision time**, never
703/// reconstructed — without it, off-policy evaluation (comparing a candidate
704/// policy against the recorded one) is impossible. `outcome` is `None`
705/// until the affected operation completes.
706///
707/// v1 froze this contract without emitters; R0.8 wave 4 wires the first
708/// emission point (the retry classifier, see
709/// [`crate::durable::retry_decision_event`]), journaled as
710/// [`RunEventKind::PolicyDecision`].
711#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
712pub struct DecisionEvent {
713    /// Deterministic decision id (`{run_id}:d{n}` — a separate sequence from
714    /// [`RunEvent`], so decision ids stay stable if event kinds are added).
715    pub id: String,
716
717    /// The run the decision was made in.
718    pub run_id: String,
719
720    /// The thread (session) the run belongs to.
721    pub thread_id: String,
722
723    /// Sequence number within the decision stream of this run.
724    pub seq: u64,
725
726    /// Which executor decision this is.
727    pub family: DecisionFamily,
728
729    /// The observation the policy decided from (latency percentiles, failure
730    /// class, queue depth, ...). Free-form JSON: the feature schema evolves
731    /// with the policy, but the envelope does not.
732    pub features: Map<String, Value>,
733
734    /// Every action that was legal at decision time. Off-policy evaluation
735    /// needs the full set, not just the chosen one.
736    pub legal_actions: Vec<DecisionAction>,
737
738    /// The action the policy took. Must be a member of `legal_actions`
739    /// (enforced by the policy plane, not by this type).
740    pub selected: DecisionAction,
741
742    /// The probability the active policy assigned to `selected` at decision
743    /// time, in `(0, 1]`. First-class because learning correctness depends
744    /// on it: importance weighting divides by the propensity.
745    pub propensity: f64,
746
747    /// The policy that made the decision.
748    pub policy_version: PolicyVersion,
749
750    /// The result of the decision, `None` until completion.
751    pub outcome: Option<DecisionOutcome>,
752
753    /// When the decision was made, read from the run's clock.
754    pub decided_at: DateTime<Utc>,
755}
756
757/// The retry family's parameters of an [`ExecutorPolicy`].
758///
759/// These are the numbers [`crate::durable::classify_retry`] decides with:
760/// the backoff schedule draws from `[0, base_delay_ms * 2^(attempt-1)]`
761/// capped at `max_delay_ms`, and a retryable failure dead-letters once
762/// `attempt >= max_attempts`.
763#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
764pub struct RetryPolicyParameters {
765    /// Base of the exponential backoff schedule, in milliseconds.
766    pub base_delay_ms: u64,
767
768    /// Cap of the backoff schedule, in milliseconds.
769    pub max_delay_ms: u64,
770
771    /// Attempt budget: the number of attempts counting the initial one.
772    /// `0` means no retries at all — every retryable failure dead-letters.
773    pub max_attempts: u32,
774}
775
776/// The timeout family's parameters of an [`ExecutorPolicy`].
777///
778/// v1 pins the shape only: no executor decision point consumes these values
779/// yet. `None` means uncapped — the honest encoding of "no timeout policy
780/// is in force", distinct from any concrete millisecond bound.
781#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
782pub struct TimeoutPolicyParameters {
783    /// Default timeout applied to operations without their own bound, in
784    /// milliseconds. `None` means no default is imposed.
785    #[serde(default, skip_serializing_if = "Option::is_none")]
786    pub default_millis: Option<u64>,
787
788    /// Hard ceiling any operation timeout must stay under, in milliseconds.
789    /// `None` means uncapped.
790    #[serde(default, skip_serializing_if = "Option::is_none")]
791    pub max_millis: Option<u64>,
792}
793
794/// The concurrency family's parameters of an [`ExecutorPolicy`].
795///
796/// v1 pins the shape only: no executor decision point consumes these values
797/// yet. `None` means unlimited — the honest encoding of "no concurrency
798/// policy is in force".
799#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
800pub struct ConcurrencyPolicyParameters {
801    /// Maximum number of parallel executions. `None` means unlimited.
802    #[serde(default, skip_serializing_if = "Option::is_none")]
803    pub max_parallel: Option<u32>,
804}
805
806/// The executor policy contract (R0.8 wave 4): one versioned bundle of the
807/// parameters the executor's mechanical decision points agree to decide
808/// with.
809///
810/// An `ExecutorPolicy` is what a [`PolicyVersion`] *names*: the registry
811/// (server side) stores immutable policy bodies under content-derived
812/// versions, runs bind the active version at admission, and every
813/// [`DecisionEvent`] records which version decided. Because the version is
814/// derived from the content ([`derive_policy_version`]), two registries that
815/// agree on a version string agree on the exact parameters — promotion and
816/// rollback move versions, never mutate bodies.
817///
818/// v1 wires versions into admission binding and decision evidence. The
819/// static floor ([`ExecutorPolicy::static_v0`]) is the behavior every
820/// pre-learning run already had: the retry constants of
821/// [`crate::durable::classify_retry`], no timeout bound, no concurrency
822/// limit. Mechanical *application* of learned (non-floor) parameters to the
823/// queue's decision points is a later wave; wave 4 makes them addressable,
824/// promotable, and evident.
825#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
826pub struct ExecutorPolicy {
827    /// Retry parameters — the family v1 actually emits decisions for.
828    pub retry: RetryPolicyParameters,
829
830    /// Timeout parameters (shape pinned; unconsumed in v1).
831    pub timeout: TimeoutPolicyParameters,
832
833    /// Concurrency parameters (shape pinned; unconsumed in v1).
834    pub concurrency: ConcurrencyPolicyParameters,
835}
836
837impl ExecutorPolicy {
838    /// The static floor: the fixed behavior of every run before the policy
839    /// plane landed, named by [`PolicyVersion::STATIC_V0`].
840    ///
841    /// The retry parameters mirror the `crate::durable` backoff constants and
842    /// the server's default attempt budget (`DEFAULT_MAX_ATTEMPTS = 3`); the
843    /// timeout and concurrency families are uncapped, matching the executor's
844    /// behavior when no policy is in force.
845    pub fn static_v0() -> Self {
846        Self {
847            retry: RetryPolicyParameters {
848                base_delay_ms: crate::durable::BASE_RETRY_DELAY_MS,
849                max_delay_ms: crate::durable::MAX_RETRY_DELAY_MS,
850                max_attempts: 3,
851            },
852            timeout: TimeoutPolicyParameters {
853                default_millis: None,
854                max_millis: None,
855            },
856            concurrency: ConcurrencyPolicyParameters { max_parallel: None },
857        }
858    }
859
860    /// This policy with one family's parameters replaced by `parameters`
861    /// (parsed as that family's parameter type).
862    ///
863    /// This is how a promoted policy candidate — whose content is a family
864    /// plus a free-form parameter value — becomes a concrete
865    /// `ExecutorPolicy`: the candidate's parameters are validated against
866    /// the family's contract and overlaid onto the policy that was active
867    /// (the floor when nothing was promoted yet). Families without a v1
868    /// parameter contract ([`DecisionFamily::WorkerPlacement`],
869    /// [`DecisionFamily::CheckpointPlacement`]) are rejected.
870    pub fn with_family_parameters(
871        &self,
872        family: DecisionFamily,
873        parameters: serde_json::Value,
874    ) -> crate::error::Result<Self> {
875        let mut policy = *self;
876        match family {
877            DecisionFamily::Retry => {
878                policy.retry = serde_json::from_value(parameters).map_err(|e| {
879                    RustyError::InvalidUpdate(format!(
880                        "retry policy parameters do not match the contract: {e}"
881                    ))
882                })?;
883            }
884            DecisionFamily::Timeout => {
885                policy.timeout = serde_json::from_value(parameters).map_err(|e| {
886                    RustyError::InvalidUpdate(format!(
887                        "timeout policy parameters do not match the contract: {e}"
888                    ))
889                })?;
890            }
891            DecisionFamily::Concurrency => {
892                policy.concurrency = serde_json::from_value(parameters).map_err(|e| {
893                    RustyError::InvalidUpdate(format!(
894                        "concurrency policy parameters do not match the contract: {e}"
895                    ))
896                })?;
897            }
898            other => {
899                return Err(RustyError::InvalidUpdate(format!(
900                    "decision family `{other:?}` has no executor-policy parameter contract \
901                     in this version"
902                )));
903            }
904        }
905        Ok(policy)
906    }
907}
908
909/// Derive the content-addressed version of an [`ExecutorPolicy`]:
910/// `policy-{first 12 hex of sha256(canonical_json(policy))}`.
911///
912/// Content addressing is what makes the registry's immutability enforceable:
913/// a version string *is* a commitment to one exact parameter set, so
914/// "register a different body under an existing version" is detectable as a
915/// conflict rather than silently overwriting behavior. The static floor is
916/// exempt — it keeps its human-readable [`PolicyVersion::STATIC_V0`] name
917/// because it predates the registry and never needs registration.
918pub fn derive_policy_version(policy: &ExecutorPolicy) -> crate::error::Result<PolicyVersion> {
919    let bytes = serde_json::to_vec(policy)?;
920    let hash = sha256_hex(&bytes);
921    Ok(PolicyVersion::new(format!("policy-{}", &hash[..12])))
922}
923
924/// A capsule version pin — the R0.7 placeholder for R0.9's capsule manifest
925/// identity.
926///
927/// R0.9 gives capsules a full manifest (build digest, declared interface,
928/// capability grants); R0.7 pins only the version string so a run's manifest
929/// can already record *which* capsule build influenced it. Typing it now —
930/// rather than storing a bare string — localizes the R0.9 evolution to one
931/// type instead of every consumer of the manifest map. Transparent over
932/// `String`: the wire shape is the version string itself.
933#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
934#[serde(transparent)]
935pub struct CapsuleVersion(pub String);
936
937impl CapsuleVersion {
938    /// Wrap a version string.
939    pub fn new(version: impl Into<String>) -> Self {
940        Self(version.into())
941    }
942
943    /// The version string.
944    pub fn as_str(&self) -> &str {
945        &self.0
946    }
947}
948
949impl std::fmt::Display for CapsuleVersion {
950    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
951        f.write_str(&self.0)
952    }
953}
954
955/// The versioned run manifest (R0.7): everything beyond the graph itself
956/// that can influence a run, pinned at checkpoint time.
957///
958/// The R0.5 header pins the checkpoint format, the graph version and
959/// topology, and the executor policy — but a run's behavior is also shaped
960/// by its prompts, its tools' schemas, its model and parameters, and (as
961/// they land) its memory schema and capsule builds. The manifest pins all of
962/// them by content address (lowercase hex SHA-256, the one hashing primitive
963/// shared with artifact references and journal heads), so a checkpoint
964/// answers not just "which graph produced this?" but "which *configuration
965/// of everything else* produced this?".
966///
967/// **Upgrade safety.** Pinning is what lets long-running agents survive
968/// platform upgrades: a run resumed from a checkpoint keeps executing
969/// against the versions its manifest pins, while new versions shadow for new
970/// runs. An absent field means *unpinned*, never a default — consumers must
971/// not invent one. Migration contracts between pinned versions (when a run
972/// may move from pin A to pin B, and how) are R1.0's stability work,
973/// deliberately: this wave records the evidence migrations will be judged
974/// against.
975///
976/// Every field is optional and omitted from the wire when unset
977/// (`skip_serializing_if`), so a header carrying no manifest — or a manifest
978/// carrying only some pins — produces no shape change for pre-R0.7 readers.
979#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
980pub struct RunManifest {
981    /// Prompt digests: prompt name → SHA-256 of the exact prompt text
982    /// (`sha256_hex` over its UTF-8 bytes). Prompt text, not a name alone,
983    /// because an edited prompt under an unchanged name is exactly the drift
984    /// the manifest exists to catch.
985    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
986    pub prompts: BTreeMap<String, String>,
987
988    /// Tool schema digests: tool name → SHA-256 of the canonical
989    /// `serde_json` serialization of its parameters schema (the same
990    /// canonicalization [`PayloadRef::content_hash`] relies on: object keys
991    /// sort deterministically, so equal schemas hash equal).
992    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
993    pub tool_schemas: BTreeMap<String, String>,
994
995    /// The model identifier the run pinned (a provider-precise string such
996    /// as `gpt-5.2-2026-06-01`, not a floating alias like `gpt-5.2-latest` —
997    /// an alias is not a pin).
998    #[serde(default, skip_serializing_if = "Option::is_none")]
999    pub model: Option<String>,
1000
1001    /// SHA-256 digest of the canonical JSON of the model parameters
1002    /// (temperature, seed, token limits, ...) the run pinned. A digest
1003    /// rather than the parameters themselves: the header stays cheap to scan
1004    /// and parameter sets with secrets-adjacent values never land in
1005    /// evidence verbatim.
1006    #[serde(default, skip_serializing_if = "Option::is_none")]
1007    pub model_params: Option<String>,
1008
1009    /// The memory schema version the run pinned (R0.8's memory record
1010    /// model). Declared in R0.7 so runs that outlive the R0.8 upgrade can
1011    /// still be interpreted against the schema their memories were written
1012    /// under.
1013    #[serde(default, skip_serializing_if = "Option::is_none")]
1014    pub memory_schema: Option<String>,
1015
1016    /// Capsule version pins: capsule name → [`CapsuleVersion`] (placeholder
1017    /// for R0.9's capsule manifests — see that type's docs).
1018    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1019    pub capsules: BTreeMap<String, CapsuleVersion>,
1020}
1021
1022impl RunManifest {
1023    /// An empty manifest: nothing pinned. Equivalent to [`Default`].
1024    pub fn new() -> Self {
1025        Self::default()
1026    }
1027
1028    /// Pin a prompt by content: records the SHA-256 of its exact UTF-8 text
1029    /// under `name`.
1030    pub fn pin_prompt(mut self, name: impl Into<String>, prompt: &str) -> Self {
1031        self.prompts
1032            .insert(name.into(), sha256_hex(prompt.as_bytes()));
1033        self
1034    }
1035
1036    /// Pin a tool's parameters schema by content: records the SHA-256 of its
1037    /// canonical `serde_json` serialization under `name`.
1038    pub fn pin_tool_schema(mut self, name: impl Into<String>, schema: &Value) -> Self {
1039        self.tool_schemas
1040            .insert(name.into(), canonical_json_digest(schema));
1041        self
1042    }
1043
1044    /// Pin the model identifier and the content digest of its parameters.
1045    pub fn pin_model(mut self, model: impl Into<String>, parameters: &Value) -> Self {
1046        self.model = Some(model.into());
1047        self.model_params = Some(canonical_json_digest(parameters));
1048        self
1049    }
1050
1051    /// Pin the memory schema version (R0.8's record model; see the field
1052    /// docs).
1053    pub fn with_memory_schema(mut self, version: impl Into<String>) -> Self {
1054        self.memory_schema = Some(version.into());
1055        self
1056    }
1057
1058    /// Pin a capsule version (R0.9 placeholder; see [`CapsuleVersion`]).
1059    pub fn pin_capsule(mut self, name: impl Into<String>, version: CapsuleVersion) -> Self {
1060        self.capsules.insert(name.into(), version);
1061        self
1062    }
1063}
1064
1065/// The value with every object map rebuilt in sorted key order,
1066/// recursively — the canonical form every content hash in this crate
1067/// covers.
1068///
1069/// `serde_json`'s default map is BTreeMap-backed, so serializing a `Value`
1070/// already emits object keys sorted; under the default backend this
1071/// transform is an identity and every pre-existing hash is preserved
1072/// byte-for-byte. The hazard is serde_json's `preserve_order` feature,
1073/// which `cedar-policy-core` (R0.9's Cedar engine, behind the server's
1074/// `capsules` feature) enables unconditionally: feature unification then
1075/// swaps the workspace-wide map for an insertion-ordered IndexMap, and
1076/// the same logical payload serializes — and hashes — differently
1077/// depending on the order its keys happened to be inserted. Routing every
1078/// hash through this canonical form keeps content addresses stable across
1079/// both map backends and across builds with and without the feature.
1080pub(crate) fn canonicalize_value(value: &Value) -> Value {
1081    match value {
1082        Value::Object(map) => {
1083            let mut entries: Vec<(&String, &Value)> = map.iter().collect();
1084            entries.sort_by_key(|(key, _)| *key);
1085            Value::Object(
1086                entries
1087                    .into_iter()
1088                    .map(|(key, item)| (key.clone(), canonicalize_value(item)))
1089                    .collect(),
1090            )
1091        }
1092        Value::Array(items) => Value::Array(items.iter().map(canonicalize_value).collect()),
1093        scalar => scalar.clone(),
1094    }
1095}
1096
1097/// SHA-256 of the canonical `serde_json` serialization of `value` — the
1098/// digest convention shared by every manifest pin over JSON content.
1099fn canonical_json_digest(value: &Value) -> String {
1100    // Serializing a `Value` is infallible in practice (its maps always have
1101    // string keys); `PayloadRef::content_hash` documents why the result is
1102    // canonical.
1103    let bytes = serde_json::to_vec(&canonicalize_value(value))
1104        .expect("a serde_json::Value always serializes");
1105    sha256_hex(&bytes)
1106}
1107
1108/// The provenance header stamped into every checkpoint.
1109///
1110/// Answers, for any stored checkpoint: which checkpoint format wrote it
1111/// (`format_version`), which graph produced it (`graph_version` +
1112/// `graph_hash`), under which policy (`policy_version`), and where it sits
1113/// on the run's logical clock. Without this, a checkpoint is data; with it,
1114/// a checkpoint is interpretable evidence — replay can refuse (or migrate)
1115/// checkpoints whose format or graph no longer matches.
1116///
1117/// Added to `Checkpoint` with serde defaults: checkpoints written before
1118/// R0.5 (no header) deserialize into [`CheckpointHeader::default`]. R0.7
1119/// extends the header additively with the [`RunManifest`] pin set — same
1120/// rule: unset fields stay absent from the wire and old headers keep
1121/// deserializing.
1122#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1123pub struct CheckpointHeader {
1124    /// Checkpoint envelope format version; [`CURRENT_FORMAT_VERSION`] for
1125    /// anything written now.
1126    pub format_version: u32,
1127
1128    /// Application-declared graph version (via `RunConfig::with_graph_version`),
1129    /// or `"unversioned"` when the application does not version its graph.
1130    pub graph_version: String,
1131
1132    /// SHA-256 content hash of the compiled graph topology (node names and
1133    /// edge shape — see `Graph::topology_hash`). Detects graph drift between
1134    /// a checkpoint and the code about to resume it; semantic node-body
1135    /// changes are the application's responsibility via `graph_version`.
1136    pub graph_hash: String,
1137
1138    /// The executor policy active when the checkpoint was written.
1139    pub policy_version: PolicyVersion,
1140
1141    /// The run's logical clock value (milliseconds) at creation. Under the
1142    /// default system clock this is epoch milliseconds; under a logical
1143    /// clock it is the deterministic tick — either way it is the ordering
1144    /// and replay handle, not wall time.
1145    pub logical_clock: u64,
1146
1147    /// The versioned run manifest (R0.7): prompts, tool schemas, model and
1148    /// parameters, memory schema, and capsule versions pinned for the run —
1149    /// see [`RunManifest`] for the upgrade-safety contract. Stamped from
1150    /// `RunConfig::with_manifest` at checkpoint time.
1151    ///
1152    /// Additive: `None` (the default) is absent from the wire, so headers
1153    /// written before R0.7 — and headers of runs that pin nothing — keep
1154    /// their exact R0.5 shape.
1155    #[serde(default, skip_serializing_if = "Option::is_none")]
1156    pub manifest: Option<RunManifest>,
1157}
1158
1159impl Default for CheckpointHeader {
1160    /// The header for a checkpoint written without run context: current
1161    /// format, unversioned/empty graph identity, static policy, clock zero,
1162    /// no manifest. Also the deserialization fallback for pre-R0.5
1163    /// checkpoints.
1164    fn default() -> Self {
1165        Self {
1166            format_version: CURRENT_FORMAT_VERSION,
1167            graph_version: "unversioned".to_owned(),
1168            graph_hash: String::new(),
1169            policy_version: PolicyVersion::default(),
1170            logical_clock: 0,
1171            manifest: None,
1172        }
1173    }
1174}
1175
1176/// A reference to the journal head at a checkpoint boundary, stamped into
1177/// the checkpoint so evidence and state travel together.
1178///
1179/// The hash is the journal's running head hash (chained SHA-256 over
1180/// recorded events), so a checkpoint pins not just *how many* events existed
1181/// but *which* events — tamper-evident linkage between state and evidence.
1182#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1183pub struct JournalRef {
1184    /// Number of events in the journal at the boundary.
1185    pub events: u64,
1186
1187    /// Journal head hash (chained SHA-256) at the boundary.
1188    pub sha256: String,
1189}
1190
1191#[cfg(test)]
1192mod tests {
1193    use super::*;
1194    use serde_json::json;
1195
1196    #[test]
1197    fn sha256_hex_is_stable_and_lowercase() {
1198        // SHA-256 of the empty input, pinned against the published digest.
1199        assert_eq!(
1200            sha256_hex(b""),
1201            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
1202        );
1203        assert_eq!(sha256_hex(b"abc").len(), 64);
1204    }
1205
1206    #[test]
1207    fn policy_version_default_is_static_floor() {
1208        assert_eq!(PolicyVersion::default().as_str(), PolicyVersion::STATIC_V0);
1209        // Transparent newtype: serializes as a bare string.
1210        assert_eq!(
1211            serde_json::to_value(PolicyVersion::default()).unwrap(),
1212            json!("static-v0")
1213        );
1214    }
1215
1216    #[test]
1217    fn executor_policy_static_floor_mirrors_the_durable_constants() {
1218        let floor = ExecutorPolicy::static_v0();
1219        assert_eq!(
1220            floor.retry.base_delay_ms,
1221            crate::durable::BASE_RETRY_DELAY_MS
1222        );
1223        assert_eq!(floor.retry.max_delay_ms, crate::durable::MAX_RETRY_DELAY_MS);
1224        // The floor pins the server's default attempt budget; timeout and
1225        // concurrency are uncapped — the honest encoding of "no policy".
1226        assert_eq!(floor.retry.max_attempts, 3);
1227        assert!(floor.timeout.default_millis.is_none());
1228        assert!(floor.timeout.max_millis.is_none());
1229        assert!(floor.concurrency.max_parallel.is_none());
1230        // Unset options stay absent from the wire.
1231        let wire = serde_json::to_value(floor).unwrap();
1232        assert_eq!(wire["timeout"], json!({}));
1233        assert_eq!(wire["concurrency"], json!({}));
1234    }
1235
1236    #[test]
1237    fn derive_policy_version_is_content_addressed() {
1238        let policy = ExecutorPolicy::static_v0()
1239            .with_family_parameters(
1240                DecisionFamily::Retry,
1241                json!({"base_delay_ms": 500, "max_delay_ms": 60_000, "max_attempts": 5}),
1242            )
1243            .unwrap();
1244        let first = derive_policy_version(&policy).unwrap();
1245        let again = derive_policy_version(&policy).unwrap();
1246        assert_eq!(first, again, "version derivation must be deterministic");
1247        assert!(
1248            first.as_str().starts_with("policy-"),
1249            "derived versions carry the policy- prefix: {first}"
1250        );
1251        assert_eq!(first.as_str().len(), "policy-".len() + 12);
1252
1253        // Any parameter change is a different version — that is what makes
1254        // registry immutability enforceable.
1255        let changed = policy
1256            .with_family_parameters(
1257                DecisionFamily::Retry,
1258                json!({"base_delay_ms": 500, "max_delay_ms": 60_000, "max_attempts": 6}),
1259            )
1260            .unwrap();
1261        assert_ne!(first, derive_policy_version(&changed).unwrap());
1262    }
1263
1264    #[test]
1265    fn with_family_parameters_validates_and_overlays() {
1266        let base = ExecutorPolicy::static_v0();
1267
1268        // Timeout and concurrency families parse their own contracts.
1269        let with_timeout = base
1270            .with_family_parameters(
1271                DecisionFamily::Timeout,
1272                json!({"default_millis": 30_000, "max_millis": 120_000}),
1273            )
1274            .unwrap();
1275        assert_eq!(with_timeout.timeout.default_millis, Some(30_000));
1276        assert_eq!(with_timeout.timeout.max_millis, Some(120_000));
1277        // Untouched families keep the base values.
1278        assert_eq!(with_timeout.retry, base.retry);
1279
1280        let with_concurrency = base
1281            .with_family_parameters(DecisionFamily::Concurrency, json!({"max_parallel": 8}))
1282            .unwrap();
1283        assert_eq!(with_concurrency.concurrency.max_parallel, Some(8));
1284
1285        // A malformed body is rejected with the family named.
1286        let err = base
1287            .with_family_parameters(DecisionFamily::Retry, json!({"base_delay_ms": "fast"}))
1288            .unwrap_err();
1289        assert!(err.to_string().contains("retry policy parameters"), "{err}");
1290
1291        // Families without a v1 parameter contract are rejected.
1292        for family in [
1293            DecisionFamily::WorkerPlacement,
1294            DecisionFamily::CheckpointPlacement,
1295        ] {
1296            let err = base.with_family_parameters(family, json!({})).unwrap_err();
1297            assert!(
1298                err.to_string().contains("no executor-policy parameter"),
1299                "{err}"
1300            );
1301        }
1302    }
1303
1304    #[test]
1305    fn payload_ref_content_hash_agrees_across_representations() {
1306        let value = json!({"b": 1, "a": [2, 3]});
1307        let bytes = serde_json::to_vec(&value).unwrap();
1308        let inline = PayloadRef::inline(value);
1309        let referenced = PayloadRef::Artifact(ArtifactRef {
1310            sha256: sha256_hex(&bytes),
1311            bytes: bytes.len() as u64,
1312        });
1313        assert_eq!(
1314            inline.content_hash().unwrap(),
1315            referenced.content_hash().unwrap()
1316        );
1317    }
1318
1319    #[test]
1320    fn effect_repeatability_ladder() {
1321        assert!(Effect::Pure.is_freely_repeatable());
1322        assert!(Effect::ReadOnly.is_freely_repeatable());
1323        assert!(Effect::Idempotent.is_freely_repeatable());
1324        assert!(!Effect::Compensatable.is_freely_repeatable());
1325        assert!(!Effect::NonIdempotent.is_freely_repeatable());
1326    }
1327
1328    #[test]
1329    fn contracts_serde_roundtrip() {
1330        let event = RunEvent {
1331            id: "r1:7".into(),
1332            run_id: "r1".into(),
1333            thread_id: "t1".into(),
1334            node_id: Some("agent".into()),
1335            seq: 7,
1336            kind: RunEventKind::ModelCall,
1337            effect: Effect::NonIdempotent,
1338            input: Some(PayloadRef::inline(json!({"messages": []}))),
1339            output: Some(PayloadRef::Artifact(ArtifactRef {
1340                sha256: sha256_hex(b"response"),
1341                bytes: 8,
1342            })),
1343            latency_ms: Some(42),
1344            tokens: Some(Usage {
1345                prompt_tokens: 10,
1346                completion_tokens: 5,
1347                total_tokens: 15,
1348            }),
1349            cost_usd: Some(0.0001),
1350            status: EventStatus::Ok,
1351            parent: Some("r1:3".into()),
1352            recorded_at: DateTime::<Utc>::from_timestamp_millis(1_000).unwrap(),
1353        };
1354        let back: RunEvent = serde_json::from_str(&serde_json::to_string(&event).unwrap()).unwrap();
1355        assert_eq!(event, back);
1356
1357        let decision = DecisionEvent {
1358            id: "r1:d0".into(),
1359            run_id: "r1".into(),
1360            thread_id: "t1".into(),
1361            seq: 0,
1362            family: DecisionFamily::Retry,
1363            features: Map::from_iter([("failure_class".to_owned(), json!("timeout"))]),
1364            legal_actions: vec![DecisionAction::Retry { attempt: 1 }, DecisionAction::Abort],
1365            selected: DecisionAction::Retry { attempt: 1 },
1366            propensity: 0.75,
1367            policy_version: PolicyVersion::default(),
1368            outcome: None,
1369            decided_at: DateTime::<Utc>::from_timestamp_millis(1_000).unwrap(),
1370        };
1371        let back: DecisionEvent =
1372            serde_json::from_str(&serde_json::to_string(&decision).unwrap()).unwrap();
1373        assert_eq!(decision, back);
1374    }
1375
1376    #[test]
1377    fn checkpoint_header_default_matches_pre_r05_fallback() {
1378        let header = CheckpointHeader::default();
1379        assert_eq!(header.format_version, CURRENT_FORMAT_VERSION);
1380        assert_eq!(header.graph_version, "unversioned");
1381        assert_eq!(header.policy_version, PolicyVersion::default());
1382        assert_eq!(header.logical_clock, 0);
1383        assert_eq!(header.manifest, None);
1384    }
1385
1386    #[test]
1387    fn manifest_digests_are_stable_content_addresses() {
1388        // Constants computed independently (SHA-256 of the exact bytes): the
1389        // pins are content addresses, so their stability across releases is
1390        // the contract — a drifting digest would silently split runs from
1391        // their own evidence.
1392        let manifest = RunManifest::new()
1393            .pin_prompt("system", "You are a careful research agent.")
1394            .pin_tool_schema(
1395                "search",
1396                &json!({"type": "object", "properties": {"query": {"type": "string"}}}),
1397            )
1398            .pin_model(
1399                "gpt-5.2-2026-06-01",
1400                &json!({"temperature": 0, "seed": 42, "max_tokens": 512}),
1401            )
1402            .with_memory_schema("memory-v1")
1403            .pin_capsule("researcher", CapsuleVersion::new("1.4.0"));
1404
1405        assert_eq!(
1406            manifest.prompts["system"],
1407            "edff20fbc61c032a9206bdc94aec3b70e05ab953383972b267b83957d9ba7bfe"
1408        );
1409        assert_eq!(
1410            manifest.tool_schemas["search"],
1411            "094ec29d007cce150c65abf0756d79ad5b62a1acfdb6e0841f69f1377ef41761"
1412        );
1413        assert_eq!(
1414            manifest.model_params.as_deref(),
1415            Some("fc004364a674799b07f8e4e6323ad74398745607ae3bd955e0d9c1d7529a0762")
1416        );
1417        assert_eq!(manifest.model.as_deref(), Some("gpt-5.2-2026-06-01"));
1418        assert_eq!(manifest.memory_schema.as_deref(), Some("memory-v1"));
1419        assert_eq!(manifest.capsules["researcher"].as_str(), "1.4.0");
1420
1421        // Key order in the source JSON must not matter: canonicalization
1422        // sorts object keys, so semantically equal schemas pin equal.
1423        let reordered = RunManifest::new().pin_tool_schema(
1424            "search",
1425            &json!({"properties": {"query": {"type": "string"}}, "type": "object"}),
1426        );
1427        assert_eq!(manifest.tool_schemas, reordered.tool_schemas);
1428    }
1429
1430    #[test]
1431    fn manifest_serde_roundtrip_and_sparse_wire_shape() {
1432        let manifest = RunManifest::new()
1433            .pin_prompt("system", "Be brief.")
1434            .pin_model("model-x", &json!({"temperature": 0.5}));
1435        let back: RunManifest =
1436            serde_json::from_str(&serde_json::to_string(&manifest).unwrap()).unwrap();
1437        assert_eq!(manifest, back);
1438
1439        // Sparse pins stay sparse on the wire: unset fields are absent, not
1440        // null or empty — pre-R0.7 readers see no new keys at all.
1441        let value = serde_json::to_value(&manifest).unwrap();
1442        assert!(value.get("tool_schemas").is_none());
1443        assert!(value.get("memory_schema").is_none());
1444        assert!(value.get("capsules").is_none());
1445        assert!(value.get("prompts").is_some());
1446
1447        // An empty manifest serializes to an empty object, and a header that
1448        // carries no manifest omits the field entirely.
1449        assert_eq!(serde_json::to_value(RunManifest::new()).unwrap(), json!({}));
1450        let header = CheckpointHeader::default();
1451        assert!(serde_json::to_value(&header)
1452            .unwrap()
1453            .get("manifest")
1454            .is_none());
1455    }
1456
1457    #[test]
1458    fn r05_header_without_manifest_still_loads() {
1459        // The R0.5 shape — exactly what the golden file pins — deserializes
1460        // into the extended header with the manifest unset.
1461        let r05_shape = json!({
1462            "format_version": 1,
1463            "graph_version": "react-v3",
1464            "graph_hash": "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae",
1465            "policy_version": "static-v0",
1466            "logical_clock": 1750000000000u64,
1467        });
1468        let header: CheckpointHeader = serde_json::from_value(r05_shape).unwrap();
1469        assert_eq!(header.manifest, None);
1470        assert_eq!(header.format_version, CURRENT_FORMAT_VERSION);
1471
1472        // And a header carrying a manifest round-trips it.
1473        let extended = CheckpointHeader {
1474            manifest: Some(RunManifest::new().with_memory_schema("memory-v1")),
1475            ..header
1476        };
1477        let back: CheckpointHeader =
1478            serde_json::from_str(&serde_json::to_string(&extended).unwrap()).unwrap();
1479        assert_eq!(extended, back);
1480    }
1481
1482    #[test]
1483    fn effect_receipt_effect_id_is_additive() {
1484        let receipt = EffectReceipt {
1485            provider: "stripe".into(),
1486            provider_id: "ch_3PKd".into(),
1487            idempotency_key: "run-1:charge:7".into(),
1488            task_id: None,
1489            effect_id: None,
1490        };
1491        // Unset: absent on the wire — pre-R0.7 receipts see no shape change.
1492        let value = serde_json::to_value(&receipt).unwrap();
1493        assert!(value.get("effect_id").is_none());
1494
1495        // Set: carried as a bare digest string, surviving the round-trip.
1496        let with_id = EffectReceipt {
1497            effect_id: Some(
1498                "9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673ca7".into(),
1499            ),
1500            ..receipt
1501        };
1502        let back: EffectReceipt =
1503            serde_json::from_str(&serde_json::to_string(&with_id).unwrap()).unwrap();
1504        assert_eq!(with_id, back);
1505    }
1506}