Skip to main content

rusty_agent_runtime/
effects.rs

1//! Effect kernel v2 (R0.7): retry-safety moves from runtime convention into
2//! the type system.
3//!
4//! R0.5 froze the [`Effect`] taxonomy as a wire contract and R0.6 made it a
5//! runtime convention — [`crate::durable::classify_retry`] refuses to silently
6//! retry anything that is not [`Effect::is_freely_repeatable`]. That gate is a
7//! function call away from being ignored: nothing in the type of a node,
8//! tool, or durable task says what its failure modes are. This module adds
9//! the compile-time half. An effect type declares its safety class by
10//! implementing one of the marker traits below; generic infrastructure (a
11//! retry loop, a speculator, the R0.7 race pattern) can then *require* a
12//! class at the type level instead of re-checking a convention at runtime.
13//!
14//! The marker traits **compose with** the wire enum, they do not replace it:
15//! [`Effect`] stays the serde/golden-pinned contract journals and envelopes
16//! are written in; the typed kernel is the in-process API that enforcement
17//! points are built from. The mapping is one-to-one, with one deliberate
18//! naming reconciliation:
19//!
20//! | Marker trait            | Wire [`Effect`]   | What the class unlocks |
21//! |-------------------------|-------------------|------------------------|
22//! | [`PureEffect`]          | `Pure`            | caching, speculation, unrestricted retry |
23//! | [`ReadOnlyEffect`]      | `ReadOnly`        | unrestricted retry; replay serves the journaled value |
24//! | [`IdempotentEffect`]    | `Idempotent`      | automatic retry under a stable idempotency key |
25//! | [`CompensatableEffect`] | `Compensatable`   | execution only with a registered rollback handler |
26//! | [`IrreversibleEffect`]  | `NonIdempotent`   | execution only behind an explicit [`ApprovalToken`] |
27//!
28//! The 2026-08-08 review names the last rung *Irreversible*; the wire enum
29//! calls it `NonIdempotent`. We keep the wire name for two reasons: the
30//! enum's serde shape is golden-pinned evidence (an additive rename would
31//! churn every journal for zero semantic gain), and `NonIdempotent` states
32//! what the runtime can actually *verify* — the absence of a declared
33//! idempotency story — whereas irreversibility is a claim about the world it
34//! cannot check. The typed API adopts the review's vocabulary
35//! ([`IrreversibleEffect`]) because that is the word that makes the approval
36//! boundary legible at a call site; the two names denote one class.
37//!
38//! Two further mechanisms close the loop with the R0.6 receipt ledger:
39//!
40//! - **Deterministic effect ids** ([`derive_effect_id`], [`EffectId`]) — a
41//!   content-addressed identity derived from the run scope, the effect kind,
42//!   the input hash, and the idempotency key. On recovery the runtime asks
43//!   "did this exact effect already commit?" and the journal answers through
44//!   [`crate::journal::JournalSnapshot::find_effect_receipt_by_effect_id`].
45//! - **The approval boundary** ([`ApprovalToken`], [`admit_irreversible`]) —
46//!   an irreversible effect executes only when presented with a token scoped
47//!   to its derived effect id. The token is a proof-of-explicit-decision
48//!   *within the process*: it makes approval a value that must be
49//!   constructed, not a boolean that can be silently defaulted. Cross-process
50//!   attestation of approvals is R0.9's signed-receipt work.
51//!
52//! Runtime enforcement is opt-in: enabling effect admission on an executor
53//! propagates a scoped [`EffectAdmissionContext`] through
54//! [`crate::node::NodeContext`]. The prebuilt ReAct tools node carries it into
55//! [`crate::tool::ToolExecutor`] automatically; custom nodes must do the same
56//! when they construct a tool executor. Calls on that guarded path are
57//! admitted after middleware has finalized their name and arguments but
58//! before the tool body runs. Direct calls to [`crate::tool::Tool::call`] are
59//! outside this cooperative boundary. Executors that do not enable it keep
60//! the pre-R0.7 behavior, so existing graphs remain source-compatible.
61
62use std::collections::BTreeMap;
63use std::sync::{Arc, Mutex};
64
65use serde::{Deserialize, Serialize};
66use serde_json::Value;
67use thiserror::Error;
68
69use crate::record::{sha256_hex, Effect};
70
71/// Domain-separation and versioning prefix for [`derive_effect_id`].
72///
73/// Effect ids are content addresses; the prefix keeps them collision-free
74/// against every other SHA-256 digest in the system (artifact references,
75/// journal heads, topology hashes) and gives the derivation formula an
76/// explicit version handle if it ever needs to change.
77pub const EFFECT_ID_DOMAIN: &str = "rusty/effect-id/v1";
78
79/// A deterministic, content-addressed identity for one logical effect
80/// within a run scope.
81///
82/// Derived — never minted — by [`derive_effect_id`]: the same `(scope, kind,
83/// input hash, idempotency key)` tuple always yields the same id, so a
84/// recovered run re-derives the id of the effect it was about to perform and
85/// asks the journal whether a receipt already exists for it. That lookup is
86/// what turns "retry carefully" into "do not re-execute what already
87/// committed" — exactly-once *business outcomes* where the effect protocol
88/// supports it, never a pretend exactly-once execution.
89///
90/// Transparent newtype over the lowercase hex digest: serializes as a bare
91/// string, consistent with [`crate::record::ArtifactRef`].
92#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
93#[serde(transparent)]
94pub struct EffectId(String);
95
96impl EffectId {
97    /// The hex digest.
98    pub fn as_str(&self) -> &str {
99        &self.0
100    }
101}
102
103impl std::fmt::Display for EffectId {
104    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105        f.write_str(&self.0)
106    }
107}
108
109/// Derive the deterministic id of an effect occurrence.
110///
111/// The formula is `SHA-256` over the newline-joined, domain-prefixed tuple:
112///
113/// ```text
114/// EFFECT_ID_DOMAIN "\n" scope "\n" kind "\n" input_hash "\n" (idempotency_key | "-")
115/// ```
116///
117/// - `scope` is the run (or sub-run) identity the effect belongs to — two
118///   runs performing the same call get different ids, so a receipt from one
119///   run can never masquerade as another's.
120/// - `kind` is the effect type's stable identifier ([`TypedEffect::kind`]).
121/// - `input_hash` is the lowercase hex SHA-256 of the canonical input (the
122///   same canonical `serde_json` serialization [`crate::record::PayloadRef::content_hash`]
123///   uses), precomputed by the caller so this function stays IO-free.
124/// - `idempotency_key` distinguishes intentional replays under one key from
125///   distinct effects that happen to share an input; `-` fills the slot when
126///   the effect has no key, so keyed and unkeyed derivations can never
127///   collide.
128///
129/// Newline-joining (rather than concatenation) keeps the tuple unambiguous
130/// without a length prefix — the same framing [`crate::graph::Graph::topology_hash`]
131/// uses for topology lines.
132pub fn derive_effect_id(
133    scope: &str,
134    kind: &str,
135    input_hash: &str,
136    idempotency_key: Option<&str>,
137) -> EffectId {
138    let material = [
139        EFFECT_ID_DOMAIN,
140        scope,
141        kind,
142        input_hash,
143        idempotency_key.unwrap_or("-"),
144    ]
145    .join("\n");
146    EffectId(sha256_hex(material.as_bytes()))
147}
148
149/// The runtime description of one effect occurrence awaiting admission.
150///
151/// [`TypedEffect`] is the compile-time declaration surface; this value is its
152/// object-safe dispatch counterpart. A [`crate::tool::Tool`] produces one for
153/// each call after middleware has finalized the call. Its input hash is
154/// computed with the same canonical JSON convention as journal payloads, so
155/// approval tokens derived before execution match the id the dispatcher
156/// re-derives at the boundary.
157#[derive(Debug, Clone, PartialEq, Eq)]
158pub struct EffectRequest {
159    kind: String,
160    effect: Effect,
161    input_hash: String,
162    idempotency_key: Option<String>,
163}
164
165impl EffectRequest {
166    /// Describe an effect over canonical JSON `input`.
167    pub fn new(
168        kind: impl Into<String>,
169        effect: Effect,
170        input: &Value,
171        idempotency_key: Option<String>,
172    ) -> Self {
173        let input_hash = crate::record::PayloadRef::inline(input.clone())
174            .content_hash()
175            .expect("a serde_json::Value always serializes");
176        Self {
177            kind: kind.into(),
178            effect,
179            input_hash,
180            idempotency_key,
181        }
182    }
183
184    /// Bridge a typed declaration into the runtime admission surface.
185    pub fn from_typed<E: TypedEffect>(effect: &E) -> Self {
186        Self {
187            kind: effect.kind().to_owned(),
188            effect: E::EFFECT,
189            input_hash: effect.input_hash().to_owned(),
190            idempotency_key: effect.idempotency_key().map(str::to_owned),
191        }
192    }
193
194    /// Stable application-defined effect kind.
195    pub fn kind(&self) -> &str {
196        &self.kind
197    }
198
199    /// Wire-level safety class recorded for this occurrence.
200    pub fn effect(&self) -> Effect {
201        self.effect
202    }
203
204    /// Canonical input digest used in the deterministic effect id.
205    pub fn input_hash(&self) -> &str {
206        &self.input_hash
207    }
208
209    /// Stable idempotency key, when the declaration requires one.
210    pub fn idempotency_key(&self) -> Option<&str> {
211        self.idempotency_key.as_deref()
212    }
213
214    /// This occurrence's deterministic id in `scope`.
215    pub fn effect_id(&self, scope: &str) -> EffectId {
216        derive_effect_id(
217            scope,
218            self.kind(),
219            self.input_hash(),
220            self.idempotency_key(),
221        )
222    }
223}
224
225/// The typed half of the effect taxonomy: an effect type's contract with the
226/// kernel.
227///
228/// Implement this trait plus exactly one marker trait ([`PureEffect`],
229/// [`ReadOnlyEffect`], [`IdempotentEffect`], [`CompensatableEffect`],
230/// [`IrreversibleEffect`]) to declare an effect's safety class. The marker is
231/// the compile-time claim; [`TypedEffect::EFFECT`] is the wire-level class it
232/// must agree with — every admission helper checks the two against each
233/// other, so a type whose marker and declared class disagree is rejected at
234/// the enforcement point, not silently misclassified.
235pub trait TypedEffect {
236    /// The wire-level [`Effect`] class this type records in journals and
237    /// envelopes. Must agree with the marker trait the type implements (see
238    /// the module-level mapping table); the admission helpers enforce the
239    /// agreement.
240    const EFFECT: Effect;
241
242    /// The effect kind: a stable, application-chosen identifier
243    /// (`"charge_card"`, `"index_document"`). Part of the effect id and the
244    /// key under which rollback handlers are registered, so it must not
245    /// change between deployments that share a journal.
246    fn kind(&self) -> &str;
247
248    /// Lowercase hex SHA-256 of the effect's canonical input. Two calls with
249    /// equal inputs must hash equal — use the canonical `serde_json`
250    /// serialization, as [`crate::record::PayloadRef::content_hash`] does.
251    fn input_hash(&self) -> &str;
252
253    /// The idempotency key the effect commits under, when it has one. The
254    /// key participates in the effect id, so retried derivation under the
255    /// same key converges on the id a recovery pass looks up. `None` is
256    /// honest only for effects that are freely repeatable without a key.
257    fn idempotency_key(&self) -> Option<&str> {
258        None
259    }
260
261    /// This effect's deterministic id within `scope` (usually the run id) —
262    /// [`derive_effect_id`] over the type's own contract fields.
263    fn effect_id(&self, scope: &str) -> EffectId {
264        derive_effect_id(
265            scope,
266            self.kind(),
267            self.input_hash(),
268            self.idempotency_key(),
269        )
270    }
271}
272
273/// Marker: a pure function of its inputs with no observable effect beyond
274/// its return value (wire class [`Effect::Pure`]).
275///
276/// Pure work may be cached, memoized, and speculated freely: re-execution is
277/// always safe and always equivalent, so a speculative result and an
278/// on-demand result are indistinguishable. Declare it by implementing this
279/// trait; [`admit_speculation`] is the enforcement point speculators call.
280pub trait PureEffect: TypedEffect {}
281
282/// Marker: reads external state but writes nothing (wire class
283/// [`Effect::ReadOnly`]).
284///
285/// Re-execution is safe but not necessarily equivalent — the world may have
286/// changed — so exact replay serves the journaled value while live replay
287/// re-reads. Retries are unconstrained, which is why there is no admission
288/// helper for this class: nothing needs gating.
289pub trait ReadOnlyEffect: TypedEffect {}
290
291/// Marker: repeating the call under the same idempotency key has the same
292/// effect as calling once (wire class [`Effect::Idempotent`]).
293///
294/// This is the class that unlocks automatic retry — the typed form of the
295/// gate [`crate::durable::classify_retry`] applies to the untyped enum.
296/// [`admit_retry`] additionally requires the key itself: retrying an
297/// "idempotent" effect with no key is the exact unsoundness the taxonomy
298/// exists to prevent, and the helper refuses it.
299pub trait IdempotentEffect: TypedEffect {}
300
301/// Marker: repeating the call duplicates the effect, but a declared
302/// compensating action can logically undo it — charge/refund (wire class
303/// [`Effect::Compensatable`]).
304///
305/// The compensation is not optional coloring: [`admit_compensatable`]
306/// requires a rollback handler registered for the effect's kind before the
307/// effect may execute, and returns that handler so the caller holds the undo
308/// path from the start. Automatic compensation remains out of scope
309/// (unchanged from R0.6: `Compensatable` fails closed in the untyped retry
310/// path) — the handler is invoked by policy, not by the kernel.
311pub trait CompensatableEffect: TypedEffect {}
312
313/// Marker: no safe automatic repetition and no logical undo — send the
314/// email, fire the charge without a key (wire class [`Effect::NonIdempotent`];
315/// see the module docs for the deliberate naming reconciliation).
316///
317/// Execution requires an explicit [`ApprovalToken`] scoped to the effect's
318/// derived id, presented to [`admit_irreversible`]. Unknown or undeclared
319/// effects belong here by default: the wire enum already defaults to
320/// `NonIdempotent`, and the typed kernel keeps that convention — what is not
321/// declared is never silently retried and never executes without approval.
322pub trait IrreversibleEffect: TypedEffect {}
323
324/// Why the kernel refused an admission decision.
325///
326/// A dedicated error type (not [`crate::error::RustyError`]) because these
327/// are contract violations surfaced by the typed API, not runtime execution
328/// failures; the executor maps them into its own error path when the
329/// enforcement wave lands.
330#[derive(Debug, Clone, PartialEq, Eq, Error)]
331pub enum EffectViolation {
332    /// The marker trait and [`TypedEffect::EFFECT`] disagree — a type-level
333    /// bug, caught at the enforcement point rather than trusted.
334    #[error(
335        "effect kind `{kind}` is marked with the {marker:?} marker trait but declares \
336         {declared:?}: the marker and TypedEffect::EFFECT must agree"
337    )]
338    DeclarationMismatch {
339        /// The effect's kind identifier.
340        kind: String,
341        /// The wire class the marker trait implies.
342        marker: Effect,
343        /// The wire class the type actually declared.
344        declared: Effect,
345    },
346
347    /// An [`IdempotentEffect`] presented for retry admission without the
348    /// idempotency key the declaration is meaningless without.
349    #[error(
350        "idempotent effect kind `{kind}` has no idempotency key: a stable key is what the \
351         idempotency declaration means at the wire"
352    )]
353    MissingIdempotencyKey {
354        /// The effect's kind identifier.
355        kind: String,
356    },
357
358    /// A [`CompensatableEffect`] with no rollback handler registered for its
359    /// kind.
360    #[error(
361        "compensatable effect kind `{kind}` has no registered rollback handler: register one \
362         in a CompensationRegistry before executing it"
363    )]
364    MissingCompensation {
365        /// The effect's kind identifier.
366        kind: String,
367    },
368
369    /// An [`IrreversibleEffect`] presented for execution with no approval
370    /// token at all.
371    #[error(
372        "irreversible effect kind `{kind}` ({effect_id}) requires an explicit approval token \
373         scoped to its effect id"
374    )]
375    MissingApproval {
376        /// The effect's kind identifier.
377        kind: String,
378        /// The effect id the approval must be scoped to.
379        effect_id: EffectId,
380    },
381
382    /// A token was presented, but it approves a different effect id — an
383    /// approval is scoped to exactly one effect occurrence and is not
384    /// transferable.
385    #[error(
386        "approval token for {presented} does not admit irreversible effect kind `{kind}` \
387         ({required})"
388    )]
389    ApprovalScopeMismatch {
390        /// The effect's kind identifier.
391        kind: String,
392        /// The effect id the admission requires.
393        required: EffectId,
394        /// The effect id the presented token approves.
395        presented: EffectId,
396    },
397}
398
399/// An explicit, scoped approval to execute one irreversible effect
400/// occurrence.
401///
402/// The token is the approval *boundary made into a value*: constructing one
403/// is the decision, and [`admit_irreversible`] accepts it only for the exact
404/// [`EffectId`] it was minted against, so an approval for one charge cannot
405/// launder another. Within a process this is a proof of explicit decision —
406/// it cannot stop code that is determined to forge one, and it is not meant
407/// to; cross-process attestation is R0.9's signed-receipt work. What it does
408/// guarantee is structural: there is no code path through the typed kernel
409/// that executes an irreversible effect on a defaulted or forgotten
410/// approval.
411///
412/// Tokens ride the run via [`crate::executor::RunConfig::with_effect_approvals`]
413/// so the approval set travels with the run's configuration.
414#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
415pub struct ApprovalToken {
416    /// The effect occurrence this token approves.
417    effect_id: EffectId,
418
419    /// Who approved — a human operator id, a policy name, a supervision
420    /// decision reference. Evidence, not authentication: recorded so the
421    /// journal can attribute the boundary when approval journaling lands.
422    approved_by: String,
423}
424
425impl ApprovalToken {
426    /// Mint an approval for exactly one effect id. This constructor is the
427    /// approval act: call sites should read as decisions (`let approval =
428    /// ApprovalToken::approve(id, "ops:amjad")`), not as plumbing.
429    pub fn approve(effect_id: EffectId, approved_by: impl Into<String>) -> Self {
430        Self {
431            effect_id,
432            approved_by: approved_by.into(),
433        }
434    }
435
436    /// Mint an approval scoped to `effect`'s derived id within `scope` — the
437    /// common case, approving the occurrence a run is about to execute.
438    pub fn for_effect<E: IrreversibleEffect>(
439        effect: &E,
440        scope: &str,
441        approved_by: impl Into<String>,
442    ) -> Self {
443        Self::approve(effect.effect_id(scope), approved_by)
444    }
445
446    /// The effect id this token approves.
447    pub fn effect_id(&self) -> &EffectId {
448        &self.effect_id
449    }
450
451    /// Who approved.
452    pub fn approved_by(&self) -> &str {
453        &self.approved_by
454    }
455
456    /// Whether this token admits `effect_id`. Scoped, not transferable: only
457    /// the exact occurrence it was minted against.
458    pub fn admits(&self, effect_id: &EffectId) -> bool {
459        &self.effect_id == effect_id
460    }
461}
462
463/// A registered rollback handler for a [`CompensatableEffect`] kind.
464///
465/// The handler receives the journaled output of the effect occurrence to
466/// undo and returns a compensation record (what was done to undo it) for
467/// journaling. Errors are plain strings because compensation failures cross
468/// the retry taxonomy's string-classified boundary — a failed compensation
469/// is an operator signal, classified and surfaced, never silently retried by
470/// the kernel (automatic compensation stays out of scope, as in R0.6).
471///
472/// `Arc`-wrapped so an admission can hand the caller a cheap clone of the
473/// registered undo path.
474pub type CompensationHandler = Arc<dyn Fn(&Value) -> Result<Value, String> + Send + Sync>;
475
476/// The registry of rollback handlers backing [`admit_compensatable`].
477///
478/// Registration is the mechanism that makes a `Compensatable` declaration
479/// meaningful: the handler for an effect kind must exist *before* the effect
480/// executes, so the undo path is a precondition, not a postmortem. Handlers
481/// are keyed by [`TypedEffect::kind`]; re-registering a kind replaces its
482/// handler (and returns the old one) so deployments can evolve compensation
483/// logic deliberately.
484#[derive(Default, Clone)]
485pub struct CompensationRegistry {
486    handlers: BTreeMap<String, CompensationHandler>,
487}
488
489impl std::fmt::Debug for CompensationRegistry {
490    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
491        // Handlers are opaque closures; the registered kinds are the useful
492        // debug surface.
493        f.debug_set().entries(self.handlers.keys()).finish()
494    }
495}
496
497impl CompensationRegistry {
498    /// An empty registry: every `Compensatable` admission fails until a
499    /// handler is registered — the fail-closed default.
500    pub fn new() -> Self {
501        Self::default()
502    }
503
504    /// Register `handler` as the rollback path for `kind`, returning the
505    /// handler it replaced, if any.
506    pub fn register(
507        &mut self,
508        kind: impl Into<String>,
509        handler: CompensationHandler,
510    ) -> Option<CompensationHandler> {
511        self.handlers.insert(kind.into(), handler)
512    }
513
514    /// The handler registered for `kind`, if any.
515    pub fn handler_for(&self, kind: &str) -> Option<&CompensationHandler> {
516        self.handlers.get(kind)
517    }
518}
519
520/// A run-scoped, fail-closed admission boundary for runtime effect requests.
521///
522/// The scope is normally a thread id. Approvals are indexed by their exact
523/// deterministic [`EffectId`], and compensations are captured when a request
524/// is admitted so the rollback path remains alive for the entire call.
525#[derive(Clone)]
526pub struct EffectAdmissionContext {
527    scope: String,
528    approvals: Arc<Mutex<BTreeMap<EffectId, ApprovalToken>>>,
529    compensations: CompensationRegistry,
530}
531
532impl std::fmt::Debug for EffectAdmissionContext {
533    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
534        let approvals = self.approvals.lock().unwrap_or_else(|e| e.into_inner());
535        f.debug_struct("EffectAdmissionContext")
536            .field("scope", &self.scope)
537            .field("approval_effect_ids", &approvals.keys())
538            .field("compensations", &self.compensations)
539            .finish()
540    }
541}
542
543impl EffectAdmissionContext {
544    /// Start an admission boundary for `scope` with no approvals or rollback
545    /// handlers. This is intentionally fail-closed for compensatable and
546    /// irreversible effects.
547    pub fn new(scope: impl Into<String>) -> Self {
548        Self {
549            scope: scope.into(),
550            approvals: Arc::new(Mutex::new(BTreeMap::new())),
551            compensations: CompensationRegistry::new(),
552        }
553    }
554
555    /// Attach the exact approval tokens available to this run.
556    pub fn with_approvals(mut self, approvals: impl IntoIterator<Item = ApprovalToken>) -> Self {
557        self.approvals = Arc::new(Mutex::new(
558            approvals
559                .into_iter()
560                .map(|token| (token.effect_id().clone(), token))
561                .collect(),
562        ));
563        self
564    }
565
566    /// Attach the run's registered rollback handlers.
567    pub fn with_compensations(mut self, compensations: CompensationRegistry) -> Self {
568        self.compensations = compensations;
569        self
570    }
571
572    /// The run scope used to derive effect ids.
573    pub fn scope(&self) -> &str {
574        &self.scope
575    }
576
577    /// Admit one effect occurrence, or reject it before its body runs.
578    ///
579    /// Pure and read-only calls require no additional evidence. Idempotent
580    /// calls require a stable key, compensatable calls require a registered
581    /// rollback handler, and non-idempotent calls atomically consume an
582    /// approval token for this exact content-addressed occurrence. Cloned
583    /// contexts share the same approval ledger, so one token admits one call
584    /// across parallel nodes and later super-steps.
585    pub fn admit(&self, request: &EffectRequest) -> Result<EffectPermit, EffectViolation> {
586        let effect_id = request.effect_id(self.scope());
587        let (compensation, approval) = match request.effect() {
588            Effect::Pure | Effect::ReadOnly => (None, None),
589            Effect::Idempotent => {
590                if request.idempotency_key().is_none() {
591                    return Err(EffectViolation::MissingIdempotencyKey {
592                        kind: request.kind().to_owned(),
593                    });
594                }
595                (None, None)
596            }
597            Effect::Compensatable => (
598                Some(
599                    self.compensations
600                        .handler_for(request.kind())
601                        .cloned()
602                        .ok_or_else(|| EffectViolation::MissingCompensation {
603                            kind: request.kind().to_owned(),
604                        })?,
605                ),
606                None,
607            ),
608            Effect::NonIdempotent => {
609                let approval = self
610                    .approvals
611                    .lock()
612                    .unwrap_or_else(|e| e.into_inner())
613                    .remove(&effect_id)
614                    .ok_or_else(|| EffectViolation::MissingApproval {
615                        kind: request.kind().to_owned(),
616                        effect_id: effect_id.clone(),
617                    })?;
618                (None, Some(approval))
619            }
620        };
621        Ok(EffectPermit {
622            effect_id,
623            compensation,
624            approval,
625        })
626    }
627}
628
629/// Evidence that one runtime effect occurrence passed admission.
630///
631/// The permit deliberately owns the selected compensation handler. The tool
632/// dispatcher keeps it alive until the call completes, preventing a registry
633/// update from removing the rollback path after admission but before the
634/// effect finishes.
635#[derive(Clone)]
636pub struct EffectPermit {
637    effect_id: EffectId,
638    compensation: Option<CompensationHandler>,
639    approval: Option<ApprovalToken>,
640}
641
642impl std::fmt::Debug for EffectPermit {
643    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
644        f.debug_struct("EffectPermit")
645            .field("effect_id", &self.effect_id)
646            .field("has_compensation", &self.compensation.is_some())
647            .field(
648                "approved_by",
649                &self.approval.as_ref().map(ApprovalToken::approved_by),
650            )
651            .finish()
652    }
653}
654
655impl EffectPermit {
656    /// The admitted occurrence's deterministic id.
657    pub fn effect_id(&self) -> &EffectId {
658        &self.effect_id
659    }
660
661    /// The rollback handler captured for a compensatable occurrence.
662    pub fn compensation(&self) -> Option<&CompensationHandler> {
663        self.compensation.as_ref()
664    }
665
666    /// The one-shot approval consumed for an irreversible occurrence.
667    pub fn approval(&self) -> Option<&ApprovalToken> {
668        self.approval.as_ref()
669    }
670}
671
672/// The marker/class agreement check every admission helper runs first.
673///
674/// The marker traits carry no methods, so a mismatched pair (`impl
675/// IrreversibleEffect` with `EFFECT = Effect::Pure`) compiles; it must not
676/// *pass*. Checking at admission keeps the typed API honest without needing
677/// compile-fail machinery: a lying declaration is rejected where it would be
678/// exploited.
679fn check_declaration<E: TypedEffect>(effect: &E, marker: Effect) -> Result<(), EffectViolation> {
680    if E::EFFECT != marker {
681        return Err(EffectViolation::DeclarationMismatch {
682            kind: effect.kind().to_owned(),
683            marker,
684            declared: E::EFFECT,
685        });
686    }
687    Ok(())
688}
689
690/// Admit a [`PureEffect`] to caching/speculation.
691///
692/// Always succeeds for an honestly declared type — the helper exists so the
693/// speculator's call site names the precondition it relies on, and so a
694/// mismatched declaration (marker trait disagreeing with
695/// [`TypedEffect::EFFECT`]) is caught here rather than after a speculated
696/// side effect.
697pub fn admit_speculation<E: PureEffect>(effect: &E) -> Result<(), EffectViolation> {
698    check_declaration::<E>(effect, Effect::Pure)
699}
700
701/// Admit an [`IdempotentEffect`] to automatic retry.
702///
703/// The typed form of the [`crate::durable::classify_retry`] effect gate, with
704/// the convention made checkable: the effect must carry the idempotency key
705/// its declaration means nothing without. Untyped `Effect` values keep their
706/// R0.6 behavior exactly — this helper gates only the typed path.
707pub fn admit_retry<E: IdempotentEffect>(effect: &E) -> Result<(), EffectViolation> {
708    check_declaration::<E>(effect, Effect::Idempotent)?;
709    if effect.idempotency_key().is_none() {
710        return Err(EffectViolation::MissingIdempotencyKey {
711            kind: effect.kind().to_owned(),
712        });
713    }
714    Ok(())
715}
716
717/// Admit a [`CompensatableEffect`] to execute, returning its registered
718/// rollback handler.
719///
720/// The handler is returned — not merely checked — so the caller holds the
721/// undo path from the moment the effect is admitted; an effect whose kind
722/// has no registered handler is rejected.
723pub fn admit_compensatable<E: CompensatableEffect>(
724    effect: &E,
725    registry: &CompensationRegistry,
726) -> Result<CompensationHandler, EffectViolation> {
727    check_declaration::<E>(effect, Effect::Compensatable)?;
728    registry.handler_for(effect.kind()).cloned().ok_or_else(|| {
729        EffectViolation::MissingCompensation {
730            kind: effect.kind().to_owned(),
731        }
732    })
733}
734
735/// Admit an [`IrreversibleEffect`] to execute behind an explicit approval.
736///
737/// `scope` must be the run scope the effect id was (and will be) derived in
738/// — the same value recovery uses to re-derive the id. The presented token
739/// must be scoped to exactly that id; anything else — no token, or a token
740/// for another occurrence — is rejected. The approval boundary this wave
741/// lands as a helper becomes an executor enforcement point in a later wave.
742pub fn admit_irreversible<E: IrreversibleEffect>(
743    effect: &E,
744    scope: &str,
745    approval: Option<&ApprovalToken>,
746) -> Result<(), EffectViolation> {
747    check_declaration::<E>(effect, Effect::NonIdempotent)?;
748    let required = effect.effect_id(scope);
749    let token = approval.ok_or_else(|| EffectViolation::MissingApproval {
750        kind: effect.kind().to_owned(),
751        effect_id: required.clone(),
752    })?;
753    if !token.admits(&required) {
754        return Err(EffectViolation::ApprovalScopeMismatch {
755            kind: effect.kind().to_owned(),
756            required,
757            presented: token.effect_id().clone(),
758        });
759    }
760    Ok(())
761}
762
763#[cfg(test)]
764mod tests {
765    use super::*;
766
767    #[test]
768    fn effect_id_derivation_is_deterministic_and_scoped() {
769        let a = derive_effect_id("run-1", "charge_card", "abc123", Some("key-7"));
770        let b = derive_effect_id("run-1", "charge_card", "abc123", Some("key-7"));
771        assert_eq!(a, b, "same inputs must derive the same id");
772        assert_eq!(a.as_str().len(), 64, "ids are hex SHA-256 digests");
773
774        // Every tuple component is load-bearing.
775        assert_ne!(
776            a,
777            derive_effect_id("run-2", "charge_card", "abc123", Some("key-7"))
778        );
779        assert_ne!(
780            a,
781            derive_effect_id("run-1", "refund", "abc123", Some("key-7"))
782        );
783        assert_ne!(
784            a,
785            derive_effect_id("run-1", "charge_card", "def456", Some("key-7"))
786        );
787        assert_ne!(
788            a,
789            derive_effect_id("run-1", "charge_card", "abc123", Some("key-8"))
790        );
791        assert_ne!(a, derive_effect_id("run-1", "charge_card", "abc123", None));
792    }
793
794    #[test]
795    fn effect_id_is_serde_transparent() {
796        let id = derive_effect_id("run-1", "charge_card", "abc123", None);
797        let value = serde_json::to_value(&id).unwrap();
798        assert_eq!(value, serde_json::json!(id.as_str()));
799        let back: EffectId = serde_json::from_value(value).unwrap();
800        assert_eq!(back, id);
801    }
802}