Skip to main content

reef_core/runtime/
hook.rs

1//! Capability-scoped hooks and immutable registration.
2//!
3//! The inventory is fixed data rather than prose: `HOOK_INVENTORY` names every
4//! callback with its family, scope and decision, and the gate asserts that each
5//! entry has a production dispatcher. ADR-003 fixes the inventory.
6//! Approval policy, waiters, producer authority, session leases, and tool gates
7//! are intentionally absent from every hook scope.
8
9use std::cell::RefCell;
10use std::error::Error;
11use std::fmt;
12use std::panic::{AssertUnwindSafe, catch_unwind};
13use std::sync::Arc;
14
15use crate::cancel::Token;
16
17use crate::audit;
18use crate::redact::Presence;
19use crate::runtime::event::StopCode;
20use crate::runtime::model::{self, CompletionReason, Info, Request, RequestPlan};
21use crate::runtime::session::InputTarget;
22use crate::runtime::tool::{CallDisposition, StepToolSnapshot};
23use crate::state::run_state::{self};
24use crate::state::session_state::{self, CallbackWritePermit};
25use crate::transcript::item::{Assistant, Item};
26use crate::transcript::store::{
27    self, Appender, Replacer, Snapshot, SnapshotReader, Store, Version,
28};
29use crate::value::content::Part;
30use crate::value::lifecycle::{Coord, Outcome};
31use crate::value::tool_call::{ToolCall, ToolResult};
32
33/// A callback family implemented by one narrow trait.
34#[cfg(test)]
35#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
36#[non_exhaustive]
37pub(crate) enum HookFamily {
38    /// Run preparation, continuation, and natural finalization.
39    Run,
40    /// Injected-input admission.
41    Input,
42    /// Turn and Step boundaries.
43    TurnStep,
44    /// Model request/output boundaries.
45    Model,
46    /// Tool-call and tool-result boundaries.
47    Tool,
48    /// Passive observations.
49    Observer,
50    /// Transcript pre-commit reservation.
51    Transcript,
52    /// Agent teardown, separate from runtime hooks.
53    AgentTeardown,
54}
55
56/// The fourteen capability-scoped context shapes in the immutable baseline.
57#[cfg(test)]
58#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
59#[non_exhaustive]
60pub(crate) enum ScopeKind {
61    /// Run preparation.
62    Prepare,
63    /// Natural Run finalization.
64    Finalize,
65    /// Prospective-Step continuation.
66    Continue,
67    /// Injected-input admission.
68    InputAdmit,
69    /// Turn boundary.
70    Turn,
71    /// Writable Step preparation.
72    BeforeStep,
73    /// Read-only completed Step.
74    AfterStep,
75    /// Before model invocation.
76    BeforeModel,
77    /// After model output assembly.
78    AfterModel,
79    /// Before tool admission.
80    ToolCall,
81    /// Before tool-result commit.
82    ToolResult,
83    /// After durable tool execution.
84    AfterToolCommit,
85    /// Passive observation with audit-only emission.
86    Observer,
87    /// Fully read-only, non-emitting callback.
88    Read,
89}
90
91/// The closed decision families, one per callback whose return steers the runtime.
92///
93/// Two of the nine are additions this implementation makes over the shape it
94/// inherited: [`DecisionKind::Prepare`] and [`DecisionKind::Finalize`] exist for
95/// one reason stated twice. Composing initial input and composing continuation
96/// input through a bare part list cannot tell "I have no opinion" apart from
97/// "replace what everyone before me composed with nothing".
98#[cfg(test)]
99#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
100#[non_exhaustive]
101pub(crate) enum DecisionKind {
102    /// Model request control.
103    BeforeModel,
104    /// Model output rewrite.
105    AfterModel,
106    /// Tool-call control.
107    ToolCall,
108    /// Tool-result rewrite.
109    ToolResult,
110    /// Injected-input admission.
111    InputAdmit,
112    /// Run continuation or the sole hook stop request.
113    Continue,
114    /// Step completion and optional Turn close.
115    AfterStep,
116    /// Initial input composition.
117    Prepare,
118    /// Natural-completion continuation composition.
119    Finalize,
120}
121
122/// One mechanically reviewable callback-to-capability mapping.
123#[cfg(test)]
124#[derive(Clone, Copy, Debug, Eq, PartialEq)]
125#[non_exhaustive]
126pub(crate) struct HookSpec {
127    /// Stable callback spelling; crate-private dispatch key, not a public
128    /// contract. The `On*` strings are internal inventory IDs.
129    pub(crate) name: &'static str,
130    /// Narrow trait family which owns the callback.
131    pub(crate) family: HookFamily,
132    /// Scope, or `None` when the callback has no runtime scope.
133    pub(crate) scope: Option<ScopeKind>,
134    /// Closed decision, or `None` when the return is observation/items/reservation.
135    pub(crate) decision: Option<DecisionKind>,
136}
137
138#[cfg(test)]
139pub(crate) const fn hook(
140    name: &'static str,
141    family: HookFamily,
142    scope: Option<ScopeKind>,
143    decision: Option<DecisionKind>,
144) -> HookSpec {
145    HookSpec {
146        name,
147        family,
148        scope,
149        decision,
150    }
151}
152
153/// The complete callback inventory: every runtime callback plus Agent teardown.
154///
155/// The `On*` strings are crate-private dispatch keys (internal IDs), not a
156/// public contract. Consumers implement the family traits; they never name
157/// these spellings.
158///
159/// This is a slice rather than a fixed-size array on purpose. The number of
160/// callbacks is data, not type: baking it into the signature would make every
161/// added or removed hook a breaking change for callers that never counted them.
162#[cfg(test)]
163pub(crate) const HOOK_INVENTORY: &[HookSpec] = &[
164    hook(
165        "OnPrepareRun",
166        HookFamily::Run,
167        Some(ScopeKind::Prepare),
168        Some(DecisionKind::Prepare),
169    ),
170    hook(
171        "OnFinalizeRun",
172        HookFamily::Run,
173        Some(ScopeKind::Finalize),
174        Some(DecisionKind::Finalize),
175    ),
176    hook(
177        "OnRunAdmitted",
178        HookFamily::Observer,
179        Some(ScopeKind::Read),
180        None,
181    ),
182    hook(
183        "OnBeforeToolCall",
184        HookFamily::Tool,
185        Some(ScopeKind::ToolCall),
186        Some(DecisionKind::ToolCall),
187    ),
188    hook(
189        "OnBeforeToolResult",
190        HookFamily::Tool,
191        Some(ScopeKind::ToolResult),
192        Some(DecisionKind::ToolResult),
193    ),
194    hook(
195        "OnAfterToolExecute",
196        HookFamily::Tool,
197        Some(ScopeKind::AfterToolCommit),
198        None,
199    ),
200    hook(
201        "OnBeforeModel",
202        HookFamily::Model,
203        Some(ScopeKind::BeforeModel),
204        Some(DecisionKind::BeforeModel),
205    ),
206    hook(
207        "OnAfterModel",
208        HookFamily::Model,
209        Some(ScopeKind::AfterModel),
210        Some(DecisionKind::AfterModel),
211    ),
212    hook(
213        "OnBeforeInputAdmit",
214        HookFamily::Input,
215        Some(ScopeKind::InputAdmit),
216        Some(DecisionKind::InputAdmit),
217    ),
218    hook(
219        "OnBeforeTurn",
220        HookFamily::TurnStep,
221        Some(ScopeKind::Turn),
222        None,
223    ),
224    hook(
225        "OnAfterTurn",
226        HookFamily::TurnStep,
227        Some(ScopeKind::Turn),
228        None,
229    ),
230    hook(
231        "OnBeforeStep",
232        HookFamily::TurnStep,
233        Some(ScopeKind::BeforeStep),
234        None,
235    ),
236    hook(
237        "OnAfterStep",
238        HookFamily::TurnStep,
239        Some(ScopeKind::AfterStep),
240        Some(DecisionKind::AfterStep),
241    ),
242    hook("OnClose", HookFamily::AgentTeardown, None, None),
243    hook(
244        "OnContinueRun",
245        HookFamily::Run,
246        Some(ScopeKind::Continue),
247        Some(DecisionKind::Continue),
248    ),
249    hook(
250        "OnRunStart",
251        HookFamily::Observer,
252        Some(ScopeKind::Observer),
253        None,
254    ),
255    hook(
256        "OnRunEnd",
257        HookFamily::Observer,
258        Some(ScopeKind::Observer),
259        None,
260    ),
261    hook(
262        "OnTurnStart",
263        HookFamily::Observer,
264        Some(ScopeKind::Observer),
265        None,
266    ),
267    hook(
268        "OnTurnEnd",
269        HookFamily::Observer,
270        Some(ScopeKind::Observer),
271        None,
272    ),
273    hook(
274        "OnStepStart",
275        HookFamily::Observer,
276        Some(ScopeKind::Observer),
277        None,
278    ),
279    hook(
280        "OnStepEnd",
281        HookFamily::Observer,
282        Some(ScopeKind::Observer),
283        None,
284    ),
285    hook(
286        "OnGenerationStart",
287        HookFamily::Observer,
288        Some(ScopeKind::Observer),
289        None,
290    ),
291    hook(
292        "OnGenerationEnd",
293        HookFamily::Observer,
294        Some(ScopeKind::Observer),
295        None,
296    ),
297    hook(
298        "OnToolCallStart",
299        HookFamily::Observer,
300        Some(ScopeKind::Observer),
301        None,
302    ),
303    hook(
304        "OnToolCallEnd",
305        HookFamily::Observer,
306        Some(ScopeKind::Observer),
307        None,
308    ),
309    hook(
310        "OnModelEvent",
311        HookFamily::Observer,
312        Some(ScopeKind::Observer),
313        None,
314    ),
315    hook(
316        "OnAuditEvent",
317        HookFamily::Observer,
318        Some(ScopeKind::Read),
319        None,
320    ),
321    hook(
322        "OnTranscriptMutation",
323        HookFamily::Transcript,
324        Some(ScopeKind::Read),
325        None,
326    ),
327];
328
329/// Boxed hook callback error which preserves the concrete source for downcast.
330///
331/// # Effect on the Run
332///
333/// Returning one of these is a decision that the Run should not continue, not a
334/// hint that something went wrong. Reef never retries a callback, substitutes a
335/// default decision, or carries on with the remaining registrations: the failing
336/// boundary short-circuits, and whatever it had composed, staged, or planned is
337/// discarded rather than half-applied. Peers registered after the failure are not
338/// called, and peers that already ran do not have their contributions kept.
339///
340/// The failure always reaches the caller with the failing registration's name
341/// attached, as an [`AttributedError`]. Where it surfaces depends only on which
342/// boundary was running:
343///
344/// - At Run admission, as
345///   [`StartError::Prepare`](crate::runtime::agent::StartError::Prepare). The
346///   Session lease and Agent attachment are rolled back, so admission having
347///   failed means nothing was committed and no Run exists.
348/// - At every other boundary, by ending the Run: its
349///   [`Terminal`](crate::runtime::run::Terminal) reports
350///   [`Outcome::Failed`] with the
351///   [`FailureKind`](crate::runtime::run::FailureKind) of the boundary that was
352///   running — [`Hook`](crate::runtime::run::FailureKind::Hook) for most,
353///   [`Transcript`](crate::runtime::run::FailureKind::Transcript) or
354///   [`ToolCommit`](crate::runtime::run::FailureKind::ToolCommit) for a failed
355///   reservation, according to which mutation it was reserving. The retained
356///   failure is reachable from the terminal, and the registration name survives
357///   the whole chain.
358///
359/// A cancellation observed at the same boundary ends the Run as
360/// [`Cancelled`](crate::value::lifecycle::Outcome::Cancelled) instead; a real
361/// callback error is never downgraded to a cancellation.
362///
363/// This is why a degradation the Run can survive should not be reported this way.
364/// [`Emitter::emit_error`] publishes a non-fatal fact and leaves the Run running,
365/// which is the right shape for a hook whose optional work failed. `HookError`
366/// is for the case where continuing would be wrong.
367#[derive(Clone)]
368pub struct HookError(Arc<dyn Error + Send + Sync>);
369
370impl HookError {
371    /// Retains a concrete callback error without string flattening.
372    #[must_use]
373    pub fn new(error: impl Error + Send + Sync + 'static) -> Self {
374        Self(Arc::new(error))
375    }
376
377    /// Returns the retained concrete source.
378    #[must_use]
379    pub fn source_ref(&self) -> &(dyn Error + Send + Sync + 'static) {
380        self.0.as_ref()
381    }
382}
383
384impl fmt::Debug for HookError {
385    /// Renders every link of the retained chain, each one through `Display`.
386    ///
387    /// Printing only the outermost link would discard the chain that
388    /// [`source_ref`] retains: a callback error that wraps its own cause reads
389    /// as a single sentence, and the reason underneath it — the one a reader is
390    /// usually after — never appears. Walking `source` states the whole chain.
391    ///
392    /// `Display` rather than the link's own `Debug`, because the cause is
393    /// whatever a hook handed back: arbitrary text this crate neither writes
394    /// nor reviews. `Display` is the rendering those types are contracted to
395    /// produce, and it is what every other boxed failure in reef prints.
396    ///
397    /// [`source_ref`]: Self::source_ref
398    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
399        let mut tuple = formatter.debug_tuple("HookError");
400        let mut link: Option<&(dyn Error + 'static)> = Some(self.0.as_ref());
401        while let Some(error) = link {
402            tuple.field(&error.to_string());
403            link = error.source();
404        }
405        tuple.finish()
406    }
407}
408
409impl fmt::Display for HookError {
410    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
411        self.0.fmt(formatter)
412    }
413}
414
415impl Error for HookError {
416    fn source(&self) -> Option<&(dyn Error + 'static)> {
417        Some(self.0.as_ref())
418    }
419}
420
421/// Result returned by a mutating or reserving callback.
422pub type HookResult<T> = Result<T, HookError>;
423
424/// Stable Session identity without transcript, inbox, state-write, or lease authority.
425#[derive(Clone, Copy, Debug)]
426pub struct SessionIdentity<'a>(&'a Coord);
427
428impl SessionIdentity<'_> {
429    /// Returns the Session identifier carried by the callback coordinate.
430    #[must_use]
431    pub fn id(&self) -> &str {
432        self.0.session_id()
433    }
434}
435
436/// A callback-local transcript capability.
437///
438/// The controller creates this from an isolated [`Store`]. Exposing only these
439/// three facets prevents ordinary scopes from reaching the live Session
440/// transcript while preserving the staging semantics: a callback reads and
441/// appends against its own snapshot, and nothing it does is visible until the
442/// controller commits.
443#[derive(Debug)]
444pub struct StagedTranscript {
445    reader: SnapshotReader,
446    appender: Appender,
447    replacer: Replacer,
448}
449
450impl StagedTranscript {
451    pub(crate) fn from_store(store: &Store) -> Self {
452        Self {
453            reader: store.snapshot_reader(),
454            appender: store.appender(),
455            replacer: store.replacer(),
456        }
457    }
458
459    /// Captures the callback-local staged history.
460    ///
461    /// # Errors
462    ///
463    /// [`store::Error::Poisoned`] if a writer panicked inside this staging area.
464    /// The area is private to one callback invocation, so that means a panic in
465    /// this callback or in a peer sharing the same staged boundary.
466    pub fn snapshot(&self) -> Result<Snapshot, store::Error> {
467        self.reader.snapshot()
468    }
469
470    /// Appends an ordered owned batch to this callback's staging area.
471    ///
472    /// # Errors
473    ///
474    /// [`store::Error::VersionOverflow`] if the staged version would pass
475    /// [`Version::MAX`], or [`store::Error::Poisoned`] as
476    /// [`snapshot`](Self::snapshot) describes. There is no version conflict to
477    /// report, because this append names no expected version: composing into a
478    /// staging area is not a race against the live transcript, and what the
479    /// boundary later commits is compare-and-set against the live version for the
480    /// registrations as a whole.
481    pub fn append_batch(&self, items: Vec<Item>) -> Result<Version, store::Error> {
482        self.appender.append_batch(items)
483    }
484
485    /// Replaces this callback's complete staged history.
486    ///
487    /// # Errors
488    ///
489    /// [`store::Error::VersionOverflow`] or [`store::Error::Poisoned`], for the
490    /// same reasons as [`append_batch`](Self::append_batch). Replacing the staged
491    /// history does not replace the live one; what reaches the session is the
492    /// resolved staged result, committed by the boundary that created this
493    /// capability.
494    pub fn replace(&self, items: Vec<Item>) -> Result<Version, store::Error> {
495        self.replacer.replace(items)
496    }
497}
498
499/// The only outward capability available to mutating hook scopes.
500pub trait Emitter: Send + Sync {
501    /// Emits a validated, non-model-visible audit fact.
502    fn emit_audit(&self, event: audit::Event);
503
504    /// Emits a non-fatal error fact without granting event producer authority.
505    fn emit_error(&self, error: Arc<dyn Error + Send + Sync>);
506}
507
508/// One fact a synchronous callback handed to the loop for publication.
509#[derive(Debug)]
510pub(crate) enum BufferedFact {
511    Audit(audit::Event),
512    Error(Arc<dyn Error + Send + Sync>),
513}
514
515/// The [`Emitter`] every synchronous callback on the loop's own thread writes to.
516///
517/// A callback is synchronous and the outward stream is not, so no callback can
518/// publish anything itself: it records the fact here and the loop hands the queue
519/// to the `Producer` at its next await point. The queue is FIFO and every drain is
520/// total, so the only latitude the loop has is *when* it drains — and it drains
521/// before its own next publication. That is what makes
522/// [`ObserverScope::emit_audit`] mean "now" instead of "some time before this Run
523/// ends": a fact queued while the model stream is still arriving reaches the
524/// consumer ahead of the content event that follows it.
525///
526/// The one exception is a callback running on the managed blocking pool, which
527/// cannot use a buffer at all: it has already returned control to no one, so it
528/// emits through a request/ack rendezvous with the loop instead.
529#[derive(Debug, Default)]
530pub(crate) struct FactBuffer {
531    facts: std::sync::Mutex<Vec<BufferedFact>>,
532}
533
534impl FactBuffer {
535    /// Removes and returns every queued fact, preserving producer order.
536    pub(crate) fn take_facts(&self) -> Vec<BufferedFact> {
537        std::mem::take(&mut *self.facts.lock().expect("hook fact lock poisoned"))
538    }
539
540    #[cfg(test)]
541    pub(crate) fn audit_kinds(&self) -> Vec<String> {
542        self.facts
543            .lock()
544            .expect("hook fact lock poisoned")
545            .iter()
546            .filter_map(|fact| match fact {
547                BufferedFact::Audit(event) => Some(event.kind().to_owned()),
548                BufferedFact::Error(_) => None,
549            })
550            .collect()
551    }
552
553    #[cfg(test)]
554    pub(crate) fn error_messages(&self) -> Vec<String> {
555        self.facts
556            .lock()
557            .expect("hook fact lock poisoned")
558            .iter()
559            .filter_map(|fact| match fact {
560                BufferedFact::Audit(_) => None,
561                BufferedFact::Error(error) => Some(error.to_string()),
562            })
563            .collect()
564    }
565}
566
567impl Emitter for FactBuffer {
568    fn emit_audit(&self, event: audit::Event) {
569        self.facts
570            .lock()
571            .expect("hook fact lock poisoned")
572            .push(BufferedFact::Audit(event));
573    }
574
575    fn emit_error(&self, error: Arc<dyn Error + Send + Sync>) {
576        self.facts
577            .lock()
578            .expect("hook fact lock poisoned")
579            .push(BufferedFact::Error(error));
580    }
581}
582
583#[derive(Clone, Copy, Debug)]
584struct ReadBase<'a> {
585    session: SessionIdentity<'a>,
586    coord: &'a Coord,
587    run_state: &'a run_state::Store,
588    session_state: &'a session_state::Reader,
589}
590
591#[derive(Clone, Copy, Debug)]
592struct WriteBase<'a> {
593    read: ReadBase<'a>,
594    session_state: Option<&'a session_state::Writer>,
595}
596
597#[derive(Clone, Copy, Debug)]
598struct PrepareBase<'a> {
599    read: ReadBase<'a>,
600    session_state: Option<&'a session_state::StagedWriter>,
601}
602
603#[derive(Clone, Copy)]
604struct ControlBase<'a> {
605    write: WriteBase<'a>,
606    emitter: &'a dyn Emitter,
607}
608
609impl fmt::Debug for ControlBase<'_> {
610    /// Shows the read/write position and elides the emitter behind it.
611    ///
612    /// `Emitter` is a public trait with no `Debug` supertrait, so an
613    /// implementation's identity is not reef's to print. The trailing `..`
614    /// records that something is there rather than implying nothing is.
615    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
616        formatter
617            .debug_struct("ControlBase")
618            .field("write", &self.write)
619            .finish_non_exhaustive()
620    }
621}
622
623#[derive(Clone, Copy, Debug)]
624struct StagedBase<'a> {
625    control: ControlBase<'a>,
626    staged: &'a StagedTranscript,
627}
628
629macro_rules! read_capabilities {
630    ($this:ident, $base:expr) => {
631        /// Returns stable Session identity without broader Session authority.
632        #[must_use]
633        pub const fn session(&$this) -> SessionIdentity<'_> {
634            $base.read.session
635        }
636
637        /// Returns the immutable callback coordinate.
638        #[must_use]
639        pub const fn coord(&$this) -> &Coord {
640            $base.read.coord
641        }
642
643        /// Returns this hook's private per-Run scratch store.
644        #[must_use]
645        pub const fn run_state(&$this) -> &run_state::Store {
646            $base.read.run_state
647        }
648
649        /// Returns owned-snapshot Session-state read authority.
650        #[must_use]
651        pub const fn session_state(&$this) -> &session_state::Reader {
652            $base.read.session_state
653        }
654    };
655}
656
657macro_rules! direct_read_capabilities {
658    ($this:ident, $base:expr) => {
659        /// Returns stable Session identity without broader Session authority.
660        #[must_use]
661        pub const fn session(&$this) -> SessionIdentity<'_> {
662            $base.session
663        }
664
665        /// Returns the immutable callback coordinate.
666        #[must_use]
667        pub const fn coord(&$this) -> &Coord {
668            $base.coord
669        }
670
671        /// Returns this hook's private per-Run scratch store.
672        #[must_use]
673        pub const fn run_state(&$this) -> &run_state::Store {
674            $base.run_state
675        }
676
677        /// Returns owned-snapshot Session-state read authority.
678        #[must_use]
679        pub const fn session_state(&$this) -> &session_state::Reader {
680            $base.session_state
681        }
682    };
683}
684
685macro_rules! write_capabilities {
686    ($this:ident, $base:expr) => {
687        read_capabilities!($this, $base);
688
689        /// Returns lease-bound write authority only for a hook which declared
690        /// `requires_session_state(true)`.
691        #[must_use]
692        pub const fn session_state_writer(&$this) -> Option<&session_state::Writer> {
693            $base.session_state
694        }
695    };
696}
697
698macro_rules! control_capabilities {
699    ($this:ident, $base:expr) => {
700        write_capabilities!($this, $base.write);
701
702        /// Emits an audit fact through the capability-narrowed boundary.
703        pub fn emit_audit(&$this, event: audit::Event) {
704            $base.emitter.emit_audit(event);
705        }
706
707        /// Emits a non-fatal error through the capability-narrowed boundary.
708        pub fn emit_error(&$this, error: Arc<dyn Error + Send + Sync>) {
709            $base.emitter.emit_error(error);
710        }
711    };
712}
713
714macro_rules! staged_capabilities {
715    ($this:ident, $base:expr) => {
716        control_capabilities!($this, $base.control);
717
718        /// Returns this callback's isolated transcript staging area.
719        #[must_use]
720        pub const fn staged(&$this) -> &StagedTranscript {
721            $base.staged
722        }
723    };
724}
725
726/// [`RunHooks::prepare`] scope; no outward stream exists at this boundary.
727///
728/// Both writable capabilities are callback-local overlays. The controller owns
729/// their resolution and this scope cannot mutate the live Session directly.
730#[derive(Debug)]
731pub struct PrepareScope<'a> {
732    base: PrepareBase<'a>,
733    staged: &'a StagedTranscript,
734    base_snapshot: &'a Snapshot,
735    input: &'a [Part],
736}
737
738impl PrepareScope<'_> {
739    direct_read_capabilities!(self, self.base.read);
740
741    /// Returns the callback-local Session-state overlay when this registration
742    /// declared `requires_session_state(true)`.
743    #[must_use]
744    pub const fn staged_session_state_writer(&self) -> Option<&session_state::StagedWriter> {
745        self.base.session_state
746    }
747
748    /// Returns this callback's isolated transcript staging area.
749    #[must_use]
750    pub const fn staged(&self) -> &StagedTranscript {
751        self.staged
752    }
753
754    /// Returns the pre-prepare atomic transcript snapshot.
755    #[must_use]
756    pub const fn base_snapshot(&self) -> &Snapshot {
757        self.base_snapshot
758    }
759
760    /// Returns the current composed input proposal.
761    #[must_use]
762    pub const fn input(&self) -> &[Part] {
763        self.input
764    }
765}
766
767/// [`RunHooks::compose_continuation`] scope on the natural completion path.
768#[derive(Debug)]
769pub struct ContinuationScope<'a> {
770    base: StagedBase<'a>,
771    continuation: &'a [Part],
772    continuations: usize,
773    turns: usize,
774}
775
776impl ContinuationScope<'_> {
777    staged_capabilities!(self, self.base);
778
779    /// Returns the preceding hook's continuation proposal.
780    #[must_use]
781    pub const fn continuation(&self) -> &[Part] {
782        self.continuation
783    }
784
785    /// Returns the number of prior continuation Turns.
786    #[must_use]
787    pub const fn continuations(&self) -> usize {
788        self.continuations
789    }
790
791    /// Returns the number of completed Turns.
792    #[must_use]
793    pub const fn turns(&self) -> usize {
794        self.turns
795    }
796}
797
798/// [`RunHooks::decide_stop`] scope before a prospective Step exists.
799#[derive(Debug)]
800pub struct StopDecisionScope<'a> {
801    base: ControlBase<'a>,
802}
803
804impl StopDecisionScope<'_> {
805    control_capabilities!(self, self.base);
806}
807
808/// [`InputHooks::before_input_admit`] scope around one claimed owned batch.
809#[derive(Debug)]
810pub struct InputAdmitScope<'a> {
811    base: ControlBase<'a>,
812    target: InputTarget,
813    items: &'a [Item],
814}
815
816impl InputAdmitScope<'_> {
817    control_capabilities!(self, self.base);
818
819    /// Returns the frozen mailbox target.
820    #[must_use]
821    pub const fn target(&self) -> InputTarget {
822        self.target
823    }
824
825    /// Returns the claimed batch as a read-only slice.
826    #[must_use]
827    pub const fn items(&self) -> &[Item] {
828        self.items
829    }
830}
831
832/// Shared scope for true Turn boundary hooks.
833#[derive(Debug)]
834pub struct TurnScope<'a> {
835    base: StagedBase<'a>,
836    trigger: &'a [Item],
837}
838
839impl TurnScope<'_> {
840    staged_capabilities!(self, self.base);
841
842    /// Returns the input batch which opened this Turn.
843    #[must_use]
844    pub const fn trigger(&self) -> &[Item] {
845        self.trigger
846    }
847}
848
849/// One owned, immutable Step fact frozen after the sole writable plan window.
850///
851/// The runtime creates this once per Step and reuses the same [`Arc`] at every
852/// later hook and lifecycle boundary. The owned plan retains all five lanes:
853/// system instruction, client tools, sampling parameters, hosted extensions,
854/// and ephemeral content. The tool snapshot preserves the exact routing handles
855/// from which the model-visible tool lanes were materialized.
856#[derive(Debug)]
857pub struct StepSnapshot {
858    model: Info,
859    plan: RequestPlan,
860    tools: StepToolSnapshot,
861    shared_tools: Arc<StepToolSnapshot>,
862}
863
864impl StepSnapshot {
865    pub(crate) fn freeze(model: Info, plan: RequestPlan, tools: StepToolSnapshot) -> Arc<Self> {
866        // `StepToolSnapshot::shallow_clone` preserves the same executor/mapper
867        // handles and transcript Arc. The public value getter can remain const,
868        // while batch routing receives one shared owner without resolving providers
869        // a second time through `StepToolSnapshot::shallow_clone`.
870        let shared_tools = Arc::new(tools.shallow_clone());
871        Arc::new(Self {
872            model,
873            plan,
874            tools,
875            shared_tools,
876        })
877    }
878
879    /// Returns the complete frozen model identity and capability facts.
880    #[must_use]
881    pub const fn model(&self) -> &Info {
882        &self.model
883    }
884
885    /// Returns the complete frozen plan, including every model-input lane.
886    #[must_use]
887    pub const fn plan(&self) -> &RequestPlan {
888        &self.plan
889    }
890
891    /// Returns the exact immutable exposure/router snapshot for this Step.
892    #[must_use]
893    pub const fn tools(&self) -> &StepToolSnapshot {
894        &self.tools
895    }
896
897    /// Returns the shared shallow twin used by invocation routing.
898    pub(crate) const fn shared_tools(&self) -> &Arc<StepToolSnapshot> {
899        &self.shared_tools
900    }
901}
902
903/// `OnBeforeStep` scope and the sole writable [`RequestPlan`] window.
904#[derive(Debug)]
905pub struct BeforeStepScope<'a> {
906    base: StagedBase<'a>,
907    model: &'a Info,
908    plan: &'a mut RequestPlan,
909}
910
911impl BeforeStepScope<'_> {
912    staged_capabilities!(self, self.base);
913
914    /// Returns immutable model identity and capabilities.
915    #[must_use]
916    pub const fn model(&self) -> &Info {
917        self.model
918    }
919
920    /// Returns the unique plan which runtime re-reads after this fan-out.
921    pub const fn plan(&mut self) -> &mut RequestPlan {
922        self.plan
923    }
924}
925
926/// `OnAfterStep` scope with the shared immutable Step snapshot.
927#[derive(Debug)]
928pub struct AfterStepScope<'a> {
929    base: StagedBase<'a>,
930    snapshot: &'a Arc<StepSnapshot>,
931}
932
933impl AfterStepScope<'_> {
934    staged_capabilities!(self, self.base);
935
936    /// Returns the exact frozen Step snapshot reused by later boundaries.
937    #[must_use]
938    pub fn snapshot(&self) -> &StepSnapshot {
939        self.snapshot
940    }
941}
942
943/// [`ModelHooks::before_model`] scope over one immutable request and Step snapshot.
944#[derive(Debug)]
945pub struct BeforeModelScope<'a> {
946    base: ControlBase<'a>,
947    snapshot: &'a Arc<StepSnapshot>,
948    request: &'a Request,
949}
950
951impl BeforeModelScope<'_> {
952    control_capabilities!(self, self.base);
953
954    /// Returns the exact frozen Step snapshot.
955    #[must_use]
956    pub fn snapshot(&self) -> &StepSnapshot {
957        self.snapshot
958    }
959
960    /// Returns the current frozen request; rewrites use the returned decision.
961    #[must_use]
962    pub const fn request(&self) -> &Request {
963        self.request
964    }
965}
966
967/// [`ModelHooks::after_model`] scope over assembled but uncommitted assistant output.
968#[derive(Debug)]
969pub struct AfterModelScope<'a> {
970    base: ControlBase<'a>,
971    snapshot: &'a Arc<StepSnapshot>,
972    output: &'a Assistant,
973    generated: bool,
974    finish_reason: &'a str,
975    completion: CompletionReason,
976}
977
978impl AfterModelScope<'_> {
979    control_capabilities!(self, self.base);
980
981    /// Returns the exact frozen Step snapshot used for this generation.
982    #[must_use]
983    pub fn snapshot(&self) -> &StepSnapshot {
984        self.snapshot
985    }
986
987    /// Returns the current read-only assistant output.
988    #[must_use]
989    pub const fn output(&self) -> &Assistant {
990        self.output
991    }
992
993    /// Reports whether a real model generation produced this output.
994    #[must_use]
995    pub const fn generated(&self) -> bool {
996        self.generated
997    }
998
999    /// Returns the provider's verbatim finish label, or empty when unavailable.
1000    #[must_use]
1001    pub const fn finish_reason(&self) -> &str {
1002        self.finish_reason
1003    }
1004
1005    /// Returns the portable completion classification.
1006    #[must_use]
1007    pub const fn completion(&self) -> CompletionReason {
1008        self.completion
1009    }
1010}
1011
1012/// `OnBeforeToolCall` scope over one effective call and frozen Step facts.
1013#[derive(Debug)]
1014pub struct ToolCallScope<'a> {
1015    base: ControlBase<'a>,
1016    snapshot: &'a Arc<StepSnapshot>,
1017    call: &'a ToolCall,
1018}
1019
1020impl ToolCallScope<'_> {
1021    control_capabilities!(self, self.base);
1022
1023    /// Returns the exact frozen Step snapshot used by this tool batch.
1024    #[must_use]
1025    pub fn snapshot(&self) -> &StepSnapshot {
1026        self.snapshot
1027    }
1028
1029    /// Returns the current call; rewrites use the returned decision.
1030    #[must_use]
1031    pub const fn call(&self) -> &ToolCall {
1032        self.call
1033    }
1034}
1035
1036/// `OnBeforeToolResult` scope over an uncommitted closed result.
1037#[derive(Debug)]
1038pub struct ToolResultScope<'a> {
1039    base: ControlBase<'a>,
1040    snapshot: &'a Arc<StepSnapshot>,
1041    call: &'a ToolCall,
1042    disposition: CallDisposition,
1043    result: &'a ToolResult,
1044}
1045
1046impl ToolResultScope<'_> {
1047    control_capabilities!(self, self.base);
1048
1049    /// Returns the exact frozen Step snapshot used by this tool batch.
1050    #[must_use]
1051    pub fn snapshot(&self) -> &StepSnapshot {
1052        self.snapshot
1053    }
1054
1055    /// Returns the final effective call.
1056    #[must_use]
1057    pub const fn call(&self) -> &ToolCall {
1058        self.call
1059    }
1060
1061    /// Returns the call's stable pre-result disposition.
1062    #[must_use]
1063    pub const fn disposition(&self) -> CallDisposition {
1064        self.disposition
1065    }
1066
1067    /// Returns the current closed result; rewrites use the decision.
1068    #[must_use]
1069    pub const fn result(&self) -> &ToolResult {
1070        self.result
1071    }
1072}
1073
1074/// [`ToolHooks::after_tool_commit`] scope after the complete result batch is durable.
1075#[derive(Debug)]
1076pub struct AfterToolCommitScope<'a> {
1077    base: StagedBase<'a>,
1078    snapshot: &'a Arc<StepSnapshot>,
1079    result: &'a ToolResult,
1080}
1081
1082impl AfterToolCommitScope<'_> {
1083    staged_capabilities!(self, self.base);
1084
1085    /// Returns the exact frozen Step snapshot used by this tool batch.
1086    #[must_use]
1087    pub fn snapshot(&self) -> &StepSnapshot {
1088        self.snapshot
1089    }
1090
1091    /// Returns the already-durable closed result.
1092    #[must_use]
1093    pub const fn result(&self) -> &ToolResult {
1094        self.result
1095    }
1096}
1097
1098/// Passive observer scope with audit-only emission.
1099pub struct ObserverScope<'a> {
1100    base: ReadBase<'a>,
1101    snapshot: Option<&'a Arc<StepSnapshot>>,
1102    audit_sink: &'a dyn ObserverAuditSink,
1103}
1104
1105impl fmt::Debug for ObserverScope<'_> {
1106    /// Shows where the observation is anchored and elides the audit sink.
1107    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1108        formatter
1109            .debug_struct("ObserverScope")
1110            .field("base", &self.base)
1111            .field("snapshot", &Presence(self.snapshot.is_some()))
1112            .finish_non_exhaustive()
1113    }
1114}
1115
1116impl ObserverScope<'_> {
1117    direct_read_capabilities!(self, self.base);
1118
1119    /// Returns the exact frozen Step snapshot when the boundary belongs to a Step.
1120    #[must_use]
1121    pub fn snapshot(&self) -> Option<&StepSnapshot> {
1122        self.snapshot.map(Arc::as_ref)
1123    }
1124
1125    /// Emits only an audit fact; no generic Error or event authority is present.
1126    pub fn emit_audit(&self, event: audit::Event) {
1127        self.audit_sink.push(event);
1128    }
1129
1130    fn with_audit_sink<'a>(&'a self, audit_sink: &'a dyn ObserverAuditSink) -> ObserverScope<'a> {
1131        ObserverScope {
1132            base: self.base,
1133            snapshot: self.snapshot,
1134            audit_sink,
1135        }
1136    }
1137}
1138
1139trait ObserverAuditSink {
1140    fn push(&self, event: audit::Event);
1141}
1142
1143struct CallbackAuditBuffer {
1144    pending: RefCell<Vec<audit::Event>>,
1145}
1146
1147impl CallbackAuditBuffer {
1148    const fn new() -> Self {
1149        Self {
1150            pending: RefCell::new(Vec::new()),
1151        }
1152    }
1153
1154    /// Hands FIFO facts to `emitter` after either a normal return or a panic.
1155    ///
1156    /// This is the inner of two stages, and it is not publication: it exists so
1157    /// that emission happens outside the callback catch boundary, and what it
1158    /// flushes into is normally a [`FactBuffer`], which queues again. When the
1159    /// fact reaches the consumer is decided there — see [`FactBuffer`] — not
1160    /// here.
1161    fn flush_to(&self, emitter: &dyn Emitter) {
1162        for event in self.pending.borrow_mut().drain(..) {
1163            emitter.emit_audit(event);
1164        }
1165    }
1166}
1167
1168impl ObserverAuditSink for CallbackAuditBuffer {
1169    fn push(&self, event: audit::Event) {
1170        self.pending.borrow_mut().push(event);
1171    }
1172}
1173
1174struct DirectAuditSink<'a>(&'a dyn Emitter);
1175
1176impl ObserverAuditSink for DirectAuditSink<'_> {
1177    fn push(&self, event: audit::Event) {
1178        self.0.emit_audit(event);
1179    }
1180}
1181
1182/// Fully read-only, non-emitting scope used inside serialized critical sections.
1183#[derive(Debug)]
1184pub struct ReadScope<'a> {
1185    base: ReadBase<'a>,
1186}
1187
1188impl ReadScope<'_> {
1189    direct_read_capabilities!(self, self.base);
1190}
1191
1192/// [`RunHooks::prepare`] decision.
1193///
1194/// Registrations run in registration order and each observes the previous one's
1195/// result, so a bare part list would make "I do not compose input" and "replace
1196/// everything composed so far with nothing" the same value — and the last
1197/// registration would win outright. A registration that has no opinion about the
1198/// input returns [`PrepareDecision::Continue`]; only [`PrepareDecision::Modify`]
1199/// rewrites it, and it may not rewrite it to nothing.
1200#[derive(Debug)]
1201pub enum PrepareDecision {
1202    /// Keep the composed input unchanged.
1203    Continue,
1204    /// Replace the composed input before admission.
1205    Modify(Vec<Part>),
1206}
1207
1208/// An invalid [`RunHooks::prepare`] decision produced by a registration.
1209///
1210/// This mirrors the `Modify` rule of [`InputAdmitDecision`]: a rewrite that
1211/// would discard everything is invalid, not a silent no-op. Refusing it here is
1212/// what makes "model-visible implies recorded" hold for the admitted input — a
1213/// registration that blanked the caller's parts would otherwise leave the Run
1214/// with a first request the transcript has no record of.
1215#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1216#[non_exhaustive]
1217pub enum PrepareError {
1218    /// A registration returned `Modify` with an empty replacement.
1219    EmptyModify,
1220}
1221
1222impl fmt::Display for PrepareError {
1223    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1224        match self {
1225            Self::EmptyModify => {
1226                formatter.write_str("a registration rewrote the initial input to nothing")
1227            }
1228        }
1229    }
1230}
1231
1232impl Error for PrepareError {}
1233
1234/// [`RunHooks::compose_continuation`] decision.
1235///
1236/// This is [`PrepareDecision`]'s sibling and exists for the same reason:
1237/// registrations run in registration order and each observes the previous one's
1238/// result, so a bare part list would make "I have no opinion about continuing"
1239/// and "replace the continuation everyone before me asked for with nothing" the
1240/// same value, and the last registration would win outright. A registration with
1241/// no opinion returns [`ContinuationDecision::Keep`]; only
1242/// [`ContinuationDecision::Replace`] rewrites the request.
1243///
1244/// The one place it differs from `PrepareDecision` is that an **empty `Replace`
1245/// is legitimate here**, so there is no `FinalizeError`. A continuation is a
1246/// request for another Turn, not user content: replacing it with nothing is a
1247/// governance hook vetoing a peer's request and ending the Run, which is a
1248/// meaningful answer rather than data loss. `PrepareDecision` refuses an empty
1249/// `Modify` because there the parts *are* the caller's submission, and blanking
1250/// them would leave the Run with a first request the transcript never recorded.
1251#[derive(Debug)]
1252pub enum ContinuationDecision {
1253    /// Keep the accumulated continuation request unchanged.
1254    Keep,
1255    /// Replace the accumulated continuation request; empty ends the Run.
1256    Replace(Vec<Part>),
1257}
1258
1259/// [`ModelHooks::before_model`] decision.
1260///
1261/// [`Self::Modify`] is where a composition layer normalises history for the
1262/// provider it is about to call. Core applies visibility and the tool-exchange
1263/// grammar and stops there: it never rewrites a
1264/// [`Segment`](crate::value::content::Segment) because a different provider
1265/// produced it, because deciding that one vendor's thinking segment is unusable
1266/// by another requires knowing both vendors' rules — a `compat` matrix core does
1267/// not and must not learn. A registration that changes model mid-session reads
1268/// [`BeforeModelScope::request`], rewrites the segments its next provider cannot
1269/// accept, and re-freezes through
1270/// [`RequestPlan::try_into_request`](crate::runtime::model::RequestPlan::try_into_request), which
1271/// is the only way to construct a [`Request`] and therefore cannot be bypassed.
1272#[derive(Debug)]
1273pub enum BeforeModelDecision {
1274    /// Continue with the current request.
1275    Continue,
1276    /// Replace the request after runtime validation.
1277    Modify(Request),
1278    /// Supply assistant output without invoking the model.
1279    ShortCircuit(Assistant),
1280    /// Deliberately abort model invocation.
1281    Abort(String),
1282}
1283
1284/// [`ModelHooks::after_model`] decision.
1285#[derive(Debug)]
1286pub enum AfterModelDecision {
1287    /// Keep assembled output.
1288    Continue,
1289    /// Replace assembled output before commit.
1290    Modify(Assistant),
1291}
1292
1293/// [`ToolHooks::before_tool_call`] decision.
1294#[derive(Debug)]
1295pub enum ToolCallDecision {
1296    /// Continue with the current call.
1297    Continue,
1298    /// Replace the call before the separate Gate plane.
1299    Modify(ToolCall),
1300    /// Block execution with a nonempty hook reason.
1301    Block(String),
1302    /// Supply a closed result without execution.
1303    ShortCircuit(ToolResult),
1304}
1305
1306/// [`ToolHooks::before_tool_result`] decision.
1307#[derive(Debug)]
1308pub enum ToolResultDecision {
1309    /// Keep the current closed result.
1310    Continue,
1311    /// Replace the result before commit and publication.
1312    Modify(ToolResult),
1313}
1314
1315/// [`InputHooks::before_input_admit`] decision.
1316#[derive(Debug)]
1317pub enum InputAdmitDecision {
1318    /// Admit the claimed batch unchanged.
1319    Admit,
1320    /// Replace the claimed batch before append.
1321    Modify(Vec<Item>),
1322    /// Permanently discard the claimed batch with a reason.
1323    Reject(String),
1324}
1325
1326/// [`RunHooks::decide_stop`] decision and the sole hook-initiated stop surface.
1327#[derive(Debug)]
1328pub enum StopDecision {
1329    /// Continue into the prospective Step.
1330    Continue,
1331    /// Ask runtime to emit its unique validated `EventStop`.
1332    Stop(StopCode),
1333}
1334
1335/// [`TurnStepHooks::after_step`] decision.
1336#[derive(Debug)]
1337pub enum AfterStepDecision {
1338    /// Keep the Turn open and append the ordered items.
1339    Continue(Vec<Item>),
1340    /// Close the current Turn after appending the ordered items.
1341    EndTurn(Vec<Item>),
1342}
1343
1344/// The ten lifecycle observation variants, mechanically paired with callbacks.
1345#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1346#[non_exhaustive]
1347pub enum LifecycleKind {
1348    /// `OnRunStart`.
1349    RunStart,
1350    /// `OnRunEnd`.
1351    RunEnd,
1352    /// `OnTurnStart`.
1353    TurnStart,
1354    /// `OnTurnEnd`.
1355    TurnEnd,
1356    /// `OnStepStart`.
1357    StepStart,
1358    /// `OnStepEnd`.
1359    StepEnd,
1360    /// `OnGenerationStart`.
1361    GenerationStart,
1362    /// `OnGenerationEnd`.
1363    GenerationEnd,
1364    /// `OnToolCallStart`.
1365    ToolCallStart,
1366    /// `OnToolCallEnd`.
1367    ToolCallEnd,
1368}
1369
1370/// A closed, internally consistent lifecycle terminal fact.
1371#[derive(Clone)]
1372#[non_exhaustive]
1373pub enum LifecycleEnd {
1374    /// Normal success.
1375    Completed,
1376    /// Consumer or explicit Run stop.
1377    #[non_exhaustive]
1378    Stopped {
1379        /// Optional opaque hook stop code; ordinary consumer stops have none.
1380        code: Option<StopCode>,
1381    },
1382    /// Parent cancellation or deadline.
1383    #[non_exhaustive]
1384    Cancelled {
1385        /// Authoritative cancellation detail.
1386        error: Arc<dyn Error + Send + Sync>,
1387    },
1388    /// Execution or contract failure.
1389    #[non_exhaustive]
1390    Failed {
1391        /// Authoritative failure detail.
1392        error: Arc<dyn Error + Send + Sync>,
1393    },
1394}
1395
1396impl fmt::Debug for LifecycleEnd {
1397    /// Names the ending and renders its cause through `Display`.
1398    ///
1399    /// The error is an arbitrary boxed failure supplied from outside this
1400    /// crate, so its `Debug` is neither written nor reviewed here; `Display` is
1401    /// the diagnostic the error type is contracted to produce, and it is what
1402    /// `HookError` already prints for the same reason.
1403    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1404        match self {
1405            Self::Completed => formatter.write_str("Completed"),
1406            Self::Stopped { code } => formatter
1407                .debug_struct("Stopped")
1408                .field("code", code)
1409                .finish(),
1410            Self::Cancelled { error } => formatter
1411                .debug_struct("Cancelled")
1412                .field("error", &error.to_string())
1413                .finish(),
1414            Self::Failed { error } => formatter
1415                .debug_struct("Failed")
1416                .field("error", &error.to_string())
1417                .finish(),
1418        }
1419    }
1420}
1421
1422impl LifecycleEnd {
1423    /// Returns the authoritative portable outcome.
1424    #[must_use]
1425    pub const fn outcome(&self) -> Outcome {
1426        match self {
1427            Self::Completed => Outcome::Completed,
1428            Self::Stopped { .. } => Outcome::Stopped,
1429            Self::Cancelled { .. } => Outcome::Cancelled,
1430            Self::Failed { .. } => Outcome::Failed,
1431        }
1432    }
1433
1434    /// Returns the optional explicit stop code.
1435    #[must_use]
1436    pub const fn stop_code(&self) -> Option<&StopCode> {
1437        match self {
1438            Self::Stopped { code } => code.as_ref(),
1439            Self::Completed | Self::Cancelled { .. } | Self::Failed { .. } => None,
1440        }
1441    }
1442
1443    /// Returns cancellation/failure detail when the outcome requires it.
1444    #[must_use]
1445    pub fn error(&self) -> Option<&(dyn Error + Send + Sync)> {
1446        match self {
1447            Self::Cancelled { error } | Self::Failed { error } => Some(error.as_ref()),
1448            Self::Completed | Self::Stopped { .. } => None,
1449        }
1450    }
1451}
1452
1453/// Closed progress reached by a `ToolCall` before its end observation.
1454///
1455/// The private representation makes a committed result without a value and completed
1456/// post-hooks without finalization unrepresentable.
1457///
1458/// ```compile_fail
1459/// use reef_core::runtime::{hook, tool};
1460/// let _ = hook::ToolCallProgress {
1461///     disposition: tool::CallDisposition::Executed,
1462/// };
1463/// ```
1464#[derive(Clone, Debug)]
1465pub struct ToolCallProgress {
1466    disposition: CallDisposition,
1467    state: ToolCallProgressState,
1468}
1469
1470#[derive(Clone, Debug)]
1471enum ToolCallProgressState {
1472    Observed,
1473    ResultAvailable(ToolResult),
1474    ResultCommitted(ToolResult),
1475    PostHooksCompleted(ToolResult),
1476}
1477
1478/// Public classification of the closed `ToolCall` progress.
1479#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1480#[non_exhaustive]
1481pub enum ToolCallProgressKind {
1482    /// The call ended before a closed result became available.
1483    Observed,
1484    /// A closed result exists but its enclosing batch is not yet durable.
1485    ResultAvailable,
1486    /// The enclosing result batch committed.
1487    ResultCommitted,
1488    /// Finalization and the post-execution hook phase both completed.
1489    PostHooksCompleted,
1490}
1491
1492impl ToolCallProgress {
1493    pub(crate) const fn observed(disposition: CallDisposition) -> Self {
1494        Self {
1495            disposition,
1496            state: ToolCallProgressState::Observed,
1497        }
1498    }
1499
1500    pub(crate) const fn result_available(disposition: CallDisposition, result: ToolResult) -> Self {
1501        Self {
1502            disposition,
1503            state: ToolCallProgressState::ResultAvailable(result),
1504        }
1505    }
1506
1507    pub(crate) const fn result_committed(disposition: CallDisposition, result: ToolResult) -> Self {
1508        Self {
1509            disposition,
1510            state: ToolCallProgressState::ResultCommitted(result),
1511        }
1512    }
1513
1514    pub(crate) const fn completed_post_hooks(
1515        disposition: CallDisposition,
1516        result: ToolResult,
1517    ) -> Self {
1518        Self {
1519            disposition,
1520            state: ToolCallProgressState::PostHooksCompleted(result),
1521        }
1522    }
1523
1524    /// Returns the furthest stable call disposition.
1525    #[must_use]
1526    pub const fn disposition(&self) -> CallDisposition {
1527        self.disposition
1528    }
1529
1530    /// Returns the closed progress classification.
1531    #[must_use]
1532    pub const fn kind(&self) -> ToolCallProgressKind {
1533        match self.state {
1534            ToolCallProgressState::Observed => ToolCallProgressKind::Observed,
1535            ToolCallProgressState::ResultAvailable(_) => ToolCallProgressKind::ResultAvailable,
1536            ToolCallProgressState::ResultCommitted(_) => ToolCallProgressKind::ResultCommitted,
1537            ToolCallProgressState::PostHooksCompleted(_) => {
1538                ToolCallProgressKind::PostHooksCompleted
1539            }
1540        }
1541    }
1542
1543    /// Returns the effective result once one became available.
1544    #[must_use]
1545    pub const fn result(&self) -> Option<&ToolResult> {
1546        match &self.state {
1547            ToolCallProgressState::Observed => None,
1548            ToolCallProgressState::ResultAvailable(result)
1549            | ToolCallProgressState::ResultCommitted(result)
1550            | ToolCallProgressState::PostHooksCompleted(result) => Some(result),
1551        }
1552    }
1553
1554    /// Reports whether the enclosing result batch is durable.
1555    #[must_use]
1556    pub const fn is_result_committed(&self) -> bool {
1557        matches!(
1558            self.state,
1559            ToolCallProgressState::ResultCommitted(_)
1560                | ToolCallProgressState::PostHooksCompleted(_)
1561        )
1562    }
1563
1564    /// Reports whether the post-execution hook phase completed after finalization.
1565    #[must_use]
1566    pub const fn post_hooks_completed(&self) -> bool {
1567        matches!(self.state, ToolCallProgressState::PostHooksCompleted(_))
1568    }
1569}
1570
1571/// Why a crate-internal `ToolCall` terminal fact was rejected.
1572#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1573pub(crate) enum ToolCallEndError {
1574    /// This disposition cannot reach the supplied result progress.
1575    InvalidDisposition {
1576        disposition: CallDisposition,
1577        progress: ToolCallProgressKind,
1578    },
1579    /// Normal completion requires the closed result and post-hook phase.
1580    CompletedBeforePostHooks(ToolCallProgressKind),
1581    /// A post-hook-complete call cannot carry a non-completed terminal state.
1582    PostHooksWithoutCompletion(Outcome),
1583}
1584
1585/// A validated, externally non-constructible `ToolCall` terminal observation.
1586///
1587/// ```compile_fail
1588/// use reef_core::runtime::hook;
1589/// let _ = hook::ToolCallEndObservation {};
1590/// ```
1591///
1592/// Crate-internal validation is deliberately not a public escape hatch:
1593///
1594/// ```compile_fail
1595/// use reef_core::runtime::hook;
1596/// let _ = hook::ToolCallEndObservation::try_new;
1597/// ```
1598#[derive(Clone, Debug)]
1599pub struct ToolCallEndObservation {
1600    coord: Coord,
1601    end: LifecycleEnd,
1602    original_call: ToolCall,
1603    effective_call: ToolCall,
1604    progress: ToolCallProgress,
1605}
1606
1607impl ToolCallEndObservation {
1608    pub(crate) fn try_new(
1609        coord: Coord,
1610        end: LifecycleEnd,
1611        original_call: ToolCall,
1612        effective_call: ToolCall,
1613        progress: ToolCallProgress,
1614    ) -> Result<Self, ToolCallEndError> {
1615        let progress_kind = progress.kind();
1616        let disposition = progress.disposition();
1617        let disposition_matches_progress = match progress_kind {
1618            ToolCallProgressKind::Observed => matches!(
1619                disposition,
1620                CallDisposition::Truncated | CallDisposition::NotExecuted
1621            ),
1622            ToolCallProgressKind::ResultAvailable
1623            | ToolCallProgressKind::ResultCommitted
1624            | ToolCallProgressKind::PostHooksCompleted => !matches!(
1625                disposition,
1626                CallDisposition::Truncated | CallDisposition::NotExecuted
1627            ),
1628        };
1629        if !disposition_matches_progress {
1630            return Err(ToolCallEndError::InvalidDisposition {
1631                disposition,
1632                progress: progress_kind,
1633            });
1634        }
1635
1636        match (&end, progress_kind) {
1637            (LifecycleEnd::Completed, ToolCallProgressKind::PostHooksCompleted) => {}
1638            (LifecycleEnd::Completed, incomplete) => {
1639                return Err(ToolCallEndError::CompletedBeforePostHooks(incomplete));
1640            }
1641            (
1642                LifecycleEnd::Stopped { .. }
1643                | LifecycleEnd::Cancelled { .. }
1644                | LifecycleEnd::Failed { .. },
1645                ToolCallProgressKind::PostHooksCompleted,
1646            ) => {
1647                return Err(ToolCallEndError::PostHooksWithoutCompletion(end.outcome()));
1648            }
1649            (
1650                LifecycleEnd::Stopped { .. }
1651                | LifecycleEnd::Cancelled { .. }
1652                | LifecycleEnd::Failed { .. },
1653                ToolCallProgressKind::Observed
1654                | ToolCallProgressKind::ResultAvailable
1655                | ToolCallProgressKind::ResultCommitted,
1656            ) => {}
1657        }
1658
1659        Ok(Self {
1660            coord,
1661            end,
1662            original_call,
1663            effective_call,
1664            progress,
1665        })
1666    }
1667
1668    /// Returns the exact ended `ToolCall` coordinate.
1669    #[must_use]
1670    pub const fn coord(&self) -> &Coord {
1671        &self.coord
1672    }
1673
1674    /// Returns the authoritative terminal state.
1675    #[must_use]
1676    pub const fn end(&self) -> &LifecycleEnd {
1677        &self.end
1678    }
1679
1680    /// Returns the original model-emitted call.
1681    #[must_use]
1682    pub const fn original_call(&self) -> &ToolCall {
1683        &self.original_call
1684    }
1685
1686    /// Returns the final effective call after successful rewrites.
1687    #[must_use]
1688    pub const fn effective_call(&self) -> &ToolCall {
1689        &self.effective_call
1690    }
1691
1692    /// Returns the closed result/finalization progress.
1693    #[must_use]
1694    pub const fn progress(&self) -> &ToolCallProgress {
1695        &self.progress
1696    }
1697}
1698
1699/// Complete immutable facts for exactly one lifecycle callback.
1700///
1701/// Every field is an owned value rather than a view, so an observer cannot see a
1702/// fact mutate under it and the producer needs no defensive copy.
1703#[derive(Clone, Debug)]
1704#[non_exhaustive]
1705pub enum LifecycleObservation {
1706    /// Prepared Run input at execution start.
1707    #[non_exhaustive]
1708    RunStart {
1709        /// Started Run coordinate.
1710        coord: Coord,
1711        /// Prepared input after all rewrites.
1712        input: Vec<Part>,
1713    },
1714    /// Authoritative Run terminal fact and entered Turn count.
1715    #[non_exhaustive]
1716    RunEnd {
1717        /// Ended Run coordinate.
1718        coord: Coord,
1719        /// Authoritative terminal state.
1720        end: LifecycleEnd,
1721        /// Number of Turns entered.
1722        turns: usize,
1723    },
1724    /// Input which opened a Turn.
1725    #[non_exhaustive]
1726    TurnStart {
1727        /// Started Turn coordinate.
1728        coord: Coord,
1729        /// Owned trigger batch.
1730        trigger: Vec<Item>,
1731    },
1732    /// Authoritative Turn terminal fact and entered Step count.
1733    #[non_exhaustive]
1734    TurnEnd {
1735        /// Ended Turn coordinate.
1736        coord: Coord,
1737        /// Authoritative terminal state.
1738        end: LifecycleEnd,
1739        /// Number of Steps entered.
1740        steps: usize,
1741    },
1742    /// Frozen snapshot used by a started Step.
1743    #[non_exhaustive]
1744    StepStart {
1745        /// Started Step coordinate.
1746        coord: Coord,
1747        /// Exact shared Step snapshot.
1748        snapshot: Arc<StepSnapshot>,
1749    },
1750    /// Authoritative Step terminal fact and the same frozen snapshot.
1751    #[non_exhaustive]
1752    StepEnd {
1753        /// Ended Step coordinate.
1754        coord: Coord,
1755        /// Authoritative terminal state.
1756        end: LifecycleEnd,
1757        /// Exact shared Step snapshot.
1758        snapshot: Arc<StepSnapshot>,
1759    },
1760    /// Exact frozen provider request.
1761    ///
1762    /// This observation has no [`event::Kind`] counterpart, and that is a
1763    /// decision rather than an omission: its payload is the whole frozen
1764    /// [`Request`], so publishing it outward would copy the projected history and
1765    /// the system instruction onto a stream a host may log, to tell a consumer
1766    /// something [`event::Kind::StepStart`] already tells it. See ADR-021.
1767    ///
1768    /// [`event::Kind`]: crate::runtime::event::Kind
1769    /// [`event::Kind::StepStart`]: crate::runtime::event::Kind::StepStart
1770    #[non_exhaustive]
1771    GenerationStart {
1772        /// Started Generation coordinate.
1773        coord: Coord,
1774        /// Exact request passed to the provider.
1775        request: Request,
1776    },
1777    /// Authoritative generation outcome plus provider completion facts.
1778    #[non_exhaustive]
1779    GenerationEnd {
1780        /// Ended Generation coordinate.
1781        coord: Coord,
1782        /// Authoritative terminal state.
1783        end: LifecycleEnd,
1784        /// Verbatim provider finish label.
1785        finish_reason: String,
1786        /// Normalized provider-neutral completion reason.
1787        completion: CompletionReason,
1788    },
1789    /// Original model-emitted `ToolCall`.
1790    #[non_exhaustive]
1791    ToolCallStart {
1792        /// Started `ToolCall` coordinate.
1793        coord: Coord,
1794        /// Original frozen call.
1795        call: ToolCall,
1796    },
1797    /// Authoritative closed `ToolCall` outcome, rewrites, result, and progress.
1798    ToolCallEnd(ToolCallEndObservation),
1799}
1800
1801impl LifecycleObservation {
1802    /// Returns the callback variant without inspecting its payload.
1803    #[must_use]
1804    pub const fn kind(&self) -> LifecycleKind {
1805        match self {
1806            Self::RunStart { .. } => LifecycleKind::RunStart,
1807            Self::RunEnd { .. } => LifecycleKind::RunEnd,
1808            Self::TurnStart { .. } => LifecycleKind::TurnStart,
1809            Self::TurnEnd { .. } => LifecycleKind::TurnEnd,
1810            Self::StepStart { .. } => LifecycleKind::StepStart,
1811            Self::StepEnd { .. } => LifecycleKind::StepEnd,
1812            Self::GenerationStart { .. } => LifecycleKind::GenerationStart,
1813            Self::GenerationEnd { .. } => LifecycleKind::GenerationEnd,
1814            Self::ToolCallStart { .. } => LifecycleKind::ToolCallStart,
1815            Self::ToolCallEnd(_) => LifecycleKind::ToolCallEnd,
1816        }
1817    }
1818
1819    /// Returns the exact coordinate carried by the producer.
1820    #[must_use]
1821    pub const fn coord(&self) -> &Coord {
1822        match self {
1823            Self::RunStart { coord, .. }
1824            | Self::RunEnd { coord, .. }
1825            | Self::TurnStart { coord, .. }
1826            | Self::TurnEnd { coord, .. }
1827            | Self::StepStart { coord, .. }
1828            | Self::StepEnd { coord, .. }
1829            | Self::GenerationStart { coord, .. }
1830            | Self::GenerationEnd { coord, .. }
1831            | Self::ToolCallStart { coord, .. } => coord,
1832            Self::ToolCallEnd(observation) => observation.coord(),
1833        }
1834    }
1835}
1836
1837/// Immutable transcript mutation fact passed before the live commit.
1838#[derive(Clone, Debug)]
1839#[non_exhaustive]
1840pub enum TranscriptMutation {
1841    /// One ordered append batch and its proposed committed version.
1842    #[non_exhaustive]
1843    Append {
1844        /// Version observed before the mutation.
1845        previous: Version,
1846        /// Version proposed after the mutation.
1847        version: Version,
1848        /// Complete owned append batch.
1849        items: Vec<Item>,
1850    },
1851    /// One complete replacement and its proposed committed version.
1852    #[non_exhaustive]
1853    Replace {
1854        /// Version observed before the mutation.
1855        previous: Version,
1856        /// Version proposed after the mutation.
1857        version: Version,
1858        /// Complete owned replacement snapshot.
1859        items: Vec<Item>,
1860    },
1861}
1862
1863impl TranscriptMutation {
1864    /// Returns the version observed before reservation.
1865    #[must_use]
1866    pub const fn previous_version(&self) -> Version {
1867        match self {
1868            Self::Append { previous, .. } | Self::Replace { previous, .. } => *previous,
1869        }
1870    }
1871
1872    /// Returns the proposed post-commit version.
1873    #[must_use]
1874    pub const fn version(&self) -> Version {
1875        match self {
1876            Self::Append { version, .. } | Self::Replace { version, .. } => *version,
1877        }
1878    }
1879
1880    /// Returns the immutable owned payload.
1881    #[must_use]
1882    pub fn items(&self) -> &[Item] {
1883        match self {
1884            Self::Append { items, .. } | Self::Replace { items, .. } => items,
1885        }
1886    }
1887}
1888
1889/// A successful pre-commit reservation whose publication cannot fail.
1890///
1891/// A reservation is resolved exactly once, and both resolutions consume the box
1892/// so no code path can publish an aborted reservation or abort a published one.
1893/// The controller decides which resolution applies: any pre-commit failure
1894/// aborts every held reservation in reverse acquisition order, and a successful
1895/// commit publishes every held reservation in acquisition order and never
1896/// aborts. Publication is contractually infallible, which is what makes a held
1897/// reservation safe to publish after the commit has already succeeded.
1898pub trait TranscriptReservation: Send {
1899    /// Publishes the already-committed fact; consuming `self` forbids abort after publish.
1900    ///
1901    /// The live transcript mutation has already linearized when this runs, so an
1902    /// implementation must not fail. A panic is isolated by the controller, which
1903    /// still publishes every remaining reservation.
1904    fn publish(self: Box<Self>);
1905
1906    /// Releases a reservation that will never be committed.
1907    ///
1908    /// The controller calls this only before the live commit, so an
1909    /// implementation must not assume the mutation became visible. Releasing
1910    /// nothing is the default, because a reservation that holds no external
1911    /// resource has nothing to undo.
1912    fn abort(self: Box<Self>) {}
1913}
1914
1915/// Run-phase hooks.
1916///
1917/// The three boundaries of a Run itself: what it starts with, whether it takes
1918/// another Step, and what it does when it would otherwise finish.
1919/// [`compose_continuation`](RunHooks::compose_continuation) is how an agent keeps
1920/// going — returning more input continues the Run, returning nothing ends it —
1921/// so a Run that should do more than one turn needs this family.
1922///
1923/// ```
1924/// use std::sync::Arc;
1925///
1926/// use reef_core::runtime::{event, hook};
1927///
1928/// /// Stops the Run after a fixed number of Steps.
1929/// struct StepBudget {
1930///     remaining: std::sync::atomic::AtomicUsize,
1931/// }
1932///
1933/// impl hook::RunHooks for StepBudget {
1934///     fn prepare(&self, _scope: &hook::PrepareScope<'_>) -> hook::HookResult<hook::PrepareDecision> {
1935///         // `Continue` keeps what the caller submitted. `Modify` replaces it,
1936///         // and may not replace it with nothing.
1937///         Ok(hook::PrepareDecision::Continue)
1938///     }
1939///
1940///     fn compose_continuation(&self, _scope: &hook::ContinuationScope<'_>) -> hook::HookResult<hook::ContinuationDecision> {
1941///         Ok(hook::ContinuationDecision::Keep)
1942///     }
1943///
1944///     fn decide_stop(&self, _scope: &hook::StopDecisionScope<'_>) -> hook::HookResult<hook::StopDecision> {
1945///         use std::sync::atomic::Ordering;
1946///         Ok(if self.remaining.fetch_sub(1, Ordering::SeqCst) > 0 {
1947///             hook::StopDecision::Continue
1948///         } else {
1949///             // The one hook-initiated stop, and it names itself.
1950///             hook::StopDecision::Stop(event::StopCode::new("step-budget".to_owned()).unwrap())
1951///         })
1952///     }
1953/// }
1954///
1955/// let mut hooks = hook::RegistryBuilder::new();
1956/// hooks.register(hook::Registration::new("step-budget".to_owned()).run(Arc::new(StepBudget {
1957///     remaining: std::sync::atomic::AtomicUsize::new(4),
1958/// })));
1959/// ```
1960pub trait RunHooks: Send + Sync {
1961    /// Composes initial input before admission.
1962    ///
1963    /// # Errors
1964    ///
1965    /// Return one when this registration cannot decide what the Run's initial
1966    /// input should be — a required piece of context it could not load, or an
1967    /// input it judges inadmissible. This is the one hook whose failure is
1968    /// reported to the caller synchronously rather than through a Run:
1969    /// [`Agent::start`](crate::runtime::agent::Agent::start) returns
1970    /// [`StartError::Prepare`](crate::runtime::agent::StartError::Prepare) and no
1971    /// Run comes into existence, so it is also the only place a hook can refuse
1972    /// a Run outright instead of ending one.
1973    ///
1974    /// Reef adds one error of its own here: returning
1975    /// [`PrepareDecision::Modify`] with an empty replacement is refused as
1976    /// [`PrepareError::EmptyModify`], attributed to this registration. Composing
1977    /// nothing is [`PrepareDecision::Continue`]; deleting what the caller
1978    /// submitted is not an option, because the admitted input is also the
1979    /// transcript's record of it.
1980    ///
1981    /// See [`HookError`](HookError#effect-on-the-run) for what a failure costs.
1982    fn prepare(&self, scope: &PrepareScope<'_>) -> HookResult<PrepareDecision>;
1983
1984    /// Composes a natural-completion continuation.
1985    ///
1986    /// # Errors
1987    ///
1988    /// Return one when this registration cannot decide whether the Run should
1989    /// continue. Note that it does not need to fail in order to *stop* the Run:
1990    /// [`ContinuationDecision::Replace`] with an empty continuation ends it normally,
1991    /// which is a governance answer rather than a failure. An error here ends the
1992    /// Run as failed instead, discarding the continuation every earlier
1993    /// registration had composed.
1994    ///
1995    /// See [`HookError`](HookError#effect-on-the-run).
1996    fn compose_continuation(
1997        &self,
1998        scope: &ContinuationScope<'_>,
1999    ) -> HookResult<ContinuationDecision>;
2000
2001    /// Decides whether the prospective Step may exist.
2002    ///
2003    /// # Errors
2004    ///
2005    /// Return one when this registration cannot decide, rather than when it
2006    /// decides against another Step: refusing a Step is
2007    /// [`StopDecision::Stop`], which ends the Run normally carrying a stop
2008    /// code a consumer can read. An error ends it as failed and publishes no stop
2009    /// at all.
2010    ///
2011    /// See [`HookError`](HookError#effect-on-the-run).
2012    fn decide_stop(&self, scope: &StopDecisionScope<'_>) -> HookResult<StopDecision>;
2013}
2014
2015/// Injected-input admission hook.
2016///
2017/// Mid-run input arrives through
2018/// [`Session::input_mailbox`](crate::runtime::session::Session::input_mailbox)
2019/// and is claimed at the boundary it targeted. This is the one chance to rewrite
2020/// or refuse a claimed batch before it becomes a transcript record.
2021///
2022/// ```
2023/// use std::sync::Arc;
2024///
2025/// use reef_core::runtime::hook;
2026///
2027/// /// Refuses injected input once the conversation is long enough.
2028/// struct Doorman;
2029///
2030/// impl hook::InputHooks for Doorman {
2031///     fn before_input_admit(&self, scope: &hook::InputAdmitScope<'_>) -> hook::InputAdmitDecision {
2032///         if scope.items().is_empty() {
2033///             // A rejection must say why; an empty reason is refused.
2034///             hook::InputAdmitDecision::Reject("nothing to admit".to_owned())
2035///         } else {
2036///             hook::InputAdmitDecision::Admit
2037///         }
2038///     }
2039/// }
2040///
2041/// let registration = hook::Registration::new("doorman".to_owned()).input(Arc::new(Doorman));
2042/// # let _ = registration;
2043/// ```
2044pub trait InputHooks: Send + Sync {
2045    /// Rewrites, admits, or permanently rejects one claimed batch.
2046    fn before_input_admit(&self, scope: &InputAdmitScope<'_>) -> InputAdmitDecision;
2047}
2048
2049/// Turn and Step boundary hooks.
2050///
2051/// Four boundaries inside a Run. [`before_step`](TurnStepHooks::before_step) is
2052/// the only place with a writable [`crate::runtime::model::RequestPlan`],
2053/// so it is where per-request material goes — a compaction policy rewrites
2054/// history here, and a status line goes into the plan's ephemeral lane, which
2055/// reaches the model without ever becoming a record.
2056///
2057/// ```
2058/// use std::sync::Arc;
2059///
2060/// use reef_core::runtime::hook;
2061/// use reef_core::transcript::item;
2062/// use reef_core::value::content;
2063///
2064/// /// Adds one volatile line to every request, and nothing to the transcript.
2065/// struct StatusLine;
2066///
2067/// impl hook::TurnStepHooks for StatusLine {
2068///     fn before_turn(&self, _scope: &hook::TurnScope<'_>) -> hook::HookResult<Vec<item::Item>> {
2069///         Ok(Vec::new())
2070///     }
2071///
2072///     fn after_turn(&self, _scope: &hook::TurnScope<'_>) -> hook::HookResult<Vec<item::Item>> {
2073///         Ok(Vec::new())
2074///     }
2075///
2076///     fn before_step(&self, scope: &mut hook::BeforeStepScope<'_>) -> hook::HookResult<Vec<item::Item>> {
2077///         scope
2078///             .plan()
2079///             .push_ephemeral(content::Part::text("[battery: 42%]".to_owned()));
2080///         Ok(Vec::new())
2081///     }
2082///
2083///     fn after_step(&self, _scope: &hook::AfterStepScope<'_>) -> hook::HookResult<hook::AfterStepDecision> {
2084///         Ok(hook::AfterStepDecision::Continue(Vec::new()))
2085///     }
2086/// }
2087///
2088/// let registration = hook::Registration::new("status".to_owned()).turn_step(Arc::new(StatusLine));
2089/// # let _ = registration;
2090/// ```
2091pub trait TurnStepHooks: Send + Sync {
2092    /// Runs before the Turn lifecycle starts.
2093    ///
2094    /// # Errors
2095    ///
2096    /// Return one when this registration cannot produce the items the Turn should
2097    /// open with. The Turn is never opened: the items every earlier registration
2098    /// contributed are discarded together with this one's, so the transcript
2099    /// records no half-composed Turn opening.
2100    ///
2101    /// See [`HookError`](HookError#effect-on-the-run).
2102    fn before_turn(&self, scope: &TurnScope<'_>) -> HookResult<Vec<Item>>;
2103
2104    /// Runs after ordinary Turn work and before its end observer.
2105    ///
2106    /// # Errors
2107    ///
2108    /// Return one when this registration cannot produce the items that should
2109    /// close the Turn. Nothing this boundary composed is appended. The Turn's work
2110    /// is already committed by this point, so the Run fails with a complete Turn
2111    /// behind it and no closing items — not with a partially closed Turn.
2112    ///
2113    /// See [`HookError`](HookError#effect-on-the-run).
2114    fn after_turn(&self, scope: &TurnScope<'_>) -> HookResult<Vec<Item>>;
2115
2116    /// Runs in registration order over the sole writable `RequestPlan`.
2117    ///
2118    /// # Errors
2119    ///
2120    /// Return one when this registration cannot prepare the Step — most often
2121    /// because the request material it needed to add is unavailable. The Step
2122    /// never freezes, so no model call is made, and the plan edits earlier
2123    /// registrations had already applied are dropped along with this one's. That
2124    /// is the reason a partial plan is not worth rescuing: the registrations after
2125    /// this one never saw it.
2126    ///
2127    /// See [`HookError`](HookError#effect-on-the-run).
2128    fn before_step(&self, scope: &mut BeforeStepScope<'_>) -> HookResult<Vec<Item>>;
2129
2130    /// Runs after ordinary Step work and may close its Turn.
2131    ///
2132    /// # Errors
2133    ///
2134    /// Return one when this registration cannot decide how the Step should close.
2135    /// Closing the Turn is not a failure — that is
2136    /// [`AfterStepDecision::EndTurn`] — so an error here means the decision itself
2137    /// could not be made. Neither the items nor the end-of-Turn decisions
2138    /// collected at this boundary are applied.
2139    ///
2140    /// See [`HookError`](HookError#effect-on-the-run).
2141    fn after_step(&self, scope: &AfterStepScope<'_>) -> HookResult<AfterStepDecision>;
2142}
2143
2144/// Model boundary hooks.
2145///
2146/// The two sides of one generation: the request before it is sent, and the
2147/// assistant record before it is committed. This is where a composition layer
2148/// normalises history for the provider it is about to call — core never rewrites
2149/// a segment because a different provider produced it.
2150///
2151/// ```
2152/// use std::sync::Arc;
2153///
2154/// use reef_core::runtime::hook;
2155///
2156/// /// Refuses to call the model at all after a cutoff.
2157/// struct Circuit {
2158///     open: std::sync::atomic::AtomicBool,
2159/// }
2160///
2161/// impl hook::ModelHooks for Circuit {
2162///     fn before_model(&self, _scope: &hook::BeforeModelScope<'_>) -> hook::HookResult<hook::BeforeModelDecision> {
2163///         use std::sync::atomic::Ordering;
2164///         Ok(if self.open.load(Ordering::SeqCst) {
2165///             // Declining to call the model is a decision, not a failure.
2166///             hook::BeforeModelDecision::Abort("circuit open".to_owned())
2167///         } else {
2168///             hook::BeforeModelDecision::Continue
2169///         })
2170///     }
2171///
2172///     fn after_model(&self, _scope: &hook::AfterModelScope<'_>) -> hook::AfterModelDecision {
2173///         hook::AfterModelDecision::Continue
2174///     }
2175/// }
2176///
2177/// let registration = hook::Registration::new("circuit".to_owned()).model(Arc::new(Circuit {
2178///     open: std::sync::atomic::AtomicBool::new(false),
2179/// }));
2180/// # let _ = registration;
2181/// ```
2182pub trait ModelHooks: Send + Sync {
2183    /// Controls one immutable model request.
2184    ///
2185    /// # Errors
2186    ///
2187    /// Return one when this registration cannot produce the request it wanted to
2188    /// send. Declining to call the model is not a failure — that is
2189    /// [`BeforeModelDecision::ShortCircuit`], which supplies the output itself, or
2190    /// [`BeforeModelDecision::Abort`], which states a reason — and neither is
2191    /// rewriting the request, which is [`BeforeModelDecision::Modify`]. An error is
2192    /// for the case where the rewrite itself could not be built, most commonly
2193    /// because
2194    /// re-freezing the modified history through
2195    /// [`RequestPlan::try_into_request`](crate::runtime::model::RequestPlan::try_into_request)
2196    /// returned a [`RequestError`](crate::runtime::model::RequestError) this
2197    /// registration cannot resolve.
2198    ///
2199    /// No model call is made and no generation is recorded; rewrites from earlier
2200    /// registrations are discarded with this one's.
2201    ///
2202    /// See [`HookError`](HookError#effect-on-the-run).
2203    fn before_model(&self, scope: &BeforeModelScope<'_>) -> HookResult<BeforeModelDecision>;
2204
2205    /// Rewrites successfully assembled output before commit.
2206    fn after_model(&self, scope: &AfterModelScope<'_>) -> AfterModelDecision;
2207}
2208
2209/// Tool boundary hooks, distinct from Gate admission authority.
2210///
2211/// This is the policy plane over tool calls, and it runs *before* the separate
2212/// [`Gate`](crate::runtime::tool::Gate) sees anything, so a gate only ever
2213/// judges the final effective call.
2214///
2215/// ```
2216/// use std::sync::Arc;
2217///
2218/// use reef_core::runtime::hook;
2219/// use reef_core::transcript::item;
2220///
2221/// /// Blocks one tool by name, without touching the rest.
2222/// struct Policy;
2223///
2224/// impl hook::ToolHooks for Policy {
2225///     fn before_tool_call(&self, scope: &hook::ToolCallScope<'_>) -> hook::HookResult<hook::ToolCallDecision> {
2226///         Ok(if scope.call().name().as_str() == "shell.exec" {
2227///             // A block is an ordinary business result the model reads, not a
2228///             // failure: an `Err` here would fail the whole batch.
2229///             hook::ToolCallDecision::Block("shell is disabled".to_owned())
2230///         } else {
2231///             hook::ToolCallDecision::Continue
2232///         })
2233///     }
2234///
2235///     fn before_tool_result(&self, _scope: &hook::ToolResultScope<'_>) -> hook::HookResult<hook::ToolResultDecision> {
2236///         Ok(hook::ToolResultDecision::Continue)
2237///     }
2238///
2239///     fn after_tool_commit(&self, _scope: &hook::AfterToolCommitScope<'_>) -> Vec<item::Item> {
2240///         Vec::new()
2241///     }
2242/// }
2243///
2244/// let registration = hook::Registration::new("policy".to_owned()).tool(Arc::new(Policy));
2245/// # let _ = registration;
2246/// ```
2247///
2248/// # Cooperative synchronous callback contract
2249///
2250/// These callbacks are trusted, synchronous, and cooperative. An implementation
2251/// must not block forever, wait for work that requires the same runtime thread to
2252/// advance, or catch a runtime-internal abort unwind and then continue external
2253/// side effects. Reef retains and joins every callback owner on normal, error, and
2254/// strong-delivery abort paths, but does not claim to forcibly terminate a
2255/// malicious or permanently blocked synchronous callback.
2256///
2257/// ## How a broken one looks from outside, and who to blame
2258///
2259/// Breaking that contract produces neither an error nor a panic, so it is worth
2260/// knowing the shape it does produce. A [`Self::after_tool_commit`] that never
2261/// returns leaves a thread blocked inside a destructor during teardown: the run
2262/// joins the callback it promised to join, waits for a completion that is not
2263/// coming, and never releases. The Run does not fail — it stops finishing.
2264///
2265/// Nothing in the process reports which registration is responsible, because a
2266/// diagnostic emitted from a destructor would have to be a panic during unwinding
2267/// or a library writing to stderr, and this crate does neither. What is available
2268/// instead is a backtrace: `after_tool_commit` is the only callback that runs on
2269/// Tokio's blocking pool, and the registrations are invoked one after another
2270/// rather than concurrently, so at most one is in flight and the blocking thread's
2271/// own stack names the implementing type. A *panic* at this boundary is attributed
2272/// by registration name and needs no backtrace; a hang is the case that does.
2273pub trait ToolHooks: Send + Sync {
2274    /// Rewrites, blocks, or short-circuits before the separate gate plane.
2275    ///
2276    /// # Errors
2277    ///
2278    /// Return one when this registration cannot decide about the call. Refusing a
2279    /// call is not a failure: [`ToolCallDecision::Block`] stops it with a reason and
2280    /// [`ToolCallDecision::ShortCircuit`] answers it directly, and both produce an
2281    /// ordinary business result that enters the batch like any other. An error
2282    /// instead fails the **whole batch**, not just this call, because the batch
2283    /// commits atomically and a batch missing one call's decision cannot be
2284    /// committed at all.
2285    ///
2286    /// A registration that cannot fail returns `Ok` unconditionally.
2287    ///
2288    /// See [`HookError`](HookError#effect-on-the-run).
2289    fn before_tool_call(&self, scope: &ToolCallScope<'_>) -> HookResult<ToolCallDecision>;
2290
2291    /// Rewrites every closed result before commit.
2292    ///
2293    /// # Errors
2294    ///
2295    /// Return one when this registration cannot produce the result it intended to
2296    /// commit. Rewriting a result, including into a business error, is
2297    /// [`ToolResultDecision::Modify`] rather than a failure. An error fails the batch
2298    /// commit, so the assistant record and every result in the batch stay
2299    /// uncommitted — which is what keeps a rejected rewrite from leaving a call
2300    /// nobody answered in the transcript.
2301    ///
2302    /// See [`HookError`](HookError#effect-on-the-run).
2303    fn before_tool_result(&self, scope: &ToolResultScope<'_>) -> HookResult<ToolResultDecision>;
2304
2305    /// Appends after an executed batch is durable; this late hook cannot fail it.
2306    ///
2307    /// Each emitted fact is a synchronous strong-acceptance rendezvous. Rejection,
2308    /// consumer abandonment, invalid facts, or channel closure aborts the callback.
2309    /// The callback must not swallow that internal abort and continue side effects;
2310    /// Reef nevertheless revokes this invocation's Session-state writer before
2311    /// releasing the abort rendezvous, so subsequent state writes fail closed.
2312    fn after_tool_commit(&self, scope: &AfterToolCommitScope<'_>) -> Vec<Item>;
2313}
2314
2315/// Passive hooks isolated at the exact callback invocation boundary.
2316///
2317/// An observer watches and decides nothing, which is what makes it the family a
2318/// budget, a metric or a log belongs in — and
2319/// [`model_event`](ObserverHooks::model_event) is the only route token usage has
2320/// out of the runtime at all.
2321///
2322/// ```
2323/// use std::sync::Arc;
2324/// use std::sync::atomic::{AtomicU64, Ordering};
2325///
2326/// use reef_core::runtime::{model, hook};
2327///
2328/// /// Counts tokens, and observes nothing else.
2329/// #[derive(Default)]
2330/// struct Budget {
2331///     spent: AtomicU64,
2332/// }
2333///
2334/// impl hook::ObserverHooks for Budget {
2335///     fn model_event(&self, _scope: &hook::ObserverScope<'_>, event: &model::Event) {
2336///         // Usage is incremental, so adding it up is exact.
2337///         if let model::Event::Usage(usage) = event {
2338///             self.spent.fetch_add(usage.total, Ordering::SeqCst);
2339///         }
2340///     }
2341/// }
2342///
2343/// let registration = hook::Registration::new("budget".to_owned())
2344///     .observer(Arc::new(Budget::default()));
2345/// # let _ = registration;
2346/// ```
2347///
2348/// # Every method has a default, and this is the only hook family where one does
2349///
2350/// An observation returns nothing and decides nothing: reef does exactly the
2351/// same thing whether a registration watched a boundary or not. Not overriding a
2352/// method here therefore *means* "I do not watch that", which is the honest
2353/// reading of an empty body, and the cost of forgetting one falls entirely on
2354/// the registration that forgot — it sees less than it meant to, in its own
2355/// output, and no other registration and no Run behaves differently.
2356///
2357/// Every other hook family stays fully required, deliberately. Those return a
2358/// decision reef then applies, so a default would have to *pick a policy* —
2359/// allow the call, keep the request, continue the Run — and a registration that
2360/// meant to gate a tool call but misspelled the method would compile into one
2361/// that permits every call. That is the failure this crate designs against
2362/// everywhere else, which is why its enums are exhaustive, why authorisation is
2363/// a compile-time ladder, and why no decision type implements `Default`. A
2364/// silently defaulted decision is that `Default` reached by another route.
2365///
2366/// This is not a deadline that has passed: adding a default body to a required
2367/// method compiles for every existing implementor, so any hook here can gain one
2368/// later on evidence rather than on speculation.
2369pub trait ObserverHooks: Send + Sync {
2370    /// Observes synchronous Run admission without emission.
2371    ///
2372    /// The default observes nothing.
2373    fn run_admitted(&self, scope: &ReadScope<'_>) {
2374        let _ = scope;
2375    }
2376
2377    /// Observes one closed lifecycle fact.
2378    ///
2379    /// The default observes nothing.
2380    fn lifecycle(&self, observation: &LifecycleObservation, scope: &ObserverScope<'_>) {
2381        let _ = (observation, scope);
2382    }
2383
2384    /// Observes provider usage/done facts.
2385    ///
2386    /// This is the only route [`model::Event::Usage`] has to a hook, so a
2387    /// budget or accounting policy overrides this one and leaves the rest.
2388    ///
2389    /// The default observes nothing.
2390    fn model_event(&self, scope: &ObserverScope<'_>, event: &model::Event) {
2391        let _ = (scope, event);
2392    }
2393
2394    /// Observes an audit fact inside the serialized outward boundary.
2395    ///
2396    /// The default observes nothing.
2397    fn audit_event(&self, scope: &ReadScope<'_>, event: &audit::Event) {
2398        let _ = (scope, event);
2399    }
2400}
2401
2402/// Transcript reservation hook.
2403///
2404/// The seam a durable journal is built on. Every transcript mutation is offered
2405/// here *before* it linearizes: a registration that can promise to publish
2406/// returns a [`TranscriptReservation`], and one that cannot returns an error,
2407/// which aborts the mutation with nothing written. Publication afterwards cannot
2408/// fail, so a hook that must not lose a record does its risky work — the
2409/// write-ahead, the lock, the capacity check — inside `reserve`.
2410///
2411/// [`TranscriptMutation::items`] exposes the complete owned transcript values,
2412/// including segment signatures, raw payloads and provider data. This is the
2413/// persistence rail for a byte-faithful resumable Session; the outward event stream
2414/// is an earlier, lossy observation projection and is not a substitute. With the
2415/// `serde` feature, serializing these values also serializes credential-tier
2416/// provider tokens, so the composition layer must protect its destination as the
2417/// [crate-level `Serialization` section](crate#serialization) describes.
2418///
2419/// ```
2420/// use std::sync::Arc;
2421///
2422/// use reef_core::runtime::hook;
2423///
2424/// /// Writes ahead, then publishes what it wrote.
2425/// struct Journal;
2426///
2427/// struct Reserved {
2428///     version: u64,
2429/// }
2430///
2431/// impl hook::TranscriptReservation for Reserved {
2432///     fn publish(self: Box<Self>) {
2433///         // The mutation has linearized. This cannot fail and must not.
2434///         let _durable = self.version;
2435///     }
2436///
2437///     fn abort(self: Box<Self>) {
2438///         // The mutation never happened; release what `reserve` took.
2439///     }
2440/// }
2441///
2442/// impl hook::TranscriptHooks for Journal {
2443///     fn reserve(
2444///         &self,
2445///         _scope: &hook::ReadScope<'_>,
2446///         mutation: &hook::TranscriptMutation,
2447///     ) -> hook::HookResult<Box<dyn hook::TranscriptReservation>> {
2448///         Ok(Box::new(Reserved { version: mutation.version().as_u64() }))
2449///     }
2450/// }
2451///
2452/// let registration = hook::Registration::new("journal".to_owned()).transcript(Arc::new(Journal));
2453/// # let _ = registration;
2454/// ```
2455pub trait TranscriptHooks: Send + Sync {
2456    /// Reserves one immutable mutation before live commit.
2457    ///
2458    /// # Errors
2459    ///
2460    /// Return one when this registration cannot promise to publish the mutation.
2461    /// That is the whole question this hook asks: everything that can go wrong must
2462    /// go wrong *here*, because [`TranscriptReservation::publish`] runs after the
2463    /// commit has linearized and is contractually infallible. A registration that
2464    /// needs to write ahead, take a lock, or reserve capacity does it now and
2465    /// returns an error if it cannot.
2466    ///
2467    /// A failure aborts every reservation this transaction already held, in reverse
2468    /// acquisition order, and the compare-and-set never runs — so the transcript is
2469    /// unchanged and no peer is left holding a reservation for a mutation that never
2470    /// happened. Registrations after this one are not called.
2471    ///
2472    /// Because a reservation failure fails the mutation rather than a callback
2473    /// phase, the Run's [`FailureKind`](crate::runtime::run::FailureKind) is
2474    /// [`Transcript`](crate::runtime::run::FailureKind::Transcript) or
2475    /// [`ToolCommit`](crate::runtime::run::FailureKind::ToolCommit) rather than
2476    /// [`Hook`](crate::runtime::run::FailureKind::Hook), even though this
2477    /// registration's name is still attached to the cause. At Run admission it is
2478    /// [`StartError::Prepare`](crate::runtime::agent::StartError::Prepare) instead.
2479    ///
2480    /// See [`HookError`](HookError#effect-on-the-run).
2481    fn reserve(
2482        &self,
2483        scope: &ReadScope<'_>,
2484        mutation: &TranscriptMutation,
2485    ) -> HookResult<Box<dyn TranscriptReservation>>;
2486}
2487
2488/// Agent teardown is deliberately separate from all 27 runtime callbacks.
2489///
2490/// It is the only hook that runs outside a Run, and the only one whose failure
2491/// costs nothing else: [`Agent::close`](crate::runtime::agent::Agent::close)
2492/// invokes every registration's `close` in registration order regardless of what
2493/// the others did, and reports the failures together.
2494///
2495/// ```
2496/// use std::sync::Arc;
2497/// use std::sync::atomic::{AtomicBool, Ordering};
2498///
2499/// use reef_core::runtime::hook;
2500///
2501/// /// Releases something the hook opened, exactly once.
2502/// #[derive(Default)]
2503/// struct Connection {
2504///     closed: AtomicBool,
2505/// }
2506///
2507/// impl hook::AgentTeardown for Connection {
2508///     fn close(&self) -> hook::HookResult<()> {
2509///         self.closed.store(true, Ordering::SeqCst);
2510///         Ok(())
2511///     }
2512/// }
2513///
2514/// let registration = hook::Registration::new("connection".to_owned())
2515///     .teardown(Arc::new(Connection::default()));
2516/// # let _ = registration;
2517/// ```
2518pub trait AgentTeardown: Send + Sync {
2519    /// Releases hook-owned external resources.
2520    ///
2521    /// # Errors
2522    ///
2523    /// Return one when a resource could not be released cleanly — a connection
2524    /// that would not drain, a flush that failed. This is the one fallible hook
2525    /// whose failure does **not** short-circuit anything: teardown is the last
2526    /// thing that happens, so every registration's `close` runs in registration
2527    /// order regardless, and the failures are collected rather than raced. A peer
2528    /// that would have released a file handle still gets to.
2529    ///
2530    /// [`Agent::close`](crate::runtime::agent::Agent::close) reports them together
2531    /// as [`CloseError::Hooks`](crate::runtime::agent::CloseError::Hooks), whose
2532    /// [`TeardownError::entries`](crate::runtime::agent::TeardownError::entries)
2533    /// lists every failure in registration order with its hook's name. That
2534    /// result is cached, so a repeated close returns the same failures rather than
2535    /// running teardown again — an error here is final, not a retry request. A
2536    /// panicking `close` is caught at this boundary and reported the same way.
2537    ///
2538    /// The Agent is closed either way. There is no Run left for a failure here to
2539    /// affect, which is why [`HookError`](HookError#effect-on-the-run)'s Run
2540    /// consequences do not apply.
2541    fn close(&self) -> HookResult<()>;
2542}
2543
2544/// One named hook's family registrations and admission metadata.
2545pub struct Registration {
2546    name: String,
2547    binding: Option<crate::runtime::session::Binding>,
2548    requires_session_state: bool,
2549    run: Option<Arc<dyn RunHooks>>,
2550    input: Option<Arc<dyn InputHooks>>,
2551    turn_step: Option<Arc<dyn TurnStepHooks>>,
2552    model: Option<Arc<dyn ModelHooks>>,
2553    tool: Option<Arc<dyn ToolHooks>>,
2554    observer: Option<Arc<dyn ObserverHooks>>,
2555    transcript: Option<Arc<dyn TranscriptHooks>>,
2556    teardown: Option<Arc<dyn AgentTeardown>>,
2557}
2558
2559impl fmt::Debug for Registration {
2560    /// Names the hook and states which hook families it actually claimed.
2561    ///
2562    /// Every hook is a trait object with no `Debug`, and presence is the whole
2563    /// of what a registration decides: which of the eight families this hook
2564    /// will be dispatched into.
2565    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2566        formatter
2567            .debug_struct("Registration")
2568            .field("name", &self.name)
2569            .field("binding", &self.binding)
2570            .field("requires_session_state", &self.requires_session_state)
2571            .field("run", &Presence(self.run.is_some()))
2572            .field("input", &Presence(self.input.is_some()))
2573            .field("turn_step", &Presence(self.turn_step.is_some()))
2574            .field("model", &Presence(self.model.is_some()))
2575            .field("tool", &Presence(self.tool.is_some()))
2576            .field("observer", &Presence(self.observer.is_some()))
2577            .field("transcript", &Presence(self.transcript.is_some()))
2578            .field("teardown", &Presence(self.teardown.is_some()))
2579            .finish()
2580    }
2581}
2582
2583impl Registration {
2584    /// Begins one named registration.
2585    #[must_use]
2586    pub fn new(name: String) -> Self {
2587        Self {
2588            name,
2589            binding: None,
2590            requires_session_state: false,
2591            run: None,
2592            input: None,
2593            turn_step: None,
2594            model: None,
2595            tool: None,
2596            observer: None,
2597            transcript: None,
2598            teardown: None,
2599        }
2600    }
2601
2602    /// Declares one opaque sticky Session binding.
2603    #[must_use]
2604    pub fn binding(mut self, binding: crate::runtime::session::Binding) -> Self {
2605        self.binding = Some(binding);
2606        self
2607    }
2608
2609    /// Declares use of optional successor-Run Session state.
2610    #[must_use]
2611    pub const fn requires_session_state(mut self, required: bool) -> Self {
2612        self.requires_session_state = required;
2613        self
2614    }
2615
2616    /// Mounts the Run family.
2617    #[must_use]
2618    pub fn run(mut self, hooks: Arc<dyn RunHooks>) -> Self {
2619        self.run = Some(hooks);
2620        self
2621    }
2622
2623    /// Mounts the input-admission family.
2624    #[must_use]
2625    pub fn input(mut self, hooks: Arc<dyn InputHooks>) -> Self {
2626        self.input = Some(hooks);
2627        self
2628    }
2629
2630    /// Mounts the Turn/Step family.
2631    #[must_use]
2632    pub fn turn_step(mut self, hooks: Arc<dyn TurnStepHooks>) -> Self {
2633        self.turn_step = Some(hooks);
2634        self
2635    }
2636
2637    /// Mounts the model family.
2638    #[must_use]
2639    pub fn model(mut self, hooks: Arc<dyn ModelHooks>) -> Self {
2640        self.model = Some(hooks);
2641        self
2642    }
2643
2644    /// Mounts the tool family.
2645    #[must_use]
2646    pub fn tool(mut self, hooks: Arc<dyn ToolHooks>) -> Self {
2647        self.tool = Some(hooks);
2648        self
2649    }
2650
2651    /// Mounts passive observers.
2652    #[must_use]
2653    pub fn observer(mut self, hooks: Arc<dyn ObserverHooks>) -> Self {
2654        self.observer = Some(hooks);
2655        self
2656    }
2657
2658    /// Mounts transcript reservation.
2659    #[must_use]
2660    pub fn transcript(mut self, hooks: Arc<dyn TranscriptHooks>) -> Self {
2661        self.transcript = Some(hooks);
2662        self
2663    }
2664
2665    /// Mounts Agent teardown separately from runtime families.
2666    #[must_use]
2667    pub fn teardown(mut self, hooks: Arc<dyn AgentTeardown>) -> Self {
2668        self.teardown = Some(hooks);
2669        self
2670    }
2671}
2672
2673struct RegisteredHook {
2674    registration: Registration,
2675}
2676
2677/// One family hook with its immutable registration metadata.
2678///
2679/// The index is the original registry position, not a dense family-local index,
2680/// so controllers can key independent per-registration Run state and callback
2681/// transactions without losing registrations that omitted this family.
2682pub(crate) struct RegistrationAdapter<'a, H: ?Sized> {
2683    index: usize,
2684    name: &'a str,
2685    requires_session_state: bool,
2686    hook: &'a H,
2687}
2688
2689/// Owned tool adapter used only by managed blocking callback owners.
2690pub(crate) struct OwnedToolRegistrationAdapter {
2691    index: usize,
2692    name: String,
2693    requires_session_state: bool,
2694    hook: Arc<dyn ToolHooks>,
2695}
2696
2697impl<'a, H: ?Sized> RegistrationAdapter<'a, H> {
2698    pub(crate) const fn index(&self) -> usize {
2699        self.index
2700    }
2701
2702    #[cfg_attr(not(test), expect(dead_code, reason = "reached only by tests so far"))]
2703    pub(crate) const fn name(&self) -> &'a str {
2704        self.name
2705    }
2706
2707    #[cfg_attr(not(test), expect(dead_code, reason = "reached only by tests so far"))]
2708    pub(crate) const fn requires_session_state(&self) -> bool {
2709        self.requires_session_state
2710    }
2711
2712    #[cfg_attr(not(test), expect(dead_code, reason = "reached only by tests so far"))]
2713    pub(crate) const fn hook(&self) -> &'a H {
2714        self.hook
2715    }
2716}
2717
2718impl OwnedToolRegistrationAdapter {
2719    pub(crate) const fn index(&self) -> usize {
2720        self.index
2721    }
2722
2723    pub(crate) fn name(&self) -> &str {
2724        &self.name
2725    }
2726
2727    pub(crate) fn invoke_after_tool_commit(
2728        &self,
2729        resources: CallbackResources<'_>,
2730        staged: &StagedTranscript,
2731        snapshot: &Arc<StepSnapshot>,
2732        result: &ToolResult,
2733    ) -> Vec<Item> {
2734        RegistrationAdapter {
2735            index: self.index,
2736            name: &self.name,
2737            requires_session_state: self.requires_session_state,
2738            hook: &*self.hook,
2739        }
2740        .invoke_after_tool_commit(resources, staged, snapshot, result)
2741    }
2742}
2743
2744/// Caller-owned resources for exactly one registration callback invocation.
2745///
2746/// A controller must create a fresh `run_state::Store` per registration and a fresh
2747/// `StagedTranscript` per callback. This bundle deliberately carries neither a
2748/// registry nor commit authority; the controller decides whether successful
2749/// staged work is committed and always discards failed callback stages.
2750#[derive(Clone, Copy)]
2751pub(crate) struct CallbackResources<'a> {
2752    coord: &'a Coord,
2753    run_state: &'a run_state::Store,
2754    session_state: &'a session_state::Reader,
2755    session_state_writer: Option<&'a session_state::Writer>,
2756    emitter: &'a dyn Emitter,
2757}
2758
2759/// Owned aliases of one registration's state capabilities.
2760///
2761/// These handles preserve the same slots and lease authority; they do not copy
2762/// state and never escape the crate-managed callback owner.
2763pub(crate) struct OwnedCallbackResources {
2764    run_state: run_state::Store,
2765    session_state: session_state::Reader,
2766    session_state_writer: Option<session_state::Writer>,
2767    callback_write_permit: Option<CallbackWritePermit>,
2768}
2769
2770impl OwnedCallbackResources {
2771    /// Clones the runtime-owned half of this callback's write permit.
2772    pub(crate) fn callback_write_permit(&self) -> Option<CallbackWritePermit> {
2773        self.callback_write_permit.clone()
2774    }
2775
2776    pub(crate) fn bind<'a>(
2777        &'a self,
2778        coord: &'a Coord,
2779        emitter: &'a dyn Emitter,
2780    ) -> CallbackResources<'a> {
2781        CallbackResources::new(
2782            coord,
2783            &self.run_state,
2784            &self.session_state,
2785            self.session_state_writer.as_ref(),
2786            emitter,
2787        )
2788    }
2789}
2790
2791impl<'a> CallbackResources<'a> {
2792    pub(crate) const fn new(
2793        coord: &'a Coord,
2794        run_state: &'a run_state::Store,
2795        session_state: &'a session_state::Reader,
2796        session_state_writer: Option<&'a session_state::Writer>,
2797        emitter: &'a dyn Emitter,
2798    ) -> Self {
2799        Self {
2800            coord,
2801            run_state,
2802            session_state,
2803            session_state_writer,
2804            emitter,
2805        }
2806    }
2807
2808    /// Clones only crate-private capability handles for a managed callback owner.
2809    ///
2810    /// A writable registration receives a fresh callback-local permit. The async
2811    /// owner retains the matching revocation handle, so aborting one callback does
2812    /// not revoke the registration's ordinary lease writer or any later callback.
2813    pub(crate) fn owned_handles(self) -> OwnedCallbackResources {
2814        let (session_state_writer, callback_write_permit) = match self.session_state_writer {
2815            Some(writer) => {
2816                let (writer, permit) = writer.clone_with_callback_permit();
2817                (Some(writer), Some(permit))
2818            }
2819            None => (None, None),
2820        };
2821        OwnedCallbackResources {
2822            run_state: self.run_state.clone_handle(),
2823            session_state: self.session_state.clone_handle(),
2824            session_state_writer,
2825            callback_write_permit,
2826        }
2827    }
2828
2829    /// Rebinds only the callback coordinate while preserving this registration's
2830    /// private state and capability resources.
2831    pub(crate) const fn with_coord<'b>(self, coord: &'b Coord) -> CallbackResources<'b>
2832    where
2833        'a: 'b,
2834    {
2835        self.rebind(coord, self.emitter)
2836    }
2837
2838    /// Rebinds one callback to its exact coordinate and outward emitter.
2839    ///
2840    /// Synchronous adapters use this crate-private bridge when only coordinate or
2841    /// emitter identity changes. Managed blocking callbacks instead bind the owned
2842    /// aliases above. Registration-private state capabilities remain unchanged.
2843    pub(crate) const fn rebind<'b>(
2844        self,
2845        coord: &'b Coord,
2846        emitter: &'b dyn Emitter,
2847    ) -> CallbackResources<'b>
2848    where
2849        'a: 'b,
2850    {
2851        CallbackResources {
2852            coord,
2853            run_state: self.run_state,
2854            session_state: self.session_state,
2855            session_state_writer: self.session_state_writer,
2856            emitter,
2857        }
2858    }
2859
2860    const fn scope_factory(self, requires_session_state: bool) -> ScopeFactory<'a> {
2861        ScopeFactory::new(
2862            self.coord,
2863            self.run_state,
2864            self.session_state,
2865            self.session_state_writer,
2866            requires_session_state,
2867            self.emitter,
2868        )
2869    }
2870}
2871
2872impl RegistrationAdapter<'_, dyn RunHooks> {
2873    /// Invokes only this registration's [`RunHooks::prepare`] callback.
2874    ///
2875    /// The caller supplies registration-private Run state plus callback-local
2876    /// Session-state and transcript overlays. Neither overlay is committed or
2877    /// discarded here; the caller owns resolution after observing this result.
2878    ///
2879    /// A returned [`PrepareDecision::Modify`] is validated here rather than by
2880    /// the caller, because this is the only frame that still knows *which*
2881    /// registration produced it: an empty replacement becomes a
2882    /// [`PrepareError::EmptyModify`] attributed to that name.
2883    pub(crate) fn invoke_prepare(
2884        &self,
2885        resources: CallbackResources<'_>,
2886        staged: &StagedTranscript,
2887        session_state_stage: Option<&session_state::StagedWriter>,
2888        base_snapshot: &Snapshot,
2889        input: &[Part],
2890        cancellation: &Token,
2891    ) -> Result<PrepareDecision, DispatchError> {
2892        if cancellation.is_cancelled() {
2893            return Err(DispatchError::Cancelled);
2894        }
2895        let factory = resources.scope_factory(self.requires_session_state);
2896        let scope = factory.prepare(staged, session_state_stage, base_snapshot, input);
2897        match self.hook.prepare(&scope) {
2898            Err(error) => Err(DispatchError::Callback(AttributedError {
2899                name: self.name.to_owned(),
2900                error,
2901            })),
2902            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
2903            Ok(PrepareDecision::Modify(replacement)) if replacement.is_empty() => {
2904                Err(DispatchError::Callback(AttributedError {
2905                    name: self.name.to_owned(),
2906                    error: HookError::new(PrepareError::EmptyModify),
2907                }))
2908            }
2909            Ok(decision) => Ok(decision),
2910        }
2911    }
2912
2913    /// Invokes only this registration's [`RunHooks::compose_continuation`] callback.
2914    ///
2915    /// The decision governs a continuation request: a non-empty request asks the
2916    /// loop for another Turn rather than ending the Run. `continuation` carries
2917    /// what earlier registrations already asked for, so a registration can see,
2918    /// extend, replace or ignore it.
2919    ///
2920    /// Unlike [`RegistrationAdapter::invoke_prepare`] this validates nothing: an
2921    /// empty [`ContinuationDecision::Replace`] is a deliberate veto of a peer's
2922    /// request, not a rewrite that discards user content.
2923    pub(crate) fn invoke_compose_continuation(
2924        &self,
2925        resources: CallbackResources<'_>,
2926        staged: &StagedTranscript,
2927        continuation: &[Part],
2928        continuations: usize,
2929        turns: usize,
2930        cancellation: &Token,
2931    ) -> Result<ContinuationDecision, DispatchError> {
2932        if cancellation.is_cancelled() {
2933            return Err(DispatchError::Cancelled);
2934        }
2935        let factory = resources.scope_factory(self.requires_session_state);
2936        let scope = factory.compose_continuation(staged, continuation, continuations, turns);
2937        match self.hook.compose_continuation(&scope) {
2938            Err(error) => Err(DispatchError::Callback(AttributedError {
2939                name: self.name.to_owned(),
2940                error,
2941            })),
2942            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
2943            Ok(decision) => Ok(decision),
2944        }
2945    }
2946
2947    /// Invokes only this registration's [`RunHooks::decide_stop`] callback.
2948    ///
2949    /// This is the sole surface through which a hook may stop a Run with a
2950    /// code; the loop converts a stopping decision into the single privately
2951    /// owned `EventStop` (ADR-007).
2952    pub(crate) fn invoke_decide_stop(
2953        &self,
2954        resources: CallbackResources<'_>,
2955        cancellation: &Token,
2956    ) -> Result<StopDecision, DispatchError> {
2957        if cancellation.is_cancelled() {
2958            return Err(DispatchError::Cancelled);
2959        }
2960        let factory = resources.scope_factory(self.requires_session_state);
2961        let scope = factory.decide_stop();
2962        match self.hook.decide_stop(&scope) {
2963            Err(error) => Err(DispatchError::Callback(AttributedError {
2964                name: self.name.to_owned(),
2965                error,
2966            })),
2967            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
2968            Ok(decision) => Ok(decision),
2969        }
2970    }
2971}
2972
2973impl RegistrationAdapter<'_, dyn TurnStepHooks> {
2974    /// Invokes only this registration's `OnBeforeTurn` callback.
2975    ///
2976    /// `trigger` is what opened this Turn — the admitted Run input, a claimed
2977    /// `NextTurn` batch, or a continuation an earlier
2978    /// [`RunHooks::compose_continuation`] asked for.
2979    /// The returned items are appended before the Turn's first Step.
2980    pub(crate) fn invoke_before_turn(
2981        &self,
2982        resources: CallbackResources<'_>,
2983        staged: &StagedTranscript,
2984        trigger: &[Item],
2985        cancellation: &Token,
2986    ) -> Result<Vec<Item>, DispatchError> {
2987        self.invoke_turn(resources, staged, trigger, cancellation, TurnHook::Before)
2988    }
2989
2990    /// Invokes only this registration's `OnAfterTurn` callback.
2991    pub(crate) fn invoke_after_turn(
2992        &self,
2993        resources: CallbackResources<'_>,
2994        staged: &StagedTranscript,
2995        trigger: &[Item],
2996        cancellation: &Token,
2997    ) -> Result<Vec<Item>, DispatchError> {
2998        self.invoke_turn(resources, staged, trigger, cancellation, TurnHook::After)
2999    }
3000
3001    /// Runs one Turn-boundary callback.
3002    ///
3003    /// Both boundaries take the same scope and return the same shape, so the
3004    /// cancellation and attribution rules exist once and cannot drift apart.
3005    fn invoke_turn(
3006        &self,
3007        resources: CallbackResources<'_>,
3008        staged: &StagedTranscript,
3009        trigger: &[Item],
3010        cancellation: &Token,
3011        boundary: TurnHook,
3012    ) -> Result<Vec<Item>, DispatchError> {
3013        if cancellation.is_cancelled() {
3014            return Err(DispatchError::Cancelled);
3015        }
3016        let factory = resources.scope_factory(self.requires_session_state);
3017        let scope = factory.turn(staged, trigger);
3018        let result = match boundary {
3019            TurnHook::Before => self.hook.before_turn(&scope),
3020            TurnHook::After => self.hook.after_turn(&scope),
3021        };
3022        match result {
3023            Err(error) => Err(DispatchError::Callback(AttributedError {
3024                name: self.name.to_owned(),
3025                error,
3026            })),
3027            Ok(_items) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
3028            Ok(items) => Ok(items),
3029        }
3030    }
3031
3032    /// Invokes only this registration's `OnAfterStep` callback.
3033    ///
3034    /// The decision decides whether the Turn continues past this Step; the items
3035    /// it carries are appended either way.
3036    pub(crate) fn invoke_after_step(
3037        &self,
3038        resources: CallbackResources<'_>,
3039        staged: &StagedTranscript,
3040        snapshot: &Arc<StepSnapshot>,
3041        cancellation: &Token,
3042    ) -> Result<AfterStepDecision, DispatchError> {
3043        if cancellation.is_cancelled() {
3044            return Err(DispatchError::Cancelled);
3045        }
3046        let factory = resources.scope_factory(self.requires_session_state);
3047        let scope = factory.after_step(staged, snapshot);
3048        match self.hook.after_step(&scope) {
3049            Err(error) => Err(DispatchError::Callback(AttributedError {
3050                name: self.name.to_owned(),
3051                error,
3052            })),
3053            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
3054            Ok(decision) => Ok(decision),
3055        }
3056    }
3057
3058    /// Invokes only this registration's `OnBeforeStep` callback.
3059    ///
3060    /// The caller supplies registration-private Run state, a lease-bound writer,
3061    /// and a callback-local staged transcript. This method has no authority to
3062    /// commit that staged transcript into the live Session.
3063    pub(crate) fn invoke_before_step(
3064        &self,
3065        resources: CallbackResources<'_>,
3066        staged: &StagedTranscript,
3067        model: &Info,
3068        plan: &mut RequestPlan,
3069        cancellation: &Token,
3070    ) -> Result<Vec<Item>, DispatchError> {
3071        if cancellation.is_cancelled() {
3072            return Err(DispatchError::Cancelled);
3073        }
3074        let factory = resources.scope_factory(self.requires_session_state);
3075        let mut scope = factory.before_step(staged, model, plan);
3076        match self.hook.before_step(&mut scope) {
3077            Err(error) => Err(DispatchError::Callback(AttributedError {
3078                name: self.name.to_owned(),
3079                error,
3080            })),
3081            Ok(_items) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
3082            Ok(items) => Ok(items),
3083        }
3084    }
3085}
3086
3087impl RegistrationAdapter<'_, dyn ObserverHooks> {
3088    /// Invokes only this registration's lifecycle observer.
3089    ///
3090    /// Callback audits are buffered locally. Buffer flushes and core panic
3091    /// audits remain outside the catch boundary, so core panics propagate.
3092    pub(crate) fn invoke_lifecycle(
3093        &self,
3094        resources: CallbackResources<'_>,
3095        snapshot: Option<&Arc<StepSnapshot>>,
3096        observation: &LifecycleObservation,
3097    ) {
3098        let factory = resources.scope_factory(self.requires_session_state);
3099        let pending = CallbackAuditBuffer::new();
3100        let scope = factory.observer(snapshot);
3101        let buffered_scope = scope.with_audit_sink(&pending);
3102        let result = catch_unwind(AssertUnwindSafe(|| {
3103            self.hook.lifecycle(observation, &buffered_scope);
3104        }));
3105        pending.flush_to(resources.emitter);
3106        if result.is_err() {
3107            emit_observer_panic(
3108                resources.emitter,
3109                self.name,
3110                lifecycle_hook_name(observation.kind()),
3111            );
3112        }
3113    }
3114
3115    /// Invokes only this registration's synchronous admission observer.
3116    pub(crate) fn invoke_run_admitted(&self, resources: CallbackResources<'_>) {
3117        let factory = resources.scope_factory(self.requires_session_state);
3118        let scope = factory.read();
3119        let result = catch_unwind(AssertUnwindSafe(|| self.hook.run_admitted(&scope)));
3120        if result.is_err() {
3121            emit_observer_panic(resources.emitter, self.name, "OnRunAdmitted");
3122        }
3123    }
3124
3125    /// Invokes only this registration's model-event observer.
3126    pub(crate) fn invoke_model_event(
3127        &self,
3128        resources: CallbackResources<'_>,
3129        snapshot: Option<&Arc<StepSnapshot>>,
3130        event: &model::Event,
3131    ) {
3132        let factory = resources.scope_factory(self.requires_session_state);
3133        let pending = CallbackAuditBuffer::new();
3134        let scope = factory.observer(snapshot);
3135        let buffered_scope = scope.with_audit_sink(&pending);
3136        let result = catch_unwind(AssertUnwindSafe(|| {
3137            self.hook.model_event(&buffered_scope, event);
3138        }));
3139        pending.flush_to(resources.emitter);
3140        if result.is_err() {
3141            emit_observer_panic(resources.emitter, self.name, "OnModelEvent");
3142        }
3143    }
3144
3145    /// Invokes only this registration's serialized audit observer.
3146    pub(crate) fn invoke_audit_event(
3147        &self,
3148        resources: CallbackResources<'_>,
3149        event: &audit::Event,
3150    ) {
3151        let factory = resources.scope_factory(self.requires_session_state);
3152        let scope = factory.read();
3153        let result = catch_unwind(AssertUnwindSafe(|| self.hook.audit_event(&scope, event)));
3154        if result.is_err() {
3155            emit_observer_panic(resources.emitter, self.name, "OnAuditEvent");
3156        }
3157    }
3158}
3159
3160impl RegistrationAdapter<'_, dyn InputHooks> {
3161    /// Invokes only this registration's `OnBeforeInputAdmit` callback.
3162    ///
3163    /// `OnBeforeInputAdmit` is infallible by trait shape, so cancellation is the
3164    /// only dispatch failure. The pre-callback check fails the claimed batch
3165    /// rather than admitting new work after cancellation.
3166    pub(crate) fn invoke_before_input_admit(
3167        &self,
3168        resources: CallbackResources<'_>,
3169        target: InputTarget,
3170        items: &[Item],
3171        cancellation: &Token,
3172    ) -> Result<InputAdmitDecision, DispatchError> {
3173        if cancellation.is_cancelled() {
3174            return Err(DispatchError::Cancelled);
3175        }
3176        let factory = resources.scope_factory(self.requires_session_state);
3177        let scope = factory.input_admit(target, items);
3178        let decision = self.hook.before_input_admit(&scope);
3179        if cancellation.is_cancelled() {
3180            return Err(DispatchError::Cancelled);
3181        }
3182        Ok(decision)
3183    }
3184}
3185
3186impl RegistrationAdapter<'_, dyn ModelHooks> {
3187    /// Invokes only this registration's `OnBeforeModel` callback.
3188    ///
3189    /// A real callback error outranks a concurrently observed cancellation, so
3190    /// the cancellation re-check runs only on the `Ok` path.
3191    pub(crate) fn invoke_before_model(
3192        &self,
3193        resources: CallbackResources<'_>,
3194        snapshot: &Arc<StepSnapshot>,
3195        request: &Request,
3196        cancellation: &Token,
3197    ) -> Result<BeforeModelDecision, DispatchError> {
3198        if cancellation.is_cancelled() {
3199            return Err(DispatchError::Cancelled);
3200        }
3201        let factory = resources.scope_factory(self.requires_session_state);
3202        let scope = factory.before_model(snapshot, request);
3203        match self.hook.before_model(&scope) {
3204            Err(error) => Err(DispatchError::Callback(AttributedError {
3205                name: self.name.to_owned(),
3206                error,
3207            })),
3208            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
3209            Ok(decision) => Ok(decision),
3210        }
3211    }
3212
3213    /// Invokes only this registration's `OnAfterModel` callback.
3214    #[expect(
3215        clippy::too_many_arguments,
3216        reason = "OnAfterModel observes five independent frozen model facts plus its resources"
3217    )]
3218    pub(crate) fn invoke_after_model(
3219        &self,
3220        resources: CallbackResources<'_>,
3221        snapshot: &Arc<StepSnapshot>,
3222        output: &Assistant,
3223        generated: bool,
3224        finish_reason: &str,
3225        completion: CompletionReason,
3226        cancellation: &Token,
3227    ) -> Result<AfterModelDecision, DispatchError> {
3228        if cancellation.is_cancelled() {
3229            return Err(DispatchError::Cancelled);
3230        }
3231        let factory = resources.scope_factory(self.requires_session_state);
3232        let scope = factory.after_model(snapshot, output, generated, finish_reason, completion);
3233        let decision = self.hook.after_model(&scope);
3234        if cancellation.is_cancelled() {
3235            return Err(DispatchError::Cancelled);
3236        }
3237        Ok(decision)
3238    }
3239}
3240
3241impl RegistrationAdapter<'_, dyn ToolHooks> {
3242    /// Invokes only this registration's `OnBeforeToolCall` callback.
3243    ///
3244    /// This rewrite plane runs strictly before the separate `Gate` plane, so a
3245    /// gate always decides on the call the rewrites produced.
3246    pub(crate) fn invoke_before_tool_call(
3247        &self,
3248        resources: CallbackResources<'_>,
3249        snapshot: &Arc<StepSnapshot>,
3250        call: &ToolCall,
3251        cancellation: &Token,
3252    ) -> Result<ToolCallDecision, DispatchError> {
3253        if cancellation.is_cancelled() {
3254            return Err(DispatchError::Cancelled);
3255        }
3256        let factory = resources.scope_factory(self.requires_session_state);
3257        let scope = factory.tool_call(snapshot, call);
3258        match self.hook.before_tool_call(&scope) {
3259            Err(error) => Err(DispatchError::Callback(AttributedError {
3260                name: self.name.to_owned(),
3261                error,
3262            })),
3263            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
3264            Ok(decision) => Ok(decision),
3265        }
3266    }
3267
3268    /// Invokes only this registration's `OnBeforeToolResult` callback.
3269    ///
3270    /// Each rewrite is observed by the next registration, so the committed
3271    /// append, the outward result event, and the `ToolCall` end observation all
3272    /// report the same output.
3273    pub(crate) fn invoke_before_tool_result(
3274        &self,
3275        resources: CallbackResources<'_>,
3276        snapshot: &Arc<StepSnapshot>,
3277        call: &ToolCall,
3278        disposition: CallDisposition,
3279        result: &ToolResult,
3280        cancellation: &Token,
3281    ) -> Result<ToolResultDecision, DispatchError> {
3282        if cancellation.is_cancelled() {
3283            return Err(DispatchError::Cancelled);
3284        }
3285        let factory = resources.scope_factory(self.requires_session_state);
3286        let scope = factory.tool_result(snapshot, call, disposition, result);
3287        match self.hook.before_tool_result(&scope) {
3288            Err(error) => Err(DispatchError::Callback(AttributedError {
3289                name: self.name.to_owned(),
3290                error,
3291            })),
3292            Ok(_decision) if cancellation.is_cancelled() => Err(DispatchError::Cancelled),
3293            Ok(decision) => Ok(decision),
3294        }
3295    }
3296
3297    /// Invokes only this registration's [`ToolHooks::after_tool_commit`] callback.
3298    ///
3299    /// The result batch is already durable at this boundary, so this late hook
3300    /// cannot fail the batch and takes no cancellation token: cancelling here
3301    /// would drop items that belong to an already-committed batch.
3302    pub(crate) fn invoke_after_tool_commit(
3303        &self,
3304        resources: CallbackResources<'_>,
3305        staged: &StagedTranscript,
3306        snapshot: &Arc<StepSnapshot>,
3307        result: &ToolResult,
3308    ) -> Vec<Item> {
3309        let factory = resources.scope_factory(self.requires_session_state);
3310        let scope = factory.after_tool_commit(staged, snapshot, result);
3311        self.hook.after_tool_commit(&scope)
3312    }
3313}
3314
3315impl RegistrationAdapter<'_, dyn TranscriptHooks> {
3316    /// Invokes only this registration's `OnTranscriptMutation` callback.
3317    ///
3318    /// The callback runs inside the controller's single pre-commit critical
3319    /// section and therefore receives a [`ReadScope`], which cannot re-enter the
3320    /// commit path or the outward boundary. Returning the reservation to
3321    /// the caller keeps abort/publish authority with the controller.
3322    pub(crate) fn invoke_reserve(
3323        &self,
3324        resources: CallbackResources<'_>,
3325        mutation: &TranscriptMutation,
3326    ) -> Result<Box<dyn TranscriptReservation>, DispatchError> {
3327        let factory = resources.scope_factory(self.requires_session_state);
3328        let scope = factory.read();
3329        self.hook.reserve(&scope, mutation).map_err(|error| {
3330            DispatchError::Callback(AttributedError {
3331                name: self.name.to_owned(),
3332                error,
3333            })
3334        })
3335    }
3336}
3337
3338/// Fail-closed immutable registry construction error.
3339#[derive(Clone, Debug, Eq, PartialEq)]
3340#[non_exhaustive]
3341pub enum RegistryError {
3342    /// A hook name was empty.
3343    EmptyName,
3344    /// A hook name appeared more than once.
3345    DuplicateName(String),
3346}
3347
3348impl fmt::Display for RegistryError {
3349    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3350        match self {
3351            Self::EmptyName => formatter.write_str("hook name must be non-empty"),
3352            Self::DuplicateName(name) => write!(formatter, "duplicate hook name: {name}"),
3353        }
3354    }
3355}
3356
3357impl Error for RegistryError {}
3358
3359/// One callback failure attributed to its stable registration name.
3360#[derive(Clone, Debug)]
3361pub struct AttributedError {
3362    name: String,
3363    error: HookError,
3364}
3365
3366impl AttributedError {
3367    /// Returns the hook registration name.
3368    #[must_use]
3369    pub fn name(&self) -> &str {
3370        &self.name
3371    }
3372
3373    /// Returns the unflattened callback error.
3374    #[must_use]
3375    pub const fn error(&self) -> &HookError {
3376        &self.error
3377    }
3378}
3379
3380impl fmt::Display for AttributedError {
3381    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3382        write!(formatter, "hook {} failed: {}", self.name, self.error)
3383    }
3384}
3385
3386impl Error for AttributedError {
3387    fn source(&self) -> Option<&(dyn Error + 'static)> {
3388        Some(&self.error)
3389    }
3390}
3391
3392/// Which of the two Turn-boundary callbacks one dispatch runs.
3393#[derive(Clone, Copy)]
3394enum TurnHook {
3395    Before,
3396    After,
3397}
3398
3399/// Mutating dispatch failure with callback errors distinct from cancellation.
3400#[derive(Clone, Debug)]
3401#[non_exhaustive]
3402pub(crate) enum DispatchError {
3403    /// A real callback failed and outranks a concurrently observed cancellation.
3404    Callback(AttributedError),
3405    /// Cancellation was observed after the preceding callback returned normally.
3406    Cancelled,
3407}
3408
3409impl fmt::Display for DispatchError {
3410    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3411        match self {
3412            Self::Callback(failure) => write!(
3413                formatter,
3414                "hook {} failed: {}",
3415                failure.name(),
3416                failure.error()
3417            ),
3418            Self::Cancelled => formatter.write_str("cancelled around a callback"),
3419        }
3420    }
3421}
3422
3423impl Error for DispatchError {
3424    /// Returns the attributed callback failure, chain intact.
3425    ///
3426    /// The immediate cause is the [`AttributedError`], not the [`HookError`]
3427    /// inside it. Returning the inner error directly would drop the one link
3428    /// that carries the registration name, so a caller walking the chain could
3429    /// read the failure but never learn which hook produced it. The name is
3430    /// not recoverable from anything below, and `AttributedError` yields the
3431    /// callback error from its own `source`, so nothing deeper is lost.
3432    ///
3433    /// Cancellation is the runtime's own observation rather than a report of
3434    /// something else, so it has no cause underneath it.
3435    fn source(&self) -> Option<&(dyn Error + 'static)> {
3436        match self {
3437            Self::Callback(failure) => Some(failure),
3438            Self::Cancelled => None,
3439        }
3440    }
3441}
3442
3443/// Mutable builder consumed into an immutable, shareable hook registry.
3444#[derive(Default)]
3445pub struct RegistryBuilder {
3446    hooks: Vec<Registration>,
3447}
3448
3449impl fmt::Debug for RegistryBuilder {
3450    /// Lists the hook names registered so far, in registration order.
3451    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3452        debug_hook_names("RegistryBuilder", self.hooks.iter(), formatter)
3453    }
3454}
3455
3456// A registry and the builder it is frozen from are both identified by the
3457// ordered hook roster they carry, and registration order is dispatch order.
3458fn debug_hook_names<'a>(
3459    name: &str,
3460    hooks: impl Iterator<Item = &'a Registration>,
3461    formatter: &mut fmt::Formatter<'_>,
3462) -> fmt::Result {
3463    formatter
3464        .debug_struct(name)
3465        .field(
3466            "hooks",
3467            &hooks
3468                .map(|registration| registration.name.as_str())
3469                .collect::<Vec<_>>(),
3470        )
3471        .finish()
3472}
3473
3474impl RegistryBuilder {
3475    /// Creates an empty builder.
3476    #[must_use]
3477    pub fn new() -> Self {
3478        Self::default()
3479    }
3480
3481    /// Appends one complete hook registration in observable fan-out order.
3482    pub fn register(&mut self, hook: Registration) -> &mut Self {
3483        self.hooks.push(hook);
3484        self
3485    }
3486
3487    /// Validates names and freezes registration order and trait objects.
3488    ///
3489    /// # Errors
3490    ///
3491    /// [`RegistryError::EmptyName`] if any registration has no name, or
3492    /// [`RegistryError::DuplicateName`], naming it, if two share one. A name is not
3493    /// decoration: it is how a callback failure is attributed back to the hook
3494    /// that caused it, so an unnamed or ambiguous registration would make an
3495    /// [`AttributedError`] point at nothing or at either of two hooks.
3496    /// Registrations are checked in order, so the first offender is the one
3497    /// reported.
3498    pub fn build(self) -> Result<Registry, RegistryError> {
3499        let mut names = std::collections::HashSet::new();
3500        let mut hooks = Vec::with_capacity(self.hooks.len());
3501        for registration in self.hooks {
3502            if registration.name.is_empty() {
3503                return Err(RegistryError::EmptyName);
3504            }
3505            if !names.insert(registration.name.clone()) {
3506                return Err(RegistryError::DuplicateName(registration.name));
3507            }
3508            hooks.push(RegisteredHook { registration });
3509        }
3510        Ok(Registry {
3511            hooks: hooks.into(),
3512        })
3513    }
3514}
3515
3516/// Immutable runtime hook registry with stable registration-order fan-out.
3517#[derive(Clone)]
3518pub struct Registry {
3519    hooks: Arc<[RegisteredHook]>,
3520}
3521
3522impl fmt::Debug for Registry {
3523    /// Lists the frozen hook roster, in registration order.
3524    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3525        debug_hook_names(
3526            "Registry",
3527            self.hooks.iter().map(|hook| &hook.registration),
3528            formatter,
3529        )
3530    }
3531}
3532
3533impl Registry {
3534    /// Returns the number of named registrations.
3535    #[must_use]
3536    pub fn len(&self) -> usize {
3537        self.hooks.len()
3538    }
3539
3540    /// Reports whether no hook is registered.
3541    #[must_use]
3542    pub fn is_empty(&self) -> bool {
3543        self.hooks.is_empty()
3544    }
3545
3546    /// Iterates stable registration names.
3547    #[must_use]
3548    pub fn names(&self) -> impl ExactSizeIterator<Item = &str> {
3549        self.hooks
3550            .iter()
3551            .map(|hook| hook.registration.name.as_str())
3552    }
3553
3554    /// Returns owned sticky bindings in registration order.
3555    #[must_use]
3556    pub fn bindings(&self) -> Vec<crate::runtime::session::Binding> {
3557        self.hooks
3558            .iter()
3559            .filter_map(|hook| hook.registration.binding.clone())
3560            .collect()
3561    }
3562
3563    /// Reports whether any hook requires optional Session state support.
3564    #[must_use]
3565    pub fn requires_session_state(&self) -> bool {
3566        self.hooks
3567            .iter()
3568            .any(|hook| hook.registration.requires_session_state)
3569    }
3570
3571    pub(crate) fn run_hooks(&self) -> impl Iterator<Item = RegistrationAdapter<'_, dyn RunHooks>> {
3572        self.hooks
3573            .iter()
3574            .enumerate()
3575            .filter_map(|(index, registered)| {
3576                registered
3577                    .registration
3578                    .run
3579                    .as_deref()
3580                    .map(|hook| RegistrationAdapter {
3581                        index,
3582                        name: registered.registration.name.as_str(),
3583                        requires_session_state: registered.registration.requires_session_state,
3584                        hook,
3585                    })
3586            })
3587    }
3588
3589    pub(crate) fn input_hooks(
3590        &self,
3591    ) -> impl Iterator<Item = RegistrationAdapter<'_, dyn InputHooks>> {
3592        self.hooks
3593            .iter()
3594            .enumerate()
3595            .filter_map(|(index, registered)| {
3596                registered
3597                    .registration
3598                    .input
3599                    .as_deref()
3600                    .map(|hook| RegistrationAdapter {
3601                        index,
3602                        name: registered.registration.name.as_str(),
3603                        requires_session_state: registered.registration.requires_session_state,
3604                        hook,
3605                    })
3606            })
3607    }
3608
3609    pub(crate) fn turn_step_hooks(
3610        &self,
3611    ) -> impl Iterator<Item = RegistrationAdapter<'_, dyn TurnStepHooks>> {
3612        self.hooks
3613            .iter()
3614            .enumerate()
3615            .filter_map(|(index, registered)| {
3616                registered
3617                    .registration
3618                    .turn_step
3619                    .as_deref()
3620                    .map(|hook| RegistrationAdapter {
3621                        index,
3622                        name: registered.registration.name.as_str(),
3623                        requires_session_state: registered.registration.requires_session_state,
3624                        hook,
3625                    })
3626            })
3627    }
3628
3629    pub(crate) fn model_hooks(
3630        &self,
3631    ) -> impl Iterator<Item = RegistrationAdapter<'_, dyn ModelHooks>> {
3632        self.hooks
3633            .iter()
3634            .enumerate()
3635            .filter_map(|(index, registered)| {
3636                registered
3637                    .registration
3638                    .model
3639                    .as_deref()
3640                    .map(|hook| RegistrationAdapter {
3641                        index,
3642                        name: registered.registration.name.as_str(),
3643                        requires_session_state: registered.registration.requires_session_state,
3644                        hook,
3645                    })
3646            })
3647    }
3648
3649    pub(crate) fn tool_hooks(
3650        &self,
3651    ) -> impl Iterator<Item = RegistrationAdapter<'_, dyn ToolHooks>> {
3652        self.hooks
3653            .iter()
3654            .enumerate()
3655            .filter_map(|(index, registered)| {
3656                registered
3657                    .registration
3658                    .tool
3659                    .as_deref()
3660                    .map(|hook| RegistrationAdapter {
3661                        index,
3662                        name: registered.registration.name.as_str(),
3663                        requires_session_state: registered.registration.requires_session_state,
3664                        hook,
3665                    })
3666            })
3667    }
3668
3669    pub(crate) fn owned_tool_hooks(
3670        &self,
3671    ) -> impl Iterator<Item = OwnedToolRegistrationAdapter> + '_ {
3672        self.hooks
3673            .iter()
3674            .enumerate()
3675            .filter_map(|(index, registered)| {
3676                registered
3677                    .registration
3678                    .tool
3679                    .as_ref()
3680                    .map(|hook| OwnedToolRegistrationAdapter {
3681                        index,
3682                        name: registered.registration.name.clone(),
3683                        requires_session_state: registered.registration.requires_session_state,
3684                        hook: Arc::clone(hook),
3685                    })
3686            })
3687    }
3688
3689    pub(crate) fn observer_hooks(
3690        &self,
3691    ) -> impl Iterator<Item = RegistrationAdapter<'_, dyn ObserverHooks>> {
3692        self.hooks
3693            .iter()
3694            .enumerate()
3695            .filter_map(|(index, registered)| {
3696                registered
3697                    .registration
3698                    .observer
3699                    .as_deref()
3700                    .map(|hook| RegistrationAdapter {
3701                        index,
3702                        name: registered.registration.name.as_str(),
3703                        requires_session_state: registered.registration.requires_session_state,
3704                        hook,
3705                    })
3706            })
3707    }
3708
3709    pub(crate) fn transcript_hooks(
3710        &self,
3711    ) -> impl Iterator<Item = RegistrationAdapter<'_, dyn TranscriptHooks>> {
3712        self.hooks
3713            .iter()
3714            .enumerate()
3715            .filter_map(|(index, registered)| {
3716                registered
3717                    .registration
3718                    .transcript
3719                    .as_deref()
3720                    .map(|hook| RegistrationAdapter {
3721                        index,
3722                        name: registered.registration.name.as_str(),
3723                        requires_session_state: registered.registration.requires_session_state,
3724                        hook,
3725                    })
3726            })
3727    }
3728
3729    /// Fans out Agent teardown and collects every real error without short-circuiting.
3730    #[must_use]
3731    pub fn close(&self) -> Vec<AttributedError> {
3732        let mut failures = Vec::new();
3733        for hook in self.hooks.iter() {
3734            let Some(teardown) = &hook.registration.teardown else {
3735                continue;
3736            };
3737            if let Err(error) = teardown.close() {
3738                failures.push(AttributedError {
3739                    name: hook.registration.name.clone(),
3740                    error,
3741                });
3742            }
3743        }
3744        failures
3745    }
3746
3747    pub(crate) fn close_isolated(&self, panic_error: &HookError) -> Vec<AttributedError> {
3748        let mut failures = Vec::new();
3749        for hook in self.hooks.iter() {
3750            let Some(teardown) = &hook.registration.teardown else {
3751                continue;
3752            };
3753            let error = match catch_unwind(AssertUnwindSafe(|| teardown.close())) {
3754                Ok(Ok(())) => continue,
3755                Ok(Err(error)) => error,
3756                Err(_) => panic_error.clone(),
3757            };
3758            failures.push(AttributedError {
3759                name: hook.registration.name.clone(),
3760                error,
3761            });
3762        }
3763        failures
3764    }
3765}
3766
3767pub(crate) const fn lifecycle_hook_name(kind: LifecycleKind) -> &'static str {
3768    match kind {
3769        LifecycleKind::RunStart => "OnRunStart",
3770        LifecycleKind::RunEnd => "OnRunEnd",
3771        LifecycleKind::TurnStart => "OnTurnStart",
3772        LifecycleKind::TurnEnd => "OnTurnEnd",
3773        LifecycleKind::StepStart => "OnStepStart",
3774        LifecycleKind::StepEnd => "OnStepEnd",
3775        LifecycleKind::GenerationStart => "OnGenerationStart",
3776        LifecycleKind::GenerationEnd => "OnGenerationEnd",
3777        LifecycleKind::ToolCallStart => "OnToolCallStart",
3778        LifecycleKind::ToolCallEnd => "OnToolCallEnd",
3779    }
3780}
3781
3782fn emit_observer_panic(emitter: &dyn Emitter, registration: &str, callback: &str) {
3783    let payload = format!("{registration}:{callback}")
3784        .into_bytes()
3785        .into_boxed_slice();
3786    emitter.emit_audit(audit::Event::new(
3787        "hook.observer_panic".to_owned(),
3788        Some(payload),
3789    ));
3790}
3791
3792pub(crate) struct ScopeFactory<'a> {
3793    coord: &'a Coord,
3794    run_state: &'a run_state::Store,
3795    session_state: &'a session_state::Reader,
3796    session_state_writer: Option<&'a session_state::Writer>,
3797    requires_session_state: bool,
3798    emitter: &'a dyn Emitter,
3799    direct_audit: DirectAuditSink<'a>,
3800}
3801
3802impl<'a> ScopeFactory<'a> {
3803    /// Builds scopes for one hook adapter. `requires_session_state` is taken
3804    /// from that adapter's frozen registration metadata; a writer is never
3805    /// exposed when the declaration is false.
3806    pub(crate) const fn new(
3807        coord: &'a Coord,
3808        run_state: &'a run_state::Store,
3809        session_state: &'a session_state::Reader,
3810        session_state_writer: Option<&'a session_state::Writer>,
3811        requires_session_state: bool,
3812        emitter: &'a dyn Emitter,
3813    ) -> Self {
3814        Self {
3815            coord,
3816            run_state,
3817            session_state,
3818            session_state_writer,
3819            requires_session_state,
3820            emitter,
3821            direct_audit: DirectAuditSink(emitter),
3822        }
3823    }
3824
3825    const fn read_base(&self) -> ReadBase<'a> {
3826        ReadBase {
3827            session: SessionIdentity(self.coord),
3828            coord: self.coord,
3829            run_state: self.run_state,
3830            session_state: self.session_state,
3831        }
3832    }
3833
3834    const fn write_base(&self) -> WriteBase<'a> {
3835        WriteBase {
3836            read: self.read_base(),
3837            session_state: if self.requires_session_state {
3838                self.session_state_writer
3839            } else {
3840                None
3841            },
3842        }
3843    }
3844
3845    const fn control_base(&self) -> ControlBase<'a> {
3846        ControlBase {
3847            write: self.write_base(),
3848            emitter: self.emitter,
3849        }
3850    }
3851
3852    const fn staged_base(&self, staged: &'a StagedTranscript) -> StagedBase<'a> {
3853        StagedBase {
3854            control: self.control_base(),
3855            staged,
3856        }
3857    }
3858
3859    pub(crate) const fn prepare(
3860        &self,
3861        staged: &'a StagedTranscript,
3862        session_state_stage: Option<&'a session_state::StagedWriter>,
3863        base_snapshot: &'a Snapshot,
3864        input: &'a [Part],
3865    ) -> PrepareScope<'a> {
3866        PrepareScope {
3867            base: PrepareBase {
3868                read: self.read_base(),
3869                session_state: if self.requires_session_state {
3870                    session_state_stage
3871                } else {
3872                    None
3873                },
3874            },
3875            staged,
3876            base_snapshot,
3877            input,
3878        }
3879    }
3880
3881    pub(crate) const fn compose_continuation(
3882        &self,
3883        staged: &'a StagedTranscript,
3884        continuation: &'a [Part],
3885        continuations: usize,
3886        turns: usize,
3887    ) -> ContinuationScope<'a> {
3888        ContinuationScope {
3889            base: self.staged_base(staged),
3890            continuation,
3891            continuations,
3892            turns,
3893        }
3894    }
3895
3896    pub(crate) const fn decide_stop(&self) -> StopDecisionScope<'a> {
3897        StopDecisionScope {
3898            base: self.control_base(),
3899        }
3900    }
3901
3902    pub(crate) const fn input_admit(
3903        &self,
3904        target: InputTarget,
3905        items: &'a [Item],
3906    ) -> InputAdmitScope<'a> {
3907        InputAdmitScope {
3908            base: self.control_base(),
3909            target,
3910            items,
3911        }
3912    }
3913
3914    pub(crate) const fn turn(
3915        &self,
3916        staged: &'a StagedTranscript,
3917        trigger: &'a [Item],
3918    ) -> TurnScope<'a> {
3919        TurnScope {
3920            base: self.staged_base(staged),
3921            trigger,
3922        }
3923    }
3924
3925    pub(crate) const fn before_step<'scope>(
3926        &'scope self,
3927        staged: &'scope StagedTranscript,
3928        model: &'scope Info,
3929        plan: &'scope mut RequestPlan,
3930    ) -> BeforeStepScope<'scope> {
3931        BeforeStepScope {
3932            base: self.staged_base(staged),
3933            model,
3934            plan,
3935        }
3936    }
3937
3938    pub(crate) const fn after_step(
3939        &self,
3940        staged: &'a StagedTranscript,
3941        snapshot: &'a Arc<StepSnapshot>,
3942    ) -> AfterStepScope<'a> {
3943        AfterStepScope {
3944            base: self.staged_base(staged),
3945            snapshot,
3946        }
3947    }
3948
3949    pub(crate) const fn before_model(
3950        &self,
3951        snapshot: &'a Arc<StepSnapshot>,
3952        request: &'a Request,
3953    ) -> BeforeModelScope<'a> {
3954        BeforeModelScope {
3955            base: self.control_base(),
3956            snapshot,
3957            request,
3958        }
3959    }
3960
3961    pub(crate) const fn after_model(
3962        &self,
3963        snapshot: &'a Arc<StepSnapshot>,
3964        output: &'a Assistant,
3965        generated: bool,
3966        finish_reason: &'a str,
3967        completion: CompletionReason,
3968    ) -> AfterModelScope<'a> {
3969        AfterModelScope {
3970            base: self.control_base(),
3971            snapshot,
3972            output,
3973            generated,
3974            finish_reason,
3975            completion,
3976        }
3977    }
3978
3979    pub(crate) const fn tool_call(
3980        &self,
3981        snapshot: &'a Arc<StepSnapshot>,
3982        call: &'a ToolCall,
3983    ) -> ToolCallScope<'a> {
3984        ToolCallScope {
3985            base: self.control_base(),
3986            snapshot,
3987            call,
3988        }
3989    }
3990
3991    pub(crate) const fn tool_result(
3992        &self,
3993        snapshot: &'a Arc<StepSnapshot>,
3994        call: &'a ToolCall,
3995        disposition: CallDisposition,
3996        result: &'a ToolResult,
3997    ) -> ToolResultScope<'a> {
3998        ToolResultScope {
3999            base: self.control_base(),
4000            snapshot,
4001            call,
4002            disposition,
4003            result,
4004        }
4005    }
4006
4007    pub(crate) const fn after_tool_commit(
4008        &self,
4009        staged: &'a StagedTranscript,
4010        snapshot: &'a Arc<StepSnapshot>,
4011        result: &'a ToolResult,
4012    ) -> AfterToolCommitScope<'a> {
4013        AfterToolCommitScope {
4014            base: self.staged_base(staged),
4015            snapshot,
4016            result,
4017        }
4018    }
4019
4020    pub(crate) fn observer(&self, snapshot: Option<&'a Arc<StepSnapshot>>) -> ObserverScope<'_> {
4021        ObserverScope {
4022            base: self.read_base(),
4023            snapshot,
4024            audit_sink: &self.direct_audit,
4025        }
4026    }
4027
4028    pub(crate) const fn read(&self) -> ReadScope<'a> {
4029        ReadScope {
4030            base: self.read_base(),
4031        }
4032    }
4033}