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    /// A registry artifact was resolved into a run at admission (R0.11
557    /// Extension Plane, wave 2): the run declared named configuration
558    /// artifacts at submission, and each one resolved through its
559    /// environment-tagged version pointer to the candidate the run then
560    /// pinned. An [`Effect::ReadOnly`] record (a registry lookup), the
561    /// [`RunEventKind::CapsuleResolved`] precedent applied to configuration. Output
562    /// carries the journaled [`crate::registry::ConfigResolution`] — the
563    /// artifact, the environment tag, the candidate id, the pointer slot
564    /// that admitted it (active or canary), and the digest the manifest
565    /// pins. This is the digest ↔ version join the manifest alone cannot
566    /// express: the manifest's wire shape stays frozen (digests only),
567    /// and "which candidate produced this pin" reads from here — the
568    /// event sits in the signature-covered journal, so the audit walk
569    /// signed receipt → manifest pin → resolution event → candidate →
570    /// author is covered end to end.
571    ConfigResolved,
572
573    /// A broker connection was registered (R0.11 Extension Plane, wave
574    /// 3): a named, tenant-scoped binding of a provider account to its
575    /// consent scope set landed in the broker. Journaled into the
576    /// deployment's broker evidence chain (the `receipt-keys` precedent
577    /// applied to a second control plane). An [`Effect::Pure`] record:
578    /// registration is local broker state, so the event is the lineage
579    /// evidence. Output carries the
580    /// [`crate::broker::ConnectionRecord`] — metadata by construction;
581    /// the credential bytes live only in the sealed store envelope and
582    /// can never appear here.
583    ConnectionRegistered,
584
585    /// A connection's consent act was recorded (R0.11 wave 3): the
586    /// human's grant at the provider, written down as the connection's
587    /// new scope ceiling. An [`Effect::Pure`] record. Output carries the
588    /// journaled [`crate::broker::ConnectionConsent`] — the connection,
589    /// the subject, and the recorded scope set. Scope widening is only
590    /// ever this event: a new consent act, journaled; there is no silent
591    /// widening path.
592    ConnectionConsented,
593
594    /// A connection's token material rotated beneath an unchanged
595    /// consent set (R0.11 wave 3): a recorded credential rotation. An
596    /// [`Effect::Pure`] record. Output carries the journaled
597    /// [`crate::broker::ConnectionRefresh`] — the connection and the new
598    /// expiry, never the bytes. Rotation changes nothing a run pinned:
599    /// the pin names the connection id and the consent set, not the
600    /// secret of the moment.
601    ConnectionRefreshed,
602
603    /// A connection was revoked (R0.11 wave 3). The status flip and this
604    /// event commit together, and resolution reads live connection
605    /// state, so revocation takes effect at the next tool call — not the
606    /// next deploy. An [`Effect::Pure`] record. Output carries the
607    /// journaled [`crate::broker::ConnectionRevocation`]: the connection
608    /// and the grant that stopped holding.
609    ConnectionRevoked,
610
611    /// A credential handle was issued (R0.11 wave 3): a tool (or
612    /// capsule) declaring a credential need received a short-lived,
613    /// opaque handle — scope-narrowed against the consent ceiling at
614    /// issuance. An [`Effect::Pure`] record. Output carries the
615    /// journaled [`crate::broker::HandleIssuance`] — the full claims, so
616    /// the run's evidence pins the connection id and the consent scope
617    /// set it resolved.
618    CredentialHandleIssued,
619
620    /// A credential handle was resolved at use (R0.11 wave 3): the
621    /// broker checked live connection state, expiry, and scope coverage,
622    /// and handed the credential to the host-side connector. An
623    /// [`Effect::ReadOnly`] record (the resolution itself performs no
624    /// external effect — the authenticated call it enables is the
625    /// connector's own evidence). Output carries the journaled
626    /// [`crate::broker::CredentialUse`] — handle, connection, scopes
627    /// checked — never bytes (the `CapsuleCall` precedent).
628    CredentialUse,
629
630    /// A handle issuance or resolution was refused (R0.11 wave 3):
631    /// revoked connection, expired handle, scope beyond the bound set,
632    /// `needs_reauth`, unknown handle or connection, or a broker that
633    /// could not perform the check. An [`Effect::Pure`] record: nothing
634    /// executed, so there is no external effect to classify — the event
635    /// is the evidence that nothing happened (the `CapsuleDenied`
636    /// precedent). Output carries the journaled
637    /// [`crate::broker::BrokerDenial`], attributable to the connection
638    /// and the grant — never the bytes.
639    CredentialDenied,
640
641    /// A connection's refresh path failed terminally and its status
642    /// flipped to `needs_reauth` (R0.11 wave 4): the provider's
643    /// `invalid_grant` (or an expired refresh token) means a human must
644    /// record a new consent act before the connection serves again. The
645    /// flip and this event commit together, and calls fail closed with a
646    /// typed re-auth signal from the next use — never silent retries with
647    /// stale material, because a stale credential retried looks exactly
648    /// like an attack retried. An [`Effect::Pure`] record. Output carries
649    /// the journaled [`crate::broker::ConnectionReauthRequired`] — the
650    /// connection, the classified failure that decided the flip, and the
651    /// consent set that stopped being servable.
652    ConnectionNeedsReauth,
653}
654
655/// One recorded fact about a run: the Flight Recorder's atomic evidence.
656///
657/// Events form a causal chain via `parent` (the event that caused this one —
658/// e.g. a node input's parent is its super-step start), and a total order
659/// via `seq`, a monotonic sequence number assigned by the journal at record
660/// time. `seq` — not wall time — is the ordering guarantee: recorded runs
661/// re-driven against a seeded clock reproduce the same sequence.
662///
663/// Event ids are `{run_id}:{seq}` — deterministic for a given journal, so a
664/// re-driven run with the same seed mints the same ids.
665#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
666pub struct RunEvent {
667    /// Deterministic event id (`{run_id}:{seq}`).
668    pub id: String,
669
670    /// The run this event belongs to. One `Executor::run` call = one run id.
671    pub run_id: String,
672
673    /// The thread (session) the run belongs to.
674    pub thread_id: String,
675
676    /// The node this event is about, where applicable (`None` for run-wide
677    /// events such as super-step boundaries and checkpoint writes).
678    pub node_id: Option<String>,
679
680    /// Monotonic sequence number within the journal, assigned at record
681    /// time. The total order of the run's evidence.
682    pub seq: u64,
683
684    /// What happened.
685    pub kind: RunEventKind,
686
687    /// The declared effect classification of whatever produced this event.
688    pub effect: Effect,
689
690    /// Input payload (arguments, request, snapshot), inline or referenced.
691    pub input: Option<PayloadRef>,
692
693    /// Output payload (result, response, updates), inline or referenced.
694    pub output: Option<PayloadRef>,
695
696    /// Wall/logical latency of the recorded operation in milliseconds, when
697    /// measured. Sourced from the run's clock, so a logical clock yields
698    /// reproducible values.
699    pub latency_ms: Option<u64>,
700
701    /// Token usage for model calls, when the provider reported it.
702    pub tokens: Option<Usage>,
703
704    /// Monetary cost in USD for the recorded operation, when known. `f64`
705    /// micro-costs are fine here: this is evidence, not accounting — the
706    /// ledger aggregates elsewhere.
707    pub cost_usd: Option<f64>,
708
709    /// How the event ended.
710    pub status: EventStatus,
711
712    /// The id of the event that caused this one, when there is one. A node
713    /// input's parent is its super-step start; a tool call's parent is the
714    /// node that invoked it; a checkpoint write's parent is the routing
715    /// decision that ended the step.
716    pub parent: Option<String>,
717
718    /// When the event was recorded, read from the run's clock (system wall
719    /// clock by default; the configured logical clock for seeded runs).
720    pub recorded_at: DateTime<Utc>,
721}
722
723/// The family a [`DecisionEvent`] belongs to: the closed set of executor
724/// decisions a policy may learn.
725///
726/// The set mirrors the R0.10 priority order. Deliberately absent: model and
727/// agent selection (a governed semantic policy, not an automatic one) and
728/// interrupt policy (the prevented-error counterfactual is unobservable).
729#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
730#[serde(rename_all = "snake_case")]
731pub enum DecisionFamily {
732    /// Whether to re-attempt a failed effect, and with what backoff.
733    Retry,
734    /// What timeout/stopping bound to apply to an operation.
735    Timeout,
736    /// Which equivalent worker a remote execution is placed on.
737    WorkerPlacement,
738    /// Concurrency/backpressure limits for parallel execution.
739    Concurrency,
740    /// Whether a checkpoint is written at a given boundary (headroom gated
741    /// on the R0.5 experiment: mandatory after non-idempotent effects).
742    CheckpointPlacement,
743}
744
745/// One action in a [`DecisionEvent`]'s legal set. Closed enum: learned
746/// policies choose among declared actions, never free-form outputs — that is
747/// what keeps the learning problem mechanical (dense signals, closed spaces)
748/// instead of semantic.
749#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
750#[serde(tag = "action", rename_all = "snake_case")]
751pub enum DecisionAction {
752    /// Re-attempt the failed operation; `attempt` is the 1-based retry
753    /// ordinal.
754    Retry {
755        /// The 1-based retry ordinal being taken.
756        attempt: u32,
757    },
758    /// Give up on the operation and fail the run/step.
759    Abort,
760    /// Apply a timeout of `millis` to the operation.
761    SetTimeout {
762        /// The timeout bound in milliseconds.
763        millis: u64,
764    },
765    /// Place a remote execution on worker `worker`.
766    SelectWorker {
767        /// The chosen worker's identity.
768        worker: String,
769    },
770    /// Cap concurrent executions at `limit`.
771    SetConcurrency {
772        /// The maximum number of concurrent executions.
773        limit: u32,
774    },
775    /// Persist a checkpoint at this boundary.
776    WriteCheckpoint,
777    /// Skip the checkpoint at this boundary.
778    SkipCheckpoint,
779}
780
781/// How a decided action turned out, filled in when the affected operation
782/// completes. `None` on the wire until then — decisions and outcomes are
783/// recorded separately so in-flight decisions are visible.
784#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
785#[serde(rename_all = "snake_case")]
786pub enum DecisionOutcome {
787    /// The selected action led to completion.
788    Success,
789    /// The selected action did not lead to completion.
790    Failure,
791    /// The run was cancelled or superseded before the outcome materialized.
792    Cancelled,
793}
794
795/// The role a [`DecisionEvent`] played in its run (R0.10 wave 2, the runtime
796/// digital twin).
797///
798/// Additive to the R0.8 contract: absent from the wire when `None`, so every
799/// pre-twin decision — all of which were made by the policy whose action
800/// executed — keeps its exact shape. The twin is the first emitter that
801/// records *two* decisions at one decision point (the shadow pair), which is
802/// what makes the marker necessary: without it, off-policy evaluation cannot
803/// tell the decision that bound the world from the one that merely scored
804/// the same features.
805#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
806#[serde(rename_all = "snake_case")]
807pub enum DecisionRole {
808    /// The decision whose selected action executed (the floor's, in a twin
809    /// shadow run).
810    Acting,
811    /// A candidate policy's decision over the same features, journaled for
812    /// off-policy evidence but never executed. Well-posed evidence requires
813    /// the shadow's true propensity; a shadow exploring by seeded draw is a
814    /// stochastic policy with known propensities by construction.
815    Shadow,
816}
817
818/// One executor policy decision with everything offline learning needs to
819/// evaluate it.
820///
821/// The learning contract (R0.8+): given `features` and `legal_actions`, the
822/// policy named by `policy_version` chose `selected` with probability
823/// `propensity`. Propensity is assigned **at decision time**, never
824/// reconstructed — without it, off-policy evaluation (comparing a candidate
825/// policy against the recorded one) is impossible. `outcome` is `None`
826/// until the affected operation completes.
827///
828/// v1 froze this contract without emitters; R0.8 wave 4 wires the first
829/// emission point (the retry classifier, see
830/// [`crate::durable::retry_decision_event`]), journaled as
831/// [`RunEventKind::PolicyDecision`].
832#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
833pub struct DecisionEvent {
834    /// Deterministic decision id (`{run_id}:d{n}` — a separate sequence from
835    /// [`RunEvent`], so decision ids stay stable if event kinds are added).
836    pub id: String,
837
838    /// The run the decision was made in.
839    pub run_id: String,
840
841    /// The thread (session) the run belongs to.
842    pub thread_id: String,
843
844    /// Sequence number within the decision stream of this run.
845    pub seq: u64,
846
847    /// Which executor decision this is.
848    pub family: DecisionFamily,
849
850    /// The observation the policy decided from (latency percentiles, failure
851    /// class, queue depth, ...). Free-form JSON: the feature schema evolves
852    /// with the policy, but the envelope does not.
853    pub features: Map<String, Value>,
854
855    /// Every action that was legal at decision time. Off-policy evaluation
856    /// needs the full set, not just the chosen one.
857    pub legal_actions: Vec<DecisionAction>,
858
859    /// The action the policy took. Must be a member of `legal_actions`
860    /// (enforced by the policy plane, not by this type).
861    pub selected: DecisionAction,
862
863    /// The probability the active policy assigned to `selected` at decision
864    /// time, in `(0, 1]`. First-class because learning correctness depends
865    /// on it: importance weighting divides by the propensity.
866    pub propensity: f64,
867
868    /// The policy that made the decision.
869    pub policy_version: PolicyVersion,
870
871    /// Whether this decision's action executed or only scored the features
872    /// (R0.10 wave 2 shadow pairs; see [`DecisionRole`]). `None` — every
873    /// decision recorded before the twin — means acting: the only decisions
874    /// that existed were the ones that bound the world.
875    #[serde(default, skip_serializing_if = "Option::is_none")]
876    pub role: Option<DecisionRole>,
877
878    /// The result of the decision, `None` until completion.
879    pub outcome: Option<DecisionOutcome>,
880
881    /// When the decision was made, read from the run's clock.
882    pub decided_at: DateTime<Utc>,
883}
884
885/// The envelope any learned backoff cap must stay within, in milliseconds
886/// (one hour). The floor's own cap is [`crate::durable::MAX_RETRY_DELAY_MS`];
887/// a learned policy may widen the schedule, but never past the envelope —
888/// beyond it a stuck dependency parks work for longer than any operator
889/// would accept discovering by surprise.
890pub const POLICY_MAX_DELAY_ENVELOPE_MS: u64 = 3_600_000;
891
892/// The envelope any learned attempt budget must stay within. Ten attempts
893/// is already generous past the floor's three; beyond the envelope a
894/// policy is re-trying as a substitute for fixing the cause.
895pub const POLICY_MAX_ATTEMPTS_ENVELOPE: u32 = 10;
896
897/// The minimum timeout bound any policy may impose, in milliseconds.
898/// Below it ordinary work aborts early — a correctness hazard no policy
899/// may cross (the same floor the Wave 1 headroom experiment
900/// pre-registered). The twin's ladder shares this constant
901/// ([`crate::twin::MIN_TIMEOUT_RUNG_MS`] re-exports it) so the evaluation
902/// harness and the production contract enforce one bound.
903pub const MIN_TIMEOUT_RUNG_MS: u64 = 100;
904
905/// One backoff schedule: the numbers a retry decision is made with.
906///
907/// This is the shape both the flat policy-wide schedule and each per-class
908/// override take (R0.10 wave 3): the backoff draws from
909/// `[0, base_delay_ms * 2^(attempt-1)]` capped at `max_delay_ms`, and a
910/// retryable failure dead-letters once `attempt >= max_attempts`.
911#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
912pub struct BackoffParameters {
913    /// Base of the exponential backoff schedule, in milliseconds.
914    pub base_delay_ms: u64,
915
916    /// Cap of the backoff schedule, in milliseconds.
917    pub max_delay_ms: u64,
918
919    /// Attempt budget: the number of attempts counting the initial one.
920    /// `0` means no retries at all — every retryable failure dead-letters.
921    pub max_attempts: u32,
922}
923
924impl BackoffParameters {
925    /// The contract every backoff schedule — flat or per-class — must
926    /// satisfy: a positive base no larger than the cap, a cap inside the
927    /// declared envelope, and a budget inside the declared envelope.
928    /// Anything else is rejected (`Err`), so an out-of-envelope parameter
929    /// set can never become an active policy — the gate fails closed.
930    pub fn validate(&self) -> crate::error::Result<()> {
931        let invalid = |message: String| RustyError::InvalidUpdate(message);
932        if self.base_delay_ms == 0 {
933            return Err(invalid(
934                "backoff base_delay_ms must be positive — a zero base retries immediately, \
935                 a retry storm by another name"
936                    .to_owned(),
937            ));
938        }
939        if self.base_delay_ms > self.max_delay_ms {
940            return Err(invalid(format!(
941                "backoff base_delay_ms {} exceeds max_delay_ms {} — the schedule would clamp \
942                 to the cap from the first retry, an exponential in name only",
943                self.base_delay_ms, self.max_delay_ms
944            )));
945        }
946        if self.max_delay_ms > POLICY_MAX_DELAY_ENVELOPE_MS {
947            return Err(invalid(format!(
948                "backoff max_delay_ms {} exceeds the {POLICY_MAX_DELAY_ENVELOPE_MS} ms \
949                 envelope",
950                self.max_delay_ms
951            )));
952        }
953        if self.max_attempts > POLICY_MAX_ATTEMPTS_ENVELOPE {
954            return Err(invalid(format!(
955                "backoff max_attempts {} exceeds the {POLICY_MAX_ATTEMPTS_ENVELOPE}-attempt \
956                 envelope",
957                self.max_attempts
958            )));
959        }
960        Ok(())
961    }
962}
963
964/// The retry family's parameters of an [`ExecutorPolicy`].
965///
966/// The flat schedule is the default every class falls back to. `per_class`
967/// (R0.10 wave 3) carries learned per-[`crate::durable::ErrorClass`]
968/// overrides: a class with an entry decides by that schedule (its budget
969/// narrowing the task's declared budget, never widening it); a class
970/// without one decides by the flat schedule. Absent from the wire when
971/// `None`, so the floor's serialized shape is unchanged from v1.
972#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
973pub struct RetryPolicyParameters {
974    /// Base of the exponential backoff schedule, in milliseconds.
975    pub base_delay_ms: u64,
976
977    /// Cap of the backoff schedule, in milliseconds.
978    pub max_delay_ms: u64,
979
980    /// Attempt budget: the number of attempts counting the initial one.
981    /// `0` means no retries at all — every retryable failure dead-letters.
982    pub max_attempts: u32,
983
984    /// Learned per-error-class schedules (R0.10 wave 3). `None` — every
985    /// pre-learning policy — means the flat schedule decides for all
986    /// classes, exactly the v1 behavior.
987    #[serde(default, skip_serializing_if = "Option::is_none")]
988    pub per_class: Option<BTreeMap<crate::durable::ErrorClass, BackoffParameters>>,
989}
990
991impl RetryPolicyParameters {
992    /// The flat schedule as [`BackoffParameters`].
993    pub fn flat(&self) -> BackoffParameters {
994        BackoffParameters {
995            base_delay_ms: self.base_delay_ms,
996            max_delay_ms: self.max_delay_ms,
997            max_attempts: self.max_attempts,
998        }
999    }
1000
1001    /// The family's contract: the flat schedule validates, and every
1002    /// per-class entry validates. One bad entry condemns the whole set —
1003    /// there is no "apply the valid half" path, because half-applied
1004    /// policy is how a deployment drifts from what was evaluated.
1005    pub fn validate(&self) -> crate::error::Result<()> {
1006        self.flat().validate()?;
1007        if let Some(per_class) = &self.per_class {
1008            for (class, schedule) in per_class {
1009                schedule.validate().map_err(|e| {
1010                    RustyError::InvalidUpdate(format!("per-class backoff for {class:?}: {e}"))
1011                })?;
1012            }
1013        }
1014        Ok(())
1015    }
1016}
1017
1018/// The timeout family's parameters of an [`ExecutorPolicy`].
1019///
1020/// `None` means uncapped — the honest encoding of "no timeout policy
1021/// is in force", distinct from any concrete millisecond bound.
1022/// `per_callee` (R0.10 wave 3) carries learned per-callee bounds: the
1023/// bound that applies to an operation is its callee's entry when one
1024/// exists, the default otherwise, and no bound at all under the floor.
1025#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1026pub struct TimeoutPolicyParameters {
1027    /// Default timeout applied to operations without their own bound, in
1028    /// milliseconds. `None` means no default is imposed.
1029    #[serde(default, skip_serializing_if = "Option::is_none")]
1030    pub default_millis: Option<u64>,
1031
1032    /// Hard ceiling any operation timeout must stay under, in milliseconds.
1033    /// `None` means uncapped.
1034    #[serde(default, skip_serializing_if = "Option::is_none")]
1035    pub max_millis: Option<u64>,
1036
1037    /// Learned per-callee bounds in milliseconds (R0.10 wave 3), keyed by
1038    /// the callee identity the decision point journals (a tool name, a
1039    /// node id). `None` — every pre-learning policy — means no per-callee
1040    /// bounds, exactly the v1 behavior.
1041    #[serde(default, skip_serializing_if = "Option::is_none")]
1042    pub per_callee: Option<BTreeMap<String, u64>>,
1043}
1044
1045impl TimeoutPolicyParameters {
1046    /// The family's contract: every bound respects the minimum rung (below
1047    /// it ordinary work aborts early — a correctness hazard), the default
1048    /// stays under the ceiling, and every per-callee entry stays under the
1049    /// ceiling when one is declared. One bad bound condemns the whole set.
1050    pub fn validate(&self) -> crate::error::Result<()> {
1051        let invalid = |message: String| RustyError::InvalidUpdate(message);
1052        let check_floor = |what: &str, millis: u64| -> crate::error::Result<()> {
1053            if millis < MIN_TIMEOUT_RUNG_MS {
1054                return Err(invalid(format!(
1055                    "timeout {what} {millis} ms is below the {MIN_TIMEOUT_RUNG_MS} ms minimum \
1056                     rung — below it ordinary work aborts early, a correctness hazard no \
1057                     policy may cross"
1058                )));
1059            }
1060            Ok(())
1061        };
1062        if let Some(default) = self.default_millis {
1063            check_floor("default_millis", default)?;
1064        }
1065        if let Some(max) = self.max_millis {
1066            check_floor("max_millis", max)?;
1067        }
1068        if let (Some(default), Some(max)) = (self.default_millis, self.max_millis) {
1069            if default > max {
1070                return Err(invalid(format!(
1071                    "timeout default_millis {default} exceeds max_millis {max} — the default \
1072                     bound would sit above its own ceiling"
1073                )));
1074            }
1075        }
1076        if let Some(per_callee) = &self.per_callee {
1077            for (callee, millis) in per_callee {
1078                check_floor(&format!("per_callee[{callee}]"), *millis)?;
1079                if let Some(max) = self.max_millis {
1080                    if *millis > max {
1081                        return Err(invalid(format!(
1082                            "timeout per_callee[{callee}] {millis} ms exceeds max_millis \
1083                             {max} — a learned bound may only narrow the declared ceiling"
1084                        )));
1085                    }
1086                }
1087            }
1088        }
1089        Ok(())
1090    }
1091}
1092
1093/// The concurrency family's parameters of an [`ExecutorPolicy`].
1094///
1095/// v1 pins the shape only: no executor decision point consumes these values
1096/// yet. `None` means unlimited — the honest encoding of "no concurrency
1097/// policy is in force".
1098#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1099pub struct ConcurrencyPolicyParameters {
1100    /// Maximum number of parallel executions. `None` means unlimited.
1101    #[serde(default, skip_serializing_if = "Option::is_none")]
1102    pub max_parallel: Option<u32>,
1103}
1104
1105/// The executor policy contract (R0.8 wave 4): one versioned bundle of the
1106/// parameters the executor's mechanical decision points agree to decide
1107/// with.
1108///
1109/// An `ExecutorPolicy` is what a [`PolicyVersion`] *names*: the registry
1110/// (server side) stores immutable policy bodies under content-derived
1111/// versions, runs bind the active version at admission, and every
1112/// [`DecisionEvent`] records which version decided. Because the version is
1113/// derived from the content ([`derive_policy_version`]), two registries that
1114/// agree on a version string agree on the exact parameters — promotion and
1115/// rollback move versions, never mutate bodies.
1116///
1117/// v1 wires versions into admission binding and decision evidence; R0.10
1118/// wave 3 adds the application loop: the retry classifier and the timeout
1119/// decision point read the bound version's parameters through
1120/// [`crate::durable::resolve_retry_parameters`] and
1121/// [`crate::durable::resolve_timeout_bound_ms`], with the static floor's
1122/// constants as the read path when the version names no override (or names
1123/// an invalid one — invalid parameters fail closed to the floor).
1124/// The static floor ([`ExecutorPolicy::static_v0`]) is the behavior every
1125/// pre-learning run already had: the retry constants of
1126/// [`crate::durable::classify_retry`], no timeout bound, no concurrency
1127/// limit.
1128#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1129pub struct ExecutorPolicy {
1130    /// Retry parameters — the family v1 actually emits decisions for.
1131    pub retry: RetryPolicyParameters,
1132
1133    /// Timeout parameters (shape pinned; unconsumed in v1).
1134    pub timeout: TimeoutPolicyParameters,
1135
1136    /// Concurrency parameters (shape pinned; unconsumed in v1).
1137    pub concurrency: ConcurrencyPolicyParameters,
1138}
1139
1140impl ExecutorPolicy {
1141    /// The static floor: the fixed behavior of every run before the policy
1142    /// plane landed, named by [`PolicyVersion::STATIC_V0`].
1143    ///
1144    /// The retry parameters mirror the `crate::durable` backoff constants and
1145    /// the server's default attempt budget (`DEFAULT_MAX_ATTEMPTS = 3`); the
1146    /// timeout and concurrency families are uncapped, matching the executor's
1147    /// behavior when no policy is in force.
1148    pub fn static_v0() -> Self {
1149        Self {
1150            retry: RetryPolicyParameters {
1151                base_delay_ms: crate::durable::BASE_RETRY_DELAY_MS,
1152                max_delay_ms: crate::durable::MAX_RETRY_DELAY_MS,
1153                max_attempts: 3,
1154                per_class: None,
1155            },
1156            timeout: TimeoutPolicyParameters {
1157                default_millis: None,
1158                max_millis: None,
1159                per_callee: None,
1160            },
1161            concurrency: ConcurrencyPolicyParameters { max_parallel: None },
1162        }
1163    }
1164
1165    /// `true` when this policy is exactly the static floor — the read path
1166    /// every decision point falls back to. Compared by value, not by
1167    /// version name: a registered body identical to the floor *is* the
1168    /// floor's behavior, whatever string names it.
1169    pub fn is_static_floor(&self) -> bool {
1170        self == &Self::static_v0()
1171    }
1172
1173    /// The whole bundle's contract: every family's parameters validate.
1174    /// Decision points call this (or the per-family equivalents) before
1175    /// reading parameters into a decision — an invalid bundle steers
1176    /// nothing; the floor decides instead.
1177    pub fn validate(&self) -> crate::error::Result<()> {
1178        self.retry.validate()?;
1179        self.timeout.validate()?;
1180        if let Some(0) = self.concurrency.max_parallel {
1181            return Err(RustyError::InvalidUpdate(
1182                "concurrency max_parallel 0 admits no work at all — a policy that halts the \
1183                 fleet is not a learning outcome, it is an outage"
1184                    .to_owned(),
1185            ));
1186        }
1187        Ok(())
1188    }
1189
1190    /// This policy with one family's parameters replaced by `parameters`
1191    /// (parsed as that family's parameter type).
1192    ///
1193    /// This is how a promoted policy candidate — whose content is a family
1194    /// plus a free-form parameter value — becomes a concrete
1195    /// `ExecutorPolicy`: the candidate's parameters are parsed against the
1196    /// family's contract and checked against the family's declared envelope
1197    /// (R0.10 wave 3), then overlaid onto the policy that was active (the
1198    /// floor when nothing was promoted yet). Out-of-envelope parameters are
1199    /// rejected — a malformed candidate can never become an active policy.
1200    /// Families without a parameter contract
1201    /// ([`DecisionFamily::WorkerPlacement`],
1202    /// [`DecisionFamily::CheckpointPlacement`]) are rejected: those families
1203    /// are shadow-only, and a shadow family's parameters cannot activate.
1204    pub fn with_family_parameters(
1205        &self,
1206        family: DecisionFamily,
1207        parameters: serde_json::Value,
1208    ) -> crate::error::Result<Self> {
1209        let mut policy = self.clone();
1210        match family {
1211            DecisionFamily::Retry => {
1212                policy.retry = serde_json::from_value(parameters).map_err(|e| {
1213                    RustyError::InvalidUpdate(format!(
1214                        "retry policy parameters do not match the contract: {e}"
1215                    ))
1216                })?;
1217                policy.retry.validate().map_err(|e| {
1218                    RustyError::InvalidUpdate(format!(
1219                        "retry policy parameters fall outside the envelope: {e}"
1220                    ))
1221                })?;
1222            }
1223            DecisionFamily::Timeout => {
1224                policy.timeout = serde_json::from_value(parameters).map_err(|e| {
1225                    RustyError::InvalidUpdate(format!(
1226                        "timeout policy parameters do not match the contract: {e}"
1227                    ))
1228                })?;
1229                policy.timeout.validate().map_err(|e| {
1230                    RustyError::InvalidUpdate(format!(
1231                        "timeout policy parameters fall outside the envelope: {e}"
1232                    ))
1233                })?;
1234            }
1235            DecisionFamily::Concurrency => {
1236                policy.concurrency = serde_json::from_value(parameters).map_err(|e| {
1237                    RustyError::InvalidUpdate(format!(
1238                        "concurrency policy parameters do not match the contract: {e}"
1239                    ))
1240                })?;
1241                if let Some(0) = policy.concurrency.max_parallel {
1242                    return Err(RustyError::InvalidUpdate(
1243                        "concurrency policy parameters fall outside the envelope: \
1244                         max_parallel 0 admits no work at all"
1245                            .to_owned(),
1246                    ));
1247                }
1248            }
1249            other => {
1250                return Err(RustyError::InvalidUpdate(format!(
1251                    "decision family `{other:?}` has no executor-policy parameter contract \
1252                     in this version"
1253                )));
1254            }
1255        }
1256        Ok(policy)
1257    }
1258}
1259
1260/// Derive the content-addressed version of an [`ExecutorPolicy`]:
1261/// `policy-{first 12 hex of sha256(canonical_json(policy))}`.
1262///
1263/// Content addressing is what makes the registry's immutability enforceable:
1264/// a version string *is* a commitment to one exact parameter set, so
1265/// "register a different body under an existing version" is detectable as a
1266/// conflict rather than silently overwriting behavior. The static floor is
1267/// exempt — it keeps its human-readable [`PolicyVersion::STATIC_V0`] name
1268/// because it predates the registry and never needs registration.
1269pub fn derive_policy_version(policy: &ExecutorPolicy) -> crate::error::Result<PolicyVersion> {
1270    let bytes = serde_json::to_vec(policy)?;
1271    let hash = sha256_hex(&bytes);
1272    Ok(PolicyVersion::new(format!("policy-{}", &hash[..12])))
1273}
1274
1275/// A capsule version pin — the R0.7 placeholder for R0.9's capsule manifest
1276/// identity.
1277///
1278/// R0.9 gives capsules a full manifest (build digest, declared interface,
1279/// capability grants); R0.7 pins only the version string so a run's manifest
1280/// can already record *which* capsule build influenced it. Typing it now —
1281/// rather than storing a bare string — localizes the R0.9 evolution to one
1282/// type instead of every consumer of the manifest map. Transparent over
1283/// `String`: the wire shape is the version string itself.
1284#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
1285#[serde(transparent)]
1286pub struct CapsuleVersion(pub String);
1287
1288impl CapsuleVersion {
1289    /// Wrap a version string.
1290    pub fn new(version: impl Into<String>) -> Self {
1291        Self(version.into())
1292    }
1293
1294    /// The version string.
1295    pub fn as_str(&self) -> &str {
1296        &self.0
1297    }
1298}
1299
1300impl std::fmt::Display for CapsuleVersion {
1301    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1302        f.write_str(&self.0)
1303    }
1304}
1305
1306/// The versioned run manifest (R0.7): everything beyond the graph itself
1307/// that can influence a run, pinned at checkpoint time.
1308///
1309/// The R0.5 header pins the checkpoint format, the graph version and
1310/// topology, and the executor policy — but a run's behavior is also shaped
1311/// by its prompts, its tools' schemas, its model and parameters, and (as
1312/// they land) its memory schema and capsule builds. The manifest pins all of
1313/// them by content address (lowercase hex SHA-256, the one hashing primitive
1314/// shared with artifact references and journal heads), so a checkpoint
1315/// answers not just "which graph produced this?" but "which *configuration
1316/// of everything else* produced this?".
1317///
1318/// **Upgrade safety.** Pinning is what lets long-running agents survive
1319/// platform upgrades: a run resumed from a checkpoint keeps executing
1320/// against the versions its manifest pins, while new versions shadow for new
1321/// runs. An absent field means *unpinned*, never a default — consumers must
1322/// not invent one. Migration contracts between pinned versions (when a run
1323/// may move from pin A to pin B, and how) are R1.0's stability work,
1324/// deliberately: this wave records the evidence migrations will be judged
1325/// against.
1326///
1327/// Every field is optional and omitted from the wire when unset
1328/// (`skip_serializing_if`), so a header carrying no manifest — or a manifest
1329/// carrying only some pins — produces no shape change for pre-R0.7 readers.
1330#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
1331pub struct RunManifest {
1332    /// Prompt digests: prompt name → SHA-256 of the exact prompt text
1333    /// (`sha256_hex` over its UTF-8 bytes). Prompt text, not a name alone,
1334    /// because an edited prompt under an unchanged name is exactly the drift
1335    /// the manifest exists to catch.
1336    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1337    pub prompts: BTreeMap<String, String>,
1338
1339    /// Tool schema digests: tool name → SHA-256 of the canonical
1340    /// `serde_json` serialization of its parameters schema (the same
1341    /// canonicalization [`PayloadRef::content_hash`] relies on: object keys
1342    /// sort deterministically, so equal schemas hash equal).
1343    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1344    pub tool_schemas: BTreeMap<String, String>,
1345
1346    /// The model identifier the run pinned (a provider-precise string such
1347    /// as `gpt-5.2-2026-06-01`, not a floating alias like `gpt-5.2-latest` —
1348    /// an alias is not a pin).
1349    #[serde(default, skip_serializing_if = "Option::is_none")]
1350    pub model: Option<String>,
1351
1352    /// SHA-256 digest of the canonical JSON of the model parameters
1353    /// (temperature, seed, token limits, ...) the run pinned. A digest
1354    /// rather than the parameters themselves: the header stays cheap to scan
1355    /// and parameter sets with secrets-adjacent values never land in
1356    /// evidence verbatim.
1357    #[serde(default, skip_serializing_if = "Option::is_none")]
1358    pub model_params: Option<String>,
1359
1360    /// The memory schema version the run pinned (R0.8's memory record
1361    /// model). Declared in R0.7 so runs that outlive the R0.8 upgrade can
1362    /// still be interpreted against the schema their memories were written
1363    /// under.
1364    #[serde(default, skip_serializing_if = "Option::is_none")]
1365    pub memory_schema: Option<String>,
1366
1367    /// Capsule version pins: capsule name → [`CapsuleVersion`] (placeholder
1368    /// for R0.9's capsule manifests — see that type's docs).
1369    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1370    pub capsules: BTreeMap<String, CapsuleVersion>,
1371
1372    /// SHA-256 digest of the canonical JSON of the middleware composition
1373    /// the run pinned (R0.11 Extension Plane, wave 4): the ordered layer
1374    /// list plus per-layer configuration the run's chain was instantiated
1375    /// from. This is the release's one additive manifest field — the
1376    /// design's named exception to the wire-frozen manifest — because no
1377    /// existing slot covers interception policy, and the deviation is
1378    /// smaller than leaving it unpinned. A digest rather than the
1379    /// composition itself, per the `model_params` reasoning; the digest ↔
1380    /// version join is the journaled resolution event, exactly as for the
1381    /// other families. Absent when the run bound no composition artifact —
1382    /// absent means unpinned, never a default, and old manifests are
1383    /// byte-stable.
1384    #[serde(default, skip_serializing_if = "Option::is_none")]
1385    pub middleware: Option<String>,
1386}
1387
1388impl RunManifest {
1389    /// An empty manifest: nothing pinned. Equivalent to [`Default`].
1390    pub fn new() -> Self {
1391        Self::default()
1392    }
1393
1394    /// Pin a prompt by content: records the SHA-256 of its exact UTF-8 text
1395    /// under `name`.
1396    pub fn pin_prompt(mut self, name: impl Into<String>, prompt: &str) -> Self {
1397        self.prompts
1398            .insert(name.into(), sha256_hex(prompt.as_bytes()));
1399        self
1400    }
1401
1402    /// Pin a tool's parameters schema by content: records the SHA-256 of its
1403    /// canonical `serde_json` serialization under `name`.
1404    pub fn pin_tool_schema(mut self, name: impl Into<String>, schema: &Value) -> Self {
1405        self.tool_schemas
1406            .insert(name.into(), canonical_json_digest(schema));
1407        self
1408    }
1409
1410    /// Pin the model identifier and the content digest of its parameters.
1411    pub fn pin_model(mut self, model: impl Into<String>, parameters: &Value) -> Self {
1412        self.model = Some(model.into());
1413        self.model_params = Some(canonical_json_digest(parameters));
1414        self
1415    }
1416
1417    /// Pin the memory schema version (R0.8's record model; see the field
1418    /// docs).
1419    pub fn with_memory_schema(mut self, version: impl Into<String>) -> Self {
1420        self.memory_schema = Some(version.into());
1421        self
1422    }
1423
1424    /// Pin a capsule version (R0.9 placeholder; see [`CapsuleVersion`]).
1425    pub fn pin_capsule(mut self, name: impl Into<String>, version: CapsuleVersion) -> Self {
1426        self.capsules.insert(name.into(), version);
1427        self
1428    }
1429
1430    /// Pin a middleware composition by content: records the SHA-256 of the
1431    /// canonical `serde_json` serialization of its ordered layer list —
1432    /// the same digest convention every JSON pin here follows, computed by
1433    /// the same rule the registry's `resolution_pin` applies, so the
1434    /// journaled resolution digest and this pin can never diverge.
1435    pub fn pin_middleware(mut self, composition: &Value) -> Self {
1436        self.middleware = Some(canonical_json_digest(composition));
1437        self
1438    }
1439}
1440
1441/// The value with every object map rebuilt in sorted key order,
1442/// recursively — the canonical form every content hash in this crate
1443/// covers.
1444///
1445/// `serde_json`'s default map is BTreeMap-backed, so serializing a `Value`
1446/// already emits object keys sorted; under the default backend this
1447/// transform is an identity and every pre-existing hash is preserved
1448/// byte-for-byte. The hazard is serde_json's `preserve_order` feature,
1449/// which `cedar-policy-core` (R0.9's Cedar engine, behind the server's
1450/// `capsules` feature) enables unconditionally: feature unification then
1451/// swaps the workspace-wide map for an insertion-ordered IndexMap, and
1452/// the same logical payload serializes — and hashes — differently
1453/// depending on the order its keys happened to be inserted. Routing every
1454/// hash through this canonical form keeps content addresses stable across
1455/// both map backends and across builds with and without the feature.
1456pub(crate) fn canonicalize_value(value: &Value) -> Value {
1457    match value {
1458        Value::Object(map) => {
1459            let mut entries: Vec<(&String, &Value)> = map.iter().collect();
1460            entries.sort_by_key(|(key, _)| *key);
1461            Value::Object(
1462                entries
1463                    .into_iter()
1464                    .map(|(key, item)| (key.clone(), canonicalize_value(item)))
1465                    .collect(),
1466            )
1467        }
1468        Value::Array(items) => Value::Array(items.iter().map(canonicalize_value).collect()),
1469        scalar => scalar.clone(),
1470    }
1471}
1472
1473/// SHA-256 of the canonical `serde_json` serialization of `value` — the
1474/// digest convention shared by every manifest pin over JSON content.
1475fn canonical_json_digest(value: &Value) -> String {
1476    // Serializing a `Value` is infallible in practice (its maps always have
1477    // string keys); `PayloadRef::content_hash` documents why the result is
1478    // canonical.
1479    let bytes = serde_json::to_vec(&canonicalize_value(value))
1480        .expect("a serde_json::Value always serializes");
1481    sha256_hex(&bytes)
1482}
1483
1484/// The provenance header stamped into every checkpoint.
1485///
1486/// Answers, for any stored checkpoint: which checkpoint format wrote it
1487/// (`format_version`), which graph produced it (`graph_version` +
1488/// `graph_hash`), under which policy (`policy_version`), and where it sits
1489/// on the run's logical clock. Without this, a checkpoint is data; with it,
1490/// a checkpoint is interpretable evidence — replay can refuse (or migrate)
1491/// checkpoints whose format or graph no longer matches.
1492///
1493/// Added to `Checkpoint` with serde defaults: checkpoints written before
1494/// R0.5 (no header) deserialize into [`CheckpointHeader::default`]. R0.7
1495/// extends the header additively with the [`RunManifest`] pin set — same
1496/// rule: unset fields stay absent from the wire and old headers keep
1497/// deserializing.
1498#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1499pub struct CheckpointHeader {
1500    /// Checkpoint envelope format version; [`CURRENT_FORMAT_VERSION`] for
1501    /// anything written now.
1502    pub format_version: u32,
1503
1504    /// Application-declared graph version (via `RunConfig::with_graph_version`),
1505    /// or `"unversioned"` when the application does not version its graph.
1506    pub graph_version: String,
1507
1508    /// SHA-256 content hash of the compiled graph topology (node names and
1509    /// edge shape — see `Graph::topology_hash`). Detects graph drift between
1510    /// a checkpoint and the code about to resume it; semantic node-body
1511    /// changes are the application's responsibility via `graph_version`.
1512    pub graph_hash: String,
1513
1514    /// The executor policy active when the checkpoint was written.
1515    pub policy_version: PolicyVersion,
1516
1517    /// The run's logical clock value (milliseconds) at creation. Under the
1518    /// default system clock this is epoch milliseconds; under a logical
1519    /// clock it is the deterministic tick — either way it is the ordering
1520    /// and replay handle, not wall time.
1521    pub logical_clock: u64,
1522
1523    /// The versioned run manifest (R0.7): prompts, tool schemas, model and
1524    /// parameters, memory schema, and capsule versions pinned for the run —
1525    /// see [`RunManifest`] for the upgrade-safety contract. Stamped from
1526    /// `RunConfig::with_manifest` at checkpoint time.
1527    ///
1528    /// Additive: `None` (the default) is absent from the wire, so headers
1529    /// written before R0.7 — and headers of runs that pin nothing — keep
1530    /// their exact R0.5 shape.
1531    #[serde(default, skip_serializing_if = "Option::is_none")]
1532    pub manifest: Option<RunManifest>,
1533}
1534
1535impl Default for CheckpointHeader {
1536    /// The header for a checkpoint written without run context: current
1537    /// format, unversioned/empty graph identity, static policy, clock zero,
1538    /// no manifest. Also the deserialization fallback for pre-R0.5
1539    /// checkpoints.
1540    fn default() -> Self {
1541        Self {
1542            format_version: CURRENT_FORMAT_VERSION,
1543            graph_version: "unversioned".to_owned(),
1544            graph_hash: String::new(),
1545            policy_version: PolicyVersion::default(),
1546            logical_clock: 0,
1547            manifest: None,
1548        }
1549    }
1550}
1551
1552/// A reference to the journal head at a checkpoint boundary, stamped into
1553/// the checkpoint so evidence and state travel together.
1554///
1555/// The hash is the journal's running head hash (chained SHA-256 over
1556/// recorded events), so a checkpoint pins not just *how many* events existed
1557/// but *which* events — tamper-evident linkage between state and evidence.
1558#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1559pub struct JournalRef {
1560    /// Number of events in the journal at the boundary.
1561    pub events: u64,
1562
1563    /// Journal head hash (chained SHA-256) at the boundary.
1564    pub sha256: String,
1565}
1566
1567#[cfg(test)]
1568mod tests {
1569    use super::*;
1570    use serde_json::json;
1571
1572    #[test]
1573    fn sha256_hex_is_stable_and_lowercase() {
1574        // SHA-256 of the empty input, pinned against the published digest.
1575        assert_eq!(
1576            sha256_hex(b""),
1577            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
1578        );
1579        assert_eq!(sha256_hex(b"abc").len(), 64);
1580    }
1581
1582    #[test]
1583    fn policy_version_default_is_static_floor() {
1584        assert_eq!(PolicyVersion::default().as_str(), PolicyVersion::STATIC_V0);
1585        // Transparent newtype: serializes as a bare string.
1586        assert_eq!(
1587            serde_json::to_value(PolicyVersion::default()).unwrap(),
1588            json!("static-v0")
1589        );
1590    }
1591
1592    #[test]
1593    fn executor_policy_static_floor_mirrors_the_durable_constants() {
1594        let floor = ExecutorPolicy::static_v0();
1595        assert_eq!(
1596            floor.retry.base_delay_ms,
1597            crate::durable::BASE_RETRY_DELAY_MS
1598        );
1599        assert_eq!(floor.retry.max_delay_ms, crate::durable::MAX_RETRY_DELAY_MS);
1600        // The floor pins the server's default attempt budget; timeout and
1601        // concurrency are uncapped — the honest encoding of "no policy".
1602        assert_eq!(floor.retry.max_attempts, 3);
1603        assert!(floor.timeout.default_millis.is_none());
1604        assert!(floor.timeout.max_millis.is_none());
1605        assert!(floor.concurrency.max_parallel.is_none());
1606        // Unset options stay absent from the wire.
1607        let wire = serde_json::to_value(floor).unwrap();
1608        assert_eq!(wire["timeout"], json!({}));
1609        assert_eq!(wire["concurrency"], json!({}));
1610    }
1611
1612    #[test]
1613    fn derive_policy_version_is_content_addressed() {
1614        let policy = ExecutorPolicy::static_v0()
1615            .with_family_parameters(
1616                DecisionFamily::Retry,
1617                json!({"base_delay_ms": 500, "max_delay_ms": 60_000, "max_attempts": 5}),
1618            )
1619            .unwrap();
1620        let first = derive_policy_version(&policy).unwrap();
1621        let again = derive_policy_version(&policy).unwrap();
1622        assert_eq!(first, again, "version derivation must be deterministic");
1623        assert!(
1624            first.as_str().starts_with("policy-"),
1625            "derived versions carry the policy- prefix: {first}"
1626        );
1627        assert_eq!(first.as_str().len(), "policy-".len() + 12);
1628
1629        // Any parameter change is a different version — that is what makes
1630        // registry immutability enforceable.
1631        let changed = policy
1632            .with_family_parameters(
1633                DecisionFamily::Retry,
1634                json!({"base_delay_ms": 500, "max_delay_ms": 60_000, "max_attempts": 6}),
1635            )
1636            .unwrap();
1637        assert_ne!(first, derive_policy_version(&changed).unwrap());
1638    }
1639
1640    #[test]
1641    fn with_family_parameters_validates_and_overlays() {
1642        let base = ExecutorPolicy::static_v0();
1643
1644        // Timeout and concurrency families parse their own contracts.
1645        let with_timeout = base
1646            .with_family_parameters(
1647                DecisionFamily::Timeout,
1648                json!({"default_millis": 30_000, "max_millis": 120_000}),
1649            )
1650            .unwrap();
1651        assert_eq!(with_timeout.timeout.default_millis, Some(30_000));
1652        assert_eq!(with_timeout.timeout.max_millis, Some(120_000));
1653        // Untouched families keep the base values.
1654        assert_eq!(with_timeout.retry, base.retry);
1655
1656        let with_concurrency = base
1657            .with_family_parameters(DecisionFamily::Concurrency, json!({"max_parallel": 8}))
1658            .unwrap();
1659        assert_eq!(with_concurrency.concurrency.max_parallel, Some(8));
1660
1661        // A malformed body is rejected with the family named.
1662        let err = base
1663            .with_family_parameters(DecisionFamily::Retry, json!({"base_delay_ms": "fast"}))
1664            .unwrap_err();
1665        assert!(err.to_string().contains("retry policy parameters"), "{err}");
1666
1667        // Families without a v1 parameter contract are rejected.
1668        for family in [
1669            DecisionFamily::WorkerPlacement,
1670            DecisionFamily::CheckpointPlacement,
1671        ] {
1672            let err = base.with_family_parameters(family, json!({})).unwrap_err();
1673            assert!(
1674                err.to_string().contains("no executor-policy parameter"),
1675                "{err}"
1676            );
1677        }
1678    }
1679
1680    #[test]
1681    fn payload_ref_content_hash_agrees_across_representations() {
1682        let value = json!({"b": 1, "a": [2, 3]});
1683        let bytes = serde_json::to_vec(&value).unwrap();
1684        let inline = PayloadRef::inline(value);
1685        let referenced = PayloadRef::Artifact(ArtifactRef {
1686            sha256: sha256_hex(&bytes),
1687            bytes: bytes.len() as u64,
1688        });
1689        assert_eq!(
1690            inline.content_hash().unwrap(),
1691            referenced.content_hash().unwrap()
1692        );
1693    }
1694
1695    #[test]
1696    fn effect_repeatability_ladder() {
1697        assert!(Effect::Pure.is_freely_repeatable());
1698        assert!(Effect::ReadOnly.is_freely_repeatable());
1699        assert!(Effect::Idempotent.is_freely_repeatable());
1700        assert!(!Effect::Compensatable.is_freely_repeatable());
1701        assert!(!Effect::NonIdempotent.is_freely_repeatable());
1702    }
1703
1704    #[test]
1705    fn contracts_serde_roundtrip() {
1706        let event = RunEvent {
1707            id: "r1:7".into(),
1708            run_id: "r1".into(),
1709            thread_id: "t1".into(),
1710            node_id: Some("agent".into()),
1711            seq: 7,
1712            kind: RunEventKind::ModelCall,
1713            effect: Effect::NonIdempotent,
1714            input: Some(PayloadRef::inline(json!({"messages": []}))),
1715            output: Some(PayloadRef::Artifact(ArtifactRef {
1716                sha256: sha256_hex(b"response"),
1717                bytes: 8,
1718            })),
1719            latency_ms: Some(42),
1720            tokens: Some(Usage {
1721                prompt_tokens: 10,
1722                completion_tokens: 5,
1723                total_tokens: 15,
1724            }),
1725            cost_usd: Some(0.0001),
1726            status: EventStatus::Ok,
1727            parent: Some("r1:3".into()),
1728            recorded_at: DateTime::<Utc>::from_timestamp_millis(1_000).unwrap(),
1729        };
1730        let back: RunEvent = serde_json::from_str(&serde_json::to_string(&event).unwrap()).unwrap();
1731        assert_eq!(event, back);
1732
1733        let decision = DecisionEvent {
1734            id: "r1:d0".into(),
1735            run_id: "r1".into(),
1736            thread_id: "t1".into(),
1737            seq: 0,
1738            family: DecisionFamily::Retry,
1739            features: Map::from_iter([("failure_class".to_owned(), json!("timeout"))]),
1740            legal_actions: vec![DecisionAction::Retry { attempt: 1 }, DecisionAction::Abort],
1741            selected: DecisionAction::Retry { attempt: 1 },
1742            propensity: 0.75,
1743            policy_version: PolicyVersion::default(),
1744            role: None,
1745            outcome: None,
1746            decided_at: DateTime::<Utc>::from_timestamp_millis(1_000).unwrap(),
1747        };
1748        let back: DecisionEvent =
1749            serde_json::from_str(&serde_json::to_string(&decision).unwrap()).unwrap();
1750        assert_eq!(decision, back);
1751    }
1752
1753    #[test]
1754    fn checkpoint_header_default_matches_pre_r05_fallback() {
1755        let header = CheckpointHeader::default();
1756        assert_eq!(header.format_version, CURRENT_FORMAT_VERSION);
1757        assert_eq!(header.graph_version, "unversioned");
1758        assert_eq!(header.policy_version, PolicyVersion::default());
1759        assert_eq!(header.logical_clock, 0);
1760        assert_eq!(header.manifest, None);
1761    }
1762
1763    #[test]
1764    fn manifest_digests_are_stable_content_addresses() {
1765        // Constants computed independently (SHA-256 of the exact bytes): the
1766        // pins are content addresses, so their stability across releases is
1767        // the contract — a drifting digest would silently split runs from
1768        // their own evidence.
1769        let manifest = RunManifest::new()
1770            .pin_prompt("system", "You are a careful research agent.")
1771            .pin_tool_schema(
1772                "search",
1773                &json!({"type": "object", "properties": {"query": {"type": "string"}}}),
1774            )
1775            .pin_model(
1776                "gpt-5.2-2026-06-01",
1777                &json!({"temperature": 0, "seed": 42, "max_tokens": 512}),
1778            )
1779            .with_memory_schema("memory-v1")
1780            .pin_capsule("researcher", CapsuleVersion::new("1.4.0"));
1781
1782        assert_eq!(
1783            manifest.prompts["system"],
1784            "edff20fbc61c032a9206bdc94aec3b70e05ab953383972b267b83957d9ba7bfe"
1785        );
1786        assert_eq!(
1787            manifest.tool_schemas["search"],
1788            "094ec29d007cce150c65abf0756d79ad5b62a1acfdb6e0841f69f1377ef41761"
1789        );
1790        assert_eq!(
1791            manifest.model_params.as_deref(),
1792            Some("fc004364a674799b07f8e4e6323ad74398745607ae3bd955e0d9c1d7529a0762")
1793        );
1794        assert_eq!(manifest.model.as_deref(), Some("gpt-5.2-2026-06-01"));
1795        assert_eq!(manifest.memory_schema.as_deref(), Some("memory-v1"));
1796        assert_eq!(manifest.capsules["researcher"].as_str(), "1.4.0");
1797
1798        // Key order in the source JSON must not matter: canonicalization
1799        // sorts object keys, so semantically equal schemas pin equal.
1800        let reordered = RunManifest::new().pin_tool_schema(
1801            "search",
1802            &json!({"properties": {"query": {"type": "string"}}, "type": "object"}),
1803        );
1804        assert_eq!(manifest.tool_schemas, reordered.tool_schemas);
1805    }
1806
1807    #[test]
1808    fn manifest_serde_roundtrip_and_sparse_wire_shape() {
1809        let manifest = RunManifest::new()
1810            .pin_prompt("system", "Be brief.")
1811            .pin_model("model-x", &json!({"temperature": 0.5}));
1812        let back: RunManifest =
1813            serde_json::from_str(&serde_json::to_string(&manifest).unwrap()).unwrap();
1814        assert_eq!(manifest, back);
1815
1816        // Sparse pins stay sparse on the wire: unset fields are absent, not
1817        // null or empty — pre-R0.7 readers see no new keys at all.
1818        let value = serde_json::to_value(&manifest).unwrap();
1819        assert!(value.get("tool_schemas").is_none());
1820        assert!(value.get("memory_schema").is_none());
1821        assert!(value.get("capsules").is_none());
1822        assert!(value.get("prompts").is_some());
1823
1824        // An empty manifest serializes to an empty object, and a header that
1825        // carries no manifest omits the field entirely.
1826        assert_eq!(serde_json::to_value(RunManifest::new()).unwrap(), json!({}));
1827        let header = CheckpointHeader::default();
1828        assert!(serde_json::to_value(&header)
1829            .unwrap()
1830            .get("manifest")
1831            .is_none());
1832    }
1833
1834    #[test]
1835    fn r05_header_without_manifest_still_loads() {
1836        // The R0.5 shape — exactly what the golden file pins — deserializes
1837        // into the extended header with the manifest unset.
1838        let r05_shape = json!({
1839            "format_version": 1,
1840            "graph_version": "react-v3",
1841            "graph_hash": "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae",
1842            "policy_version": "static-v0",
1843            "logical_clock": 1750000000000u64,
1844        });
1845        let header: CheckpointHeader = serde_json::from_value(r05_shape).unwrap();
1846        assert_eq!(header.manifest, None);
1847        assert_eq!(header.format_version, CURRENT_FORMAT_VERSION);
1848
1849        // And a header carrying a manifest round-trips it.
1850        let extended = CheckpointHeader {
1851            manifest: Some(RunManifest::new().with_memory_schema("memory-v1")),
1852            ..header
1853        };
1854        let back: CheckpointHeader =
1855            serde_json::from_str(&serde_json::to_string(&extended).unwrap()).unwrap();
1856        assert_eq!(extended, back);
1857    }
1858
1859    #[test]
1860    fn effect_receipt_effect_id_is_additive() {
1861        let receipt = EffectReceipt {
1862            provider: "stripe".into(),
1863            provider_id: "ch_3PKd".into(),
1864            idempotency_key: "run-1:charge:7".into(),
1865            task_id: None,
1866            effect_id: None,
1867        };
1868        // Unset: absent on the wire — pre-R0.7 receipts see no shape change.
1869        let value = serde_json::to_value(&receipt).unwrap();
1870        assert!(value.get("effect_id").is_none());
1871
1872        // Set: carried as a bare digest string, surviving the round-trip.
1873        let with_id = EffectReceipt {
1874            effect_id: Some(
1875                "9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673ca7".into(),
1876            ),
1877            ..receipt
1878        };
1879        let back: EffectReceipt =
1880            serde_json::from_str(&serde_json::to_string(&with_id).unwrap()).unwrap();
1881        assert_eq!(with_id, back);
1882    }
1883}