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