Skip to main content

reef_core/runtime/
event.rs

1//! Owned outward events and the three strong-acceptance delivery seams.
2//!
3//! Ownership of the outward plane is settled by ADR-007: the loop produces
4//! events, the consumer decides the three strong seams, and a successful channel
5//! send is never treated as acceptance.
6//!
7//! This plane is an observable projection, not transcript serialization. Content
8//! is published before the corresponding transcript append linearizes and exposes
9//! renderable text plus provider item identity, not the complete
10//! [`SegmentExtensions`](crate::value::content::SegmentExtensions) or record-level
11//! provider data. Ordinary publication also fails closed after interruption, so a
12//! committed input may have no `InputAdmitted` projection. Current history comes
13//! from the Transcript; a composition layer that needs a byte-faithful resumable
14//! journal uses [`TranscriptHooks`](super::hook::TranscriptHooks) and restores a
15//! [`Snapshot`](crate::transcript::store::Snapshot).
16
17use std::error::Error;
18use std::fmt;
19use std::pin::Pin;
20use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
21use std::sync::{Arc, Mutex as SyncMutex};
22use std::task::{Context, Poll};
23
24use crate::cancel::Token;
25#[cfg(test)]
26use tokio::sync::Semaphore;
27use tokio::sync::{Mutex, Notify, mpsc};
28
29use crate::audit;
30use crate::redact;
31use crate::transcript::item;
32use crate::value::lifecycle::{Coord, Outcome};
33use crate::value::tool_call::ToolCall;
34
35/// The observable category of one outward event.
36///
37/// The set answers one question: what must a consumer be able to *distinguish*
38/// in order to render an agent or host a Run? A fact that can be read from an
39/// existing category plus its payload is deliberately not a category of its own,
40/// and a fact that belongs to a policy rather than to the runtime is not one
41/// either — see ADR-021 for the per-candidate reasoning.
42///
43/// Two absences are decisions rather than gaps:
44///
45/// - **There is no `GenerationStart`.** Hooks observe one
46///   ([`hook::LifecycleObservation::GenerationStart`]) because its payload is
47///   the frozen [`model::Request`] their own [`ModelHooks::before_model`] just
48///   finished editing. A consumer must not receive that value: it is the whole projected
49///   history plus the system instruction, which the consumer can already read
50///   from the transcript and which no event should copy onto a stream that may be
51///   logged. What a consumer needs — that a generation opened, and under which
52///   coordinate — is [`Kind::StepStart`], which the phase machine publishes
53///   exactly once per generation, and the [`Coord`] every later event carries.
54/// - **There is no interrupted category.** An interruption closes the outward
55///   lane before anything else can be published (C18/C20), so such a category
56///   could not have a production emitter — which is exactly the state this set
57///   was re-derived to leave. A consumer learns an interruption from its event
58///   stream closing and from [`run::Terminal`], which is observable only after
59///   cleanup has completed (C25).
60///
61/// One presence is worth naming for the same reason:
62///
63/// - **Input admission is a category, because nothing else could carry it.**
64///   An admitted input batch is the one kind of transcript record reef commits
65///   that the model did not produce, so it needs its own outward representation.
66///   That representation is best-effort under the fail-closed interruption rule,
67///   not an authoritative recovery record. A start or `NextTurn` batch opens a
68///   Turn; a `NextStep` batch
69///   is admitted at a Step boundary and does not. Deriving admission from
70///   [`Kind::TurnStart`] therefore fails in both directions — a Turn also opens
71///   without any admission at all, and a `NextStep` batch opens no Turn — and
72///   the record itself appears in no other category. See
73///   [`Kind::InputAdmitted`] and ADR-025.
74///
75/// [`hook::LifecycleObservation::GenerationStart`]: super::hook::LifecycleObservation::GenerationStart
76/// [`ModelHooks::before_model`]: super::hook::ModelHooks::before_model
77/// [`model::Request`]: super::model::Request
78/// [`run::Terminal`]: super::run::Terminal
79#[derive(Clone, Copy, Debug, Eq, PartialEq)]
80#[non_exhaustive]
81pub enum Kind {
82    /// Incremental answer text.
83    TextDelta,
84    /// Consolidated answer text.
85    Text,
86    /// Incremental model reasoning.
87    ThinkingDelta,
88    /// Consolidated model reasoning.
89    Thinking,
90    /// A turn began.
91    TurnStart,
92    /// A turn ended.
93    TurnEnd,
94    /// A step began.
95    StepStart,
96    /// A step ended.
97    StepEnd,
98    /// A real model generation ended.
99    GenerationEnd,
100    /// The model produced a complete tool call.
101    ToolCall,
102    /// A tool result was finalized.
103    ToolResult,
104    /// A recoverable extension degradation.
105    Error,
106    /// A non-model-visible audit fact.
107    Audit,
108    /// A policy requested a graceful run stop.
109    Stop,
110    /// An input batch was accepted and atomically recorded.
111    ///
112    /// Attempted once per batch, after the transcript append has committed and
113    /// before the Turn or Step that batch opens. So it is a statement of fact,
114    /// not a request: by the time a consumer sees it the record exists and
115    /// nothing can take it back. The converse is not promised: C18/C20 suppress
116    /// this ordinary event if interruption latches after commit. The Transcript
117    /// remains authoritative. [`Event::admitted_input`] carries the projected
118    /// items and which of the three routes they arrived by.
119    ///
120    /// A registration that wants a say runs at
121    /// [`InputHooks::before_input_admit`], which is the boundary *before* the
122    /// commit and the only place a batch can still be rewritten or refused.
123    ///
124    /// [`InputHooks::before_input_admit`]: super::hook::InputHooks::before_input_admit
125    InputAdmitted,
126    /// A claimed input batch was permanently refused.
127    ///
128    /// Only a mailbox batch can reach this. A refusal is one of the two terminal
129    /// states of a claimed batch — the other is a commit — so it is not
130    /// restored to the [`InputMailbox`], nothing will retry it, and the sender
131    /// would otherwise wait forever for an answer that is never coming.
132    /// [`Event::rejection_reason`] carries the reason the refusing registration
133    /// gave.
134    ///
135    /// [`InputMailbox`]: super::session::InputMailbox
136    InputRejected,
137}
138
139/// Which of reef's three input routes produced an admitted batch.
140///
141/// The routes are indistinguishable in the transcript — every one of them
142/// records an [`item::User`] and nothing in the record says which — so this is
143/// stated here or nowhere. A consumer that renders a conversation needs it: a
144/// continuation is the agent asking itself to keep going, and drawing it as
145/// something the human said would be wrong.
146#[derive(Clone, Copy, Debug, Eq, PartialEq)]
147#[non_exhaustive]
148pub enum InputOrigin {
149    /// The input [`Agent::start`] admitted, recorded before the loop began.
150    ///
151    /// This is the only route that can be rewritten before it is recorded, by a
152    /// [`RunHooks::prepare`](super::hook::RunHooks::prepare) registration, which
153    /// is why the batch is reported rather than assumed to be what the caller
154    /// passed.
155    ///
156    /// [`Agent::start`]: super::agent::Agent::start
157    Start,
158    /// A batch claimed from the Session's [`InputMailbox`].
159    ///
160    /// [`InputMailbox`]: super::session::InputMailbox
161    Mailbox,
162    /// Items a [`RunHooks::compose_continuation`](super::hook::RunHooks::compose_continuation)
163    /// registration composed to open another Turn.
164    Continuation,
165}
166
167/// One input batch exactly as it was recorded.
168///
169/// The items are the committed records and not the parts a caller submitted:
170/// [`RunHooks::prepare`](super::hook::RunHooks::prepare) and
171/// [`InputHooks::before_input_admit`](super::hook::InputHooks::before_input_admit)
172/// both rewrite input before it is recorded, so what the transcript holds is the
173/// only version worth reporting.
174#[derive(Clone, Debug)]
175pub struct AdmittedInput {
176    origin: InputOrigin,
177    items: Vec<item::Item>,
178}
179
180impl AdmittedInput {
181    /// Returns which route this batch arrived by.
182    #[must_use]
183    pub const fn origin(&self) -> InputOrigin {
184        self.origin
185    }
186
187    /// Returns the recorded items in transcript order.
188    #[must_use]
189    pub fn items(&self) -> &[item::Item] {
190        &self.items
191    }
192}
193
194/// One of the only three boundaries requiring an explicit consumer decision.
195#[derive(Clone, Copy, Debug, Eq, PartialEq)]
196#[non_exhaustive]
197pub enum DecisionPoint {
198    /// Before tool-hook policy and executor processing.
199    ToolCall,
200    /// Before later result or lifecycle publication.
201    ToolResult,
202    /// Before work following [`ToolHooks::after_tool_commit`](super::hook::ToolHooks::after_tool_commit).
203    AfterToolCommit,
204}
205
206/// A validated, nonempty opaque stop classification.
207#[derive(Clone, Debug, Eq, PartialEq)]
208pub struct StopCode(String);
209
210impl StopCode {
211    /// Validates an opaque stop code.
212    ///
213    /// # Errors
214    ///
215    /// [`ValidationError::EmptyStopCode`] if `code` has no characters. Core never
216    /// interprets the code, so an empty one would tell a consumer only that
217    /// something stopped the Run and refuse to say what — which is the one thing
218    /// this value exists to carry.
219    pub fn new(code: String) -> Result<Self, ValidationError> {
220        if code.is_empty() {
221            return Err(ValidationError::EmptyStopCode);
222        }
223        Ok(Self(code))
224    }
225
226    /// Returns the opaque code.
227    #[must_use]
228    pub fn as_str(&self) -> &str {
229        &self.0
230    }
231}
232
233/// A stable outward-event validation failure.
234#[derive(Clone, Copy, Debug, Eq, PartialEq)]
235#[non_exhaustive]
236pub enum ValidationError {
237    /// An audit kind was empty.
238    EmptyAuditKind,
239    /// A tool-call identity was empty.
240    EmptyToolCallId,
241    /// A tool name was empty.
242    EmptyToolName,
243    /// A stop code was empty.
244    EmptyStopCode,
245    /// The event category and its private payload disagreed.
246    PayloadMismatch,
247    /// A private producer selected a decision point inconsistent with the event.
248    InvalidDecisionPoint,
249}
250
251impl fmt::Display for ValidationError {
252    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
253        formatter.write_str(match self {
254            Self::EmptyAuditKind => "event audit kind must be non-empty",
255            Self::EmptyToolCallId => "event tool-call identity must be non-empty",
256            Self::EmptyToolName => "event tool name must be non-empty",
257            Self::EmptyStopCode => "event stop code must be non-empty",
258            Self::PayloadMismatch => "event category and payload do not match",
259            Self::InvalidDecisionPoint => "event used an invalid decision point",
260        })
261    }
262}
263
264impl Error for ValidationError {}
265
266#[derive(Clone)]
267enum Payload {
268    Text(String),
269    Lifecycle(Option<Outcome>),
270    ToolCall(ToolCall),
271    ToolResult(item::ToolResult),
272    Audit(audit::Event),
273    Error(Arc<dyn Error + Send + Sync>),
274    Stop(StopCode),
275    Input(AdmittedInput),
276    Rejection(String),
277}
278
279impl fmt::Debug for Payload {
280    /// Sizes the one variant that carries model text and flattens the error.
281    ///
282    /// `Text` is answer or reasoning content on its way to a consumer. `Error`
283    /// holds an arbitrary third-party failure whose own `Debug` this crate does
284    /// not control, so it is rendered through `Display`, which is the operator
285    /// diagnostic the type is for. Every other variant already redacts itself.
286    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
287        match self {
288            Self::Text(text) => formatter
289                .debug_tuple("Text")
290                .field(&redact::Bytes(text.len()))
291                .finish(),
292            Self::Lifecycle(outcome) => formatter.debug_tuple("Lifecycle").field(outcome).finish(),
293            Self::ToolCall(call) => formatter.debug_tuple("ToolCall").field(call).finish(),
294            Self::ToolResult(result) => formatter.debug_tuple("ToolResult").field(result).finish(),
295            Self::Audit(audit) => formatter.debug_tuple("Audit").field(audit).finish(),
296            Self::Error(error) => formatter
297                .debug_tuple("Error")
298                .field(&error.to_string())
299                .finish(),
300            Self::Stop(code) => formatter.debug_tuple("Stop").field(code).finish(),
301            // `Item` redacts itself, so the batch prints its own way; the reason
302            // is a diagnostic a registration wrote for an operator to read.
303            Self::Input(input) => formatter.debug_tuple("Input").field(input).finish(),
304            Self::Rejection(reason) => formatter.debug_tuple("Rejection").field(reason).finish(),
305        }
306    }
307}
308
309/// An immutable outward event; loop-owned variants have no public constructors.
310#[derive(Clone, Debug)]
311pub struct Event {
312    kind: Kind,
313    coord: Option<Coord>,
314    item_id: Option<String>,
315    payload: Payload,
316}
317
318impl Event {
319    /// Constructs a validated extension-produced audit event.
320    ///
321    /// # Errors
322    ///
323    /// [`ValidationError::EmptyAuditKind`] if the audit fact does not name a
324    /// kind. An audit fact is classified by its kind, and an unclassifiable one
325    /// cannot be filtered, routed, or counted by whoever consumes the stream.
326    ///
327    /// This is the only construction check on the two event kinds an extension
328    /// may build. The remaining [`ValidationError`] variants describe private
329    /// producer mistakes and cannot be reached from here.
330    pub fn from_audit(audit: audit::Event) -> Result<Self, ValidationError> {
331        if audit.kind().is_empty() {
332            return Err(ValidationError::EmptyAuditKind);
333        }
334        Ok(Self {
335            kind: Kind::Audit,
336            coord: None,
337            item_id: None,
338            payload: Payload::Audit(audit),
339        })
340    }
341
342    /// Constructs a validated extension-produced non-fatal error event.
343    #[must_use]
344    pub fn from_error(error: Arc<dyn Error + Send + Sync>) -> Self {
345        Self {
346            kind: Kind::Error,
347            coord: None,
348            item_id: None,
349            payload: Payload::Error(error),
350        }
351    }
352
353    /// Returns the event category.
354    #[must_use]
355    pub const fn kind(&self) -> Kind {
356        self.kind
357    }
358
359    /// Returns the runtime-stamped coordinate, when applicable.
360    #[must_use]
361    pub const fn coord(&self) -> Option<&Coord> {
362        self.coord.as_ref()
363    }
364
365    /// Returns the provider's identity for the content item this event is part of.
366    ///
367    /// [`coord`](Self::coord) says where the event sits in reef's own
368    /// Run/Turn/Step structure; this says which of the provider's items it
369    /// belongs to. A single generation can produce several — an answer alongside
370    /// reasoning, or several separate answer items — and they interleave, so a
371    /// consumer rendering incrementally needs this to put each fragment under
372    /// the right heading rather than concatenating everything a Step emitted.
373    ///
374    /// Present on all four content kinds, and the same string on both sides: a
375    /// delta reports the identity of the
376    /// [`model::Event::ContentDelta`](crate::runtime::model::Event::ContentDelta)
377    /// it projects, the consolidated event reports the one the committed
378    /// [`Segment`](crate::value::content::Segment) kept, and
379    /// [`model::StreamGrammar`](crate::runtime::model::StreamGrammar) refuses a
380    /// stream whose final does not close the identity its deltas opened. So
381    /// grouping deltas by this value and then matching the consolidated event to
382    /// the same group is sound, and it stays sound for a provider that streams
383    /// no deltas at all.
384    ///
385    /// `None` on every other kind, and on a content event whose segment no
386    /// provider produced — one an
387    /// [`OnAfterModel`](crate::runtime::hook::ModelHooks::after_model)
388    /// registration composed, for instance. A registration that replaces
389    /// assistant content decides its identity too, including deciding it has
390    /// none, and what reaches a consumer here is always the identity of the
391    /// content it is attached to rather than of the content the provider
392    /// originally sent.
393    #[must_use]
394    pub fn item_id(&self) -> Option<&str> {
395        self.item_id.as_deref()
396    }
397
398    /// Returns text carried by a text or thinking event.
399    #[must_use]
400    pub fn text(&self) -> Option<&str> {
401        match &self.payload {
402            Payload::Text(text) => Some(text),
403            _ => None,
404        }
405    }
406
407    /// Returns a tool-call payload.
408    #[must_use]
409    pub const fn tool_call(&self) -> Option<&ToolCall> {
410        match &self.payload {
411            Payload::ToolCall(call) => Some(call),
412            _ => None,
413        }
414    }
415
416    /// Returns a tool-result payload.
417    #[must_use]
418    pub const fn tool_result(&self) -> Option<&item::ToolResult> {
419        match &self.payload {
420            Payload::ToolResult(result) => Some(result),
421            _ => None,
422        }
423    }
424
425    /// Returns the committed batch an [`InputAdmitted`](Kind::InputAdmitted) event projects.
426    ///
427    /// Never empty: an empty batch is refused before it can be recorded, because
428    /// recording one would assert that somebody said nothing.
429    #[must_use]
430    pub const fn admitted_input(&self) -> Option<&AdmittedInput> {
431        match &self.payload {
432            Payload::Input(input) => Some(input),
433            _ => None,
434        }
435    }
436
437    /// Returns why an [`InputRejected`](Kind::InputRejected) event refused a batch.
438    ///
439    /// Never empty: a rejection with no reason is a hook defect that fails the
440    /// Run, because the reason is the only thing the refusal leaves behind.
441    #[must_use]
442    pub fn rejection_reason(&self) -> Option<&str> {
443        match &self.payload {
444            Payload::Rejection(reason) => Some(reason),
445            _ => None,
446        }
447    }
448
449    /// Returns a lifecycle end outcome.
450    #[must_use]
451    pub const fn outcome(&self) -> Option<Outcome> {
452        match self.payload {
453            Payload::Lifecycle(outcome) => outcome,
454            _ => None,
455        }
456    }
457
458    /// Returns an audit payload.
459    #[must_use]
460    pub const fn as_audit(&self) -> Option<&audit::Event> {
461        match &self.payload {
462            Payload::Audit(audit) => Some(audit),
463            _ => None,
464        }
465    }
466
467    /// Returns a recoverable error payload.
468    #[must_use]
469    pub fn as_error(&self) -> Option<&(dyn Error + Send + Sync)> {
470        match &self.payload {
471            Payload::Error(error) => Some(error.as_ref()),
472            _ => None,
473        }
474    }
475
476    /// Returns the opaque stop classification.
477    #[must_use]
478    pub const fn stop_code(&self) -> Option<&StopCode> {
479        match &self.payload {
480            Payload::Stop(code) => Some(code),
481            _ => None,
482        }
483    }
484
485    const fn driver_text(kind: Kind, text: String, coord: Coord, item_id: Option<String>) -> Self {
486        Self {
487            kind,
488            coord: Some(coord),
489            item_id,
490            payload: Payload::Text(text),
491        }
492    }
493
494    const fn driver_lifecycle(kind: Kind, outcome: Option<Outcome>, coord: Coord) -> Self {
495        Self {
496            kind,
497            coord: Some(coord),
498            item_id: None,
499            payload: Payload::Lifecycle(outcome),
500        }
501    }
502
503    const fn driver_tool_call(call: ToolCall, coord: Coord) -> Self {
504        Self {
505            kind: Kind::ToolCall,
506            coord: Some(coord),
507            item_id: None,
508            payload: Payload::ToolCall(call),
509        }
510    }
511
512    const fn driver_tool_result(result: item::ToolResult, coord: Coord) -> Self {
513        Self {
514            kind: Kind::ToolResult,
515            coord: Some(coord),
516            item_id: None,
517            payload: Payload::ToolResult(result),
518        }
519    }
520
521    const fn driver_stop(code: StopCode, coord: Coord) -> Self {
522        Self {
523            kind: Kind::Stop,
524            coord: Some(coord),
525            item_id: None,
526            payload: Payload::Stop(code),
527        }
528    }
529
530    const fn driver_input_admitted(
531        origin: InputOrigin,
532        items: Vec<item::Item>,
533        coord: Coord,
534    ) -> Self {
535        Self {
536            kind: Kind::InputAdmitted,
537            coord: Some(coord),
538            item_id: None,
539            payload: Payload::Input(AdmittedInput { origin, items }),
540        }
541    }
542
543    const fn driver_input_rejected(reason: String, coord: Coord) -> Self {
544        Self {
545            kind: Kind::InputRejected,
546            coord: Some(coord),
547            item_id: None,
548            payload: Payload::Rejection(reason),
549        }
550    }
551
552    fn validate(&self, decision_point: Option<DecisionPoint>) -> Result<(), ValidationError> {
553        if !payload_matches(self.kind, &self.payload) {
554            return Err(ValidationError::PayloadMismatch);
555        }
556        match &self.payload {
557            Payload::ToolCall(call) if call.id().as_str().is_empty() => {
558                Err(ValidationError::EmptyToolCallId)
559            }
560            Payload::ToolCall(call) if call.name().as_str().is_empty() => {
561                Err(ValidationError::EmptyToolName)
562            }
563            Payload::ToolResult(result) if result.call_id().as_str().is_empty() => {
564                Err(ValidationError::EmptyToolCallId)
565            }
566            Payload::ToolResult(result) if result.tool_name().as_str().is_empty() => {
567                Err(ValidationError::EmptyToolName)
568            }
569            Payload::Audit(audit) if audit.kind().is_empty() => {
570                Err(ValidationError::EmptyAuditKind)
571            }
572            Payload::Stop(code) if code.as_str().is_empty() => Err(ValidationError::EmptyStopCode),
573            _ if decision_point != expected_decision_point(self.kind, decision_point) => {
574                Err(ValidationError::InvalidDecisionPoint)
575            }
576            _ => Ok(()),
577        }
578    }
579}
580
581const fn payload_matches(kind: Kind, payload: &Payload) -> bool {
582    matches!(
583        (kind, payload),
584        (
585            Kind::TextDelta | Kind::Text | Kind::ThinkingDelta | Kind::Thinking,
586            Payload::Text(_)
587        ) | (Kind::TurnStart | Kind::StepStart, Payload::Lifecycle(None))
588            | (
589                Kind::TurnEnd | Kind::StepEnd | Kind::GenerationEnd,
590                Payload::Lifecycle(Some(_))
591            )
592            | (Kind::ToolCall, Payload::ToolCall(_))
593            | (Kind::ToolResult, Payload::ToolResult(_))
594            | (Kind::Error, Payload::Error(_))
595            | (Kind::Audit, Payload::Audit(_))
596            | (Kind::Stop, Payload::Stop(_))
597            | (Kind::InputAdmitted, Payload::Input(_))
598            | (Kind::InputRejected, Payload::Rejection(_))
599    )
600}
601
602fn expected_decision_point(kind: Kind, requested: Option<DecisionPoint>) -> Option<DecisionPoint> {
603    match kind {
604        Kind::ToolCall => Some(DecisionPoint::ToolCall),
605        Kind::ToolResult => Some(DecisionPoint::ToolResult),
606        Kind::Audit | Kind::Error if requested == Some(DecisionPoint::AfterToolCommit) => requested,
607        _ => None,
608    }
609}
610
611/// A delivery decision was already completed.
612#[derive(Clone, Copy, Debug, Eq, PartialEq)]
613#[non_exhaustive]
614pub enum DecisionError {
615    /// This ordinary event has no decision barrier.
616    NotRequired,
617    /// Another decision or cancellation already won.
618    AlreadyDecided,
619}
620
621impl fmt::Display for DecisionError {
622    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
623        formatter.write_str(match self {
624            Self::NotRequired => "event delivery does not require acceptance",
625            Self::AlreadyDecided => "event delivery was already decided",
626        })
627    }
628}
629
630impl Error for DecisionError {}
631
632const PENDING: u8 = 0;
633const ACCEPTED: u8 = 1;
634const REJECTED: u8 = 2;
635const CANCELED: u8 = 3;
636
637struct Decision {
638    value: AtomicU8,
639    changed: Notify,
640    /// The composite interruption token this wait must wake on.
641    cancel: Token,
642    /// The run's shared single linearization point for its nonfatal cause.
643    ///
644    /// The composite token alone cannot distinguish parent cancellation from the
645    /// child cancellation caused by this run's own `request_stop`/Drop, so every
646    /// interruption value is selected here instead of from the token.
647    nonfatal: Arc<NonfatalCause>,
648    #[cfg(test)]
649    after_pending_check: SyncMutex<Option<WaitBarriers>>,
650}
651
652#[cfg(test)]
653struct WaitBarriers {
654    checked: Arc<std::sync::Barrier>,
655    resume: Arc<std::sync::Barrier>,
656}
657
658impl Decision {
659    fn decide(&self, value: u8) -> Result<(), DecisionError> {
660        self.value
661            .compare_exchange(PENDING, value, Ordering::AcqRel, Ordering::Acquire)
662            .map(|_| self.changed.notify_waiters())
663            .map_err(|_| DecisionError::AlreadyDecided)
664    }
665
666    fn decide_consumer(&self, value: u8) -> Result<(), DecisionError> {
667        if self.cancel.is_cancelled() {
668            let _already_decided = self.decide(self.nonfatal.interrupted_decision());
669            Err(DecisionError::AlreadyDecided)
670        } else {
671            self.decide(value)
672        }
673    }
674
675    fn abandon(&self) -> Result<(), DecisionError> {
676        let value = if self.cancel.is_cancelled() {
677            self.nonfatal.interrupted_decision()
678        } else {
679            REJECTED
680        };
681        self.decide(value)
682    }
683
684    async fn wait(&self) -> StrongDecision {
685        loop {
686            let changed = self.changed.notified();
687            tokio::pin!(changed);
688            let _already_ready = changed.as_mut().enable();
689            match self.value.load(Ordering::Acquire) {
690                ACCEPTED => return StrongDecision::Accepted,
691                REJECTED => return StrongDecision::Rejected,
692                CANCELED => return StrongDecision::Cancelled,
693                _ => {
694                    #[cfg(test)]
695                    self.pause_after_pending_check();
696                    tokio::select! {
697                        biased;
698                        () = self.cancel.cancelled() => {
699                            let _already_decided =
700                                self.decide(self.nonfatal.interrupted_decision());
701                        }
702                        () = &mut changed => {}
703                    }
704                }
705            }
706        }
707    }
708
709    #[cfg(test)]
710    fn pause_after_pending_check(&self) {
711        let barriers = self
712            .after_pending_check
713            .lock()
714            .expect("event wait barrier lock poisoned")
715            .take();
716        if let Some(barriers) = barriers {
717            barriers.checked.wait();
718            barriers.resume.wait();
719        }
720    }
721}
722
723/// One event and, at a strong decision point, its exactly-once decision guard.
724///
725/// Most deliveries are ordinary transport: read the [`event`](Delivery::event)
726/// and move on. Three decision points are rendezvous the Run is blocked on, and
727/// it does not proceed until this delivery is [`accept`](Delivery::accept)ed or
728/// [`reject`](Delivery::reject)ed. Dropping one undecided rejects it.
729///
730/// Do not infer this from [`Event::kind`].
731/// [`AfterToolCommit`](DecisionPoint::AfterToolCommit) can accompany either an
732/// [`Audit`](Kind::Audit) or [`Error`](Kind::Error) event, and either kind can
733/// also be an ordinary delivery. Always call
734/// [`decision_point`](Delivery::decision_point) for each delivery; that makes the
735/// whole acceptance protocol one line:
736///
737/// ```
738/// # use reef_core::runtime::event;
739/// # fn handle(delivery: &event::Delivery) -> Result<(), event::DecisionError> {
740/// if delivery.decision_point().is_some() {
741///     delivery.accept()?;
742/// }
743/// # Ok(())
744/// # }
745/// ```
746///
747/// A consumer that means to refuse further work — a policy that says no, a host
748/// shutting down — calls [`reject`](Delivery::reject) instead. At
749/// [`ToolCall`](DecisionPoint::ToolCall), rejection prevents tool-hook and executor
750/// processing. At [`ToolResult`](DecisionPoint::ToolResult) or
751/// [`AfterToolCommit`](DecisionPoint::AfterToolCommit), execution and commit have
752/// already happened; rejection does not undo those facts and only prevents later
753/// work.
754pub struct Delivery {
755    event: Event,
756    decision_point: Option<DecisionPoint>,
757    decision: Option<Arc<Decision>>,
758}
759
760impl fmt::Debug for Delivery {
761    /// Shows the event, the decision point, and whether a decision is owed.
762    ///
763    /// The decision guard is reported by presence rather than by state: reading
764    /// its state would mean loading the very atomic whose exactly-once
765    /// transition the guard exists to serialise, and a formatter has no business
766    /// participating in that handshake.
767    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
768        formatter
769            .debug_struct("Delivery")
770            .field("event", &self.event)
771            .field("decision_point", &self.decision_point)
772            .field("decision", &redact::Presence(self.decision.is_some()))
773            .finish()
774    }
775}
776
777impl Delivery {
778    /// Returns the immutable event.
779    #[must_use]
780    pub const fn event(&self) -> &Event {
781        &self.event
782    }
783
784    /// Returns the strong decision point, or `None` for ordinary transport delivery.
785    #[must_use]
786    pub const fn decision_point(&self) -> Option<DecisionPoint> {
787        self.decision_point
788    }
789
790    /// Accepts this strong boundary exactly once.
791    ///
792    /// # Errors
793    ///
794    /// - [`DecisionError::NotRequired`] if this is ordinary transport delivery
795    ///   rather than one of the three strong seams. Check
796    ///   [`decision_point`](Self::decision_point) to tell them apart; nothing is owed
797    ///   for an ordinary delivery and nothing happens if it is dropped undecided.
798    /// - [`DecisionError::AlreadyDecided`] if this delivery has already been
799    ///   decided, or if cancellation resolved it first. A cancelled Run's
800    ///   deliveries report this even on a first call, because acceptance would
801    ///   authorize work the Run is already unwinding out of — so a consumer
802    ///   cannot treat this variant as "somebody else said yes".
803    ///
804    /// Either way the governed work does not proceed on this call's authority,
805    /// and the decision that did win is not displaced.
806    pub fn accept(&self) -> Result<(), DecisionError> {
807        self.decision
808            .as_ref()
809            .ok_or(DecisionError::NotRequired)?
810            .decide_consumer(ACCEPTED)
811    }
812
813    /// Rejects this strong boundary exactly once.
814    ///
815    /// At [`DecisionPoint::ToolCall`], rejection prevents subsequent tool-hook and
816    /// executor processing. At [`DecisionPoint::ToolResult`] or
817    /// [`DecisionPoint::AfterToolCommit`], the tool has already executed and its
818    /// result has already been committed. Rejection does not undo those facts; it
819    /// only prevents later work.
820    ///
821    /// # Errors
822    ///
823    /// [`DecisionError::NotRequired`] if this is ordinary transport delivery, or
824    /// [`DecisionError::AlreadyDecided`] if a decision or a cancellation already
825    /// won — the same two conditions [`accept`](Self::accept) reports, for the
826    /// same reasons.
827    ///
828    /// Neither is a reason to retry. `NotRequired` means no decision was owed;
829    /// `AlreadyDecided` means the winning decision remains in force, and this
830    /// error does not reveal whether it accepted, rejected, or cancelled the
831    /// boundary.
832    pub fn reject(&self) -> Result<(), DecisionError> {
833        self.decision
834            .as_ref()
835            .ok_or(DecisionError::NotRequired)?
836            .decide_consumer(REJECTED)
837    }
838}
839
840impl Drop for Delivery {
841    fn drop(&mut self) {
842        if let Some(decision) = &self.decision {
843            let _already_decided = decision.abandon();
844        }
845    }
846}
847
848/// The unique consumer of a run's outward events.
849///
850/// There is exactly one of these per Run. An observable start receives it atomically
851/// from [`Agent::start_observed`](crate::runtime::agent::Agent::start_observed); the
852/// compatibility [`Run::take_events`](crate::runtime::run::Run::take_events) path hands
853/// it over once after `Agent::start`. Draining it to `None` is how a consumer knows
854/// the Run's outward lane is closed; the
855/// [`Terminal`](crate::runtime::run::Terminal) is then already resolved or about
856/// to be, and [`Run::wait`](crate::runtime::run::Run::wait) produces it.
857///
858/// Dropping this stream asks the Run to stop. That is deliberate — a consumer
859/// that has stopped listening is stating it wants nothing further — so a Run you
860/// mean to finish should be drained rather than abandoned.
861///
862/// ```
863/// # use reef_core::runtime::event;
864/// # async fn drain(events: &mut event::Stream) -> Vec<event::Kind> {
865/// let mut seen = Vec::new();
866/// while let Some(delivery) = events.recv().await {
867///     seen.push(delivery.event().kind());
868///     // Three decision points are rendezvous; do not infer them from Event::kind.
869///     // AfterToolCommit can accompany Audit or Error. Always ask the delivery.
870///     if delivery.decision_point().is_some() {
871///         delivery.accept().expect("a fresh strong delivery accepts once");
872///     }
873/// }
874/// seen
875/// # }
876/// ```
877///
878/// It also implements [`futures_core::Stream`], so a consumer already built
879/// around stream combinators can use it directly.
880pub struct Stream {
881    receiver: mpsc::UnboundedReceiver<Delivery>,
882    control: Arc<Control>,
883}
884
885impl fmt::Debug for Stream {
886    /// Reports whether the run's outward lane has latched a fatal violation.
887    ///
888    /// The load is relaxed on purpose: this is a diagnostic read, and ordering
889    /// it against the producer would let formatting influence the very
890    /// termination sequence it is trying to describe.
891    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
892        formatter
893            .debug_struct("Stream")
894            .field("fatal", &self.control.fatal.load(Ordering::Relaxed))
895            .finish()
896    }
897}
898
899impl Stream {
900    /// Receives the next delivery.
901    pub async fn recv(&mut self) -> Option<Delivery> {
902        self.receiver.recv().await
903    }
904}
905
906impl futures_core::Stream for Stream {
907    type Item = Delivery;
908
909    fn poll_next(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
910        self.receiver.poll_recv(context)
911    }
912}
913
914impl Drop for Stream {
915    fn drop(&mut self) {
916        self.control.request_stop();
917        self.receiver.close();
918    }
919}
920
921#[derive(Clone, Copy, Debug, Eq, PartialEq)]
922pub(crate) enum DeliveryOutcome {
923    Delivered,
924    Accepted,
925    Rejected,
926}
927
928/// The precise decision at one of the three runtime-owned strong seams.
929///
930/// This stays crate-private so the outward delivery API remains unchanged.
931#[derive(Clone, Copy, Debug, Eq, PartialEq)]
932pub(crate) enum StrongDecision {
933    Accepted,
934    Rejected,
935    Cancelled,
936}
937
938impl From<StrongDecision> for DeliveryOutcome {
939    fn from(decision: StrongDecision) -> Self {
940        match decision {
941            StrongDecision::Accepted => Self::Accepted,
942            StrongDecision::Rejected | StrongDecision::Cancelled => Self::Rejected,
943        }
944    }
945}
946
947#[derive(Clone, Copy, Debug, Eq, PartialEq)]
948struct DeliveryResolution {
949    outward: DeliveryOutcome,
950    strong: Option<StrongDecision>,
951}
952
953impl DeliveryResolution {
954    const fn ordinary(outward: DeliveryOutcome) -> Self {
955        Self {
956            outward,
957            strong: None,
958        }
959    }
960
961    fn strong(decision: StrongDecision) -> Self {
962        Self {
963            outward: decision.into(),
964            strong: Some(decision),
965        }
966    }
967}
968
969#[derive(Clone, Copy, Debug, Eq, PartialEq)]
970pub(crate) enum TerminalIntent {
971    Running,
972    Stopped,
973    Cancelled,
974    Failed,
975}
976
977impl TerminalIntent {
978    #[cfg_attr(not(test), expect(dead_code, reason = "reached only by tests so far"))]
979    pub(crate) const fn outcome(self) -> Option<Outcome> {
980        match self {
981            Self::Running => None,
982            Self::Stopped => Some(Outcome::Stopped),
983            Self::Cancelled => Some(Outcome::Cancelled),
984            Self::Failed => Some(Outcome::Failed),
985        }
986    }
987}
988
989/// No nonfatal terminal cause has been frozen yet.
990const NONFATAL_NONE: u8 = 0;
991/// A normal `request_stop`/`Stream` Drop won the linearization point.
992const NONFATAL_STOPPED: u8 = 1;
993/// Real parent cancellation won the linearization point.
994const NONFATAL_CANCELED: u8 = 2;
995
996/// The run's single linearization point for its one nonfatal terminal cause.
997///
998/// `Stopped` and `Cancelled` are two *causes* of the same interruption, so they
999/// cannot be derived independently from the cancellation tree: the child token
1000/// this run cancels for its own normal stop is indistinguishable from parent
1001/// cancellation once observed. Only the caller-owned `parent` token — which this
1002/// run never cancels — separates the two, and the first observer to resolve the
1003/// cause freezes it here for every later observer.
1004///
1005/// The frozen cause is never rewritten. A fatal failure is a strictly higher,
1006/// independent latch on [`Control`], so it can still upgrade the terminal in
1007/// either order without this cause ever being lost or reinterpreted.
1008struct NonfatalCause {
1009    /// The caller-owned token whose cancellation is real parent cancellation.
1010    parent: Token,
1011    cause: SyncMutex<u8>,
1012}
1013
1014impl NonfatalCause {
1015    /// Resolves the frozen nonfatal cause, freezing it on first resolution.
1016    ///
1017    /// `normal_stop` is `true` only for `request_stop`/`Stream` Drop, which
1018    /// is itself a stop request. Every other caller merely observes: it can
1019    /// freeze `Cancelled` from an already cancelled parent, but never invents a
1020    /// stop. Reading `parent` inside the critical section is what keeps a
1021    /// stop-induced child cancellation from ever being reported as `Cancelled`,
1022    /// and what makes a parent cancellation that already won outrank a later
1023    /// normal stop.
1024    fn freeze(&self, normal_stop: bool) -> u8 {
1025        let mut cause = self
1026            .cause
1027            .lock()
1028            .expect("event nonfatal cause lock poisoned");
1029        if *cause == NONFATAL_NONE {
1030            if self.parent.is_cancelled() {
1031                *cause = NONFATAL_CANCELED;
1032            } else if normal_stop {
1033                *cause = NONFATAL_STOPPED;
1034            }
1035        }
1036        *cause
1037    }
1038
1039    /// Reads the frozen cause without resolving or freezing anything.
1040    #[cfg(test)]
1041    fn frozen(&self) -> u8 {
1042        *self
1043            .cause
1044            .lock()
1045            .expect("event nonfatal cause lock poisoned")
1046    }
1047
1048    /// Selects the strong decision point value an interrupted delivery must linearize to.
1049    fn interrupted_decision(&self) -> u8 {
1050        if self.freeze(false) == NONFATAL_CANCELED {
1051            CANCELED
1052        } else {
1053            REJECTED
1054        }
1055    }
1056}
1057
1058#[cfg(test)]
1059#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1060pub(crate) enum FreezePoint {
1061    Stop,
1062    Fatal,
1063}
1064
1065#[cfg(test)]
1066struct TestFreezePause {
1067    point: FreezePoint,
1068    reached: Arc<std::sync::Barrier>,
1069    resume: Arc<std::sync::Barrier>,
1070}
1071
1072#[cfg(test)]
1073struct TestFinalConfirmPause {
1074    reached: Semaphore,
1075    resume: Semaphore,
1076}
1077
1078/// One held tool emission, announced synchronously and released asynchronously.
1079///
1080/// The waiter is a synchronous tool mapper on the loop's own runtime thread, so
1081/// the announcement cannot be a future: nothing would poll it.
1082#[cfg(test)]
1083struct TestEmitPause {
1084    reached: std::sync::mpsc::Sender<()>,
1085    resume: Semaphore,
1086}
1087
1088struct Control {
1089    /// The one frozen nonfatal cause, shared with every strong decision.
1090    nonfatal: Arc<NonfatalCause>,
1091    fatal: AtomicBool,
1092    fatal_event: SyncMutex<Option<ValidationError>>,
1093    stop_emitted: AtomicBool,
1094    pending: SyncMutex<Option<Arc<Decision>>>,
1095    /// The composite interruption token cancelled by parent cancellation and by
1096    /// this run's own normal stop.
1097    cancel: Token,
1098    interruption: Token,
1099    #[cfg(test)]
1100    before_reject_pause: SyncMutex<Option<TestFreezePause>>,
1101    #[cfg(test)]
1102    after_final_confirm_pause: SyncMutex<Option<Arc<TestFinalConfirmPause>>>,
1103}
1104
1105/// Abandons and clears the producer's strong-decision slot on completion or future Drop.
1106///
1107/// The serialized producer owns at most one decision. Keeping that registration
1108/// behind an RAII guard prevents a dropped `Driver::run` future from leaving a
1109/// stale strong decision reachable through `Control` after its delivery owner has
1110/// already been unwound.
1111struct PendingDecision<'a> {
1112    control: &'a Control,
1113    decision: Arc<Decision>,
1114}
1115
1116impl Drop for PendingDecision<'_> {
1117    fn drop(&mut self) {
1118        // The producer future owns the live side of this handshake. If that
1119        // future is dropped, terminate the decision before making the slot
1120        // available to a successor; otherwise an already-delivered guard could
1121        // still accept work whose owner no longer exists.
1122        let _already_decided = self.decision.abandon();
1123        self.control.clear(&self.decision);
1124    }
1125}
1126
1127impl Control {
1128    fn intent(&self) -> TerminalIntent {
1129        // Fatal is an independent, strictly higher latch, so it wins in either
1130        // interleaving order without ever consulting the nonfatal cause.
1131        if self.fatal.load(Ordering::Acquire) {
1132            return TerminalIntent::Failed;
1133        }
1134        // Observing only: this can freeze Cancelled from an already cancelled
1135        // parent, but it never invents a stop.
1136        match self.nonfatal.freeze(false) {
1137            NONFATAL_CANCELED => TerminalIntent::Cancelled,
1138            NONFATAL_STOPPED => TerminalIntent::Stopped,
1139            _ => TerminalIntent::Running,
1140        }
1141    }
1142
1143    fn strong_interruption(&self) -> Option<StrongDecision> {
1144        if self.fatal.load(Ordering::Acquire) {
1145            return Some(StrongDecision::Rejected);
1146        }
1147        match self.nonfatal.freeze(false) {
1148            NONFATAL_CANCELED => Some(StrongDecision::Cancelled),
1149            NONFATAL_STOPPED => Some(StrongDecision::Rejected),
1150            _ => None,
1151        }
1152    }
1153
1154    /// Linearizes the decision exposed to the strong decision point caller.
1155    ///
1156    /// A consumer acceptance is only an internal handshake result. Stop or fatal
1157    /// control may freeze after that CAS but before `reject_pending` reaches it;
1158    /// consulting this shared control point prevents such an internal acceptance
1159    /// from authorizing tool execution. Rejection and cancellation already encode
1160    /// a terminal consumer/control choice and are preserved.
1161    fn final_confirm_strong(&self, decision: StrongDecision) -> StrongDecision {
1162        if decision == StrongDecision::Accepted {
1163            self.strong_interruption().unwrap_or(decision)
1164        } else {
1165            decision
1166        }
1167    }
1168
1169    #[cfg(test)]
1170    fn pause_before_reject(&self, point: FreezePoint) {
1171        let pause = {
1172            let mut slot = self
1173                .before_reject_pause
1174                .lock()
1175                .expect("event freeze pause lock poisoned");
1176            if slot.as_ref().is_some_and(|pause| pause.point == point) {
1177                slot.take()
1178            } else {
1179                None
1180            }
1181        };
1182        if let Some(pause) = pause {
1183            pause.reached.wait();
1184            pause.resume.wait();
1185        }
1186    }
1187
1188    #[cfg(test)]
1189    async fn pause_after_final_confirm(&self) {
1190        let pause = self
1191            .after_final_confirm_pause
1192            .lock()
1193            .expect("event final-confirm pause lock poisoned")
1194            .take();
1195        if let Some(pause) = pause {
1196            pause.reached.add_permits(1);
1197            pause
1198                .resume
1199                .acquire()
1200                .await
1201                .expect("event final-confirm pause remains open")
1202                .forget();
1203        }
1204    }
1205
1206    /// Reports whether an interruption is already frozen for this run.
1207    ///
1208    /// This is the shared gate for registration and ordinary emission: both must
1209    /// fail closed once any nonfatal cause or fatal failure has been latched.
1210    fn interrupted(&self) -> bool {
1211        self.fatal.load(Ordering::Acquire) || self.nonfatal.freeze(false) != NONFATAL_NONE
1212    }
1213
1214    fn register(&self, decision: &Arc<Decision>) {
1215        let mut pending = self.pending.lock().expect("event pending lock poisoned");
1216        if self.interrupted() {
1217            let _already_decided = decision.decide(self.nonfatal.interrupted_decision());
1218        } else {
1219            *pending = Some(decision.clone());
1220        }
1221    }
1222
1223    fn clear(&self, decision: &Arc<Decision>) {
1224        let mut pending = self.pending.lock().expect("event pending lock poisoned");
1225        if pending
1226            .as_ref()
1227            .is_some_and(|current| Arc::ptr_eq(current, decision))
1228        {
1229            pending.take();
1230        }
1231    }
1232
1233    /// Terminates the registered strong decision with the frozen nonfatal cause.
1234    fn reject_pending(&self) {
1235        let decided = self.nonfatal.interrupted_decision();
1236        if let Some(decision) = self
1237            .pending
1238            .lock()
1239            .expect("event pending lock poisoned")
1240            .take()
1241        {
1242            let _already_decided = decision.decide(decided);
1243        }
1244    }
1245
1246    /// Freezes a normal stop cause, unless a parent cancellation already won.
1247    fn latch_stop(&self) {
1248        let _cause = self.nonfatal.freeze(true);
1249        #[cfg(test)]
1250        self.pause_before_reject(FreezePoint::Stop);
1251        self.reject_pending();
1252        self.interruption.cancel();
1253    }
1254
1255    fn request_stop(&self) {
1256        self.latch_stop();
1257        // The composite token is cancelled only after the cause is frozen, so no
1258        // observer can mistake this run's own stop for parent cancellation.
1259        self.cancel.cancel();
1260    }
1261
1262    fn fail(&self, event_error: Option<ValidationError>) -> Option<ValidationError> {
1263        let first_event_error = {
1264            let mut fatal_event = self
1265                .fatal_event
1266                .lock()
1267                .expect("event fatal latch lock poisoned");
1268            if !self.fatal.load(Ordering::Acquire) {
1269                *fatal_event = event_error;
1270                self.fatal.store(true, Ordering::Release);
1271            }
1272            *fatal_event
1273        };
1274        #[cfg(test)]
1275        self.pause_before_reject(FreezePoint::Fatal);
1276        self.reject_pending();
1277        self.interruption.cancel();
1278        self.cancel.cancel();
1279        first_event_error
1280    }
1281}
1282
1283pub(crate) struct Producer {
1284    sender: mpsc::UnboundedSender<Delivery>,
1285    control: Arc<Control>,
1286    serial: Mutex<()>,
1287}
1288
1289impl Producer {
1290    pub(crate) async fn emit_text(
1291        &self,
1292        kind: Kind,
1293        text: String,
1294        coord: Coord,
1295        item_id: Option<String>,
1296    ) -> Result<DeliveryOutcome, ValidationError> {
1297        self.emit(Event::driver_text(kind, text, coord, item_id), None)
1298            .await
1299    }
1300
1301    pub(crate) async fn emit_lifecycle(
1302        &self,
1303        kind: Kind,
1304        outcome: Option<Outcome>,
1305        coord: Coord,
1306    ) -> Result<DeliveryOutcome, ValidationError> {
1307        self.emit(Event::driver_lifecycle(kind, outcome, coord), None)
1308            .await
1309    }
1310
1311    pub(crate) async fn emit_input_admitted(
1312        &self,
1313        origin: InputOrigin,
1314        items: Vec<item::Item>,
1315        coord: Coord,
1316    ) -> Result<DeliveryOutcome, ValidationError> {
1317        self.emit(Event::driver_input_admitted(origin, items, coord), None)
1318            .await
1319    }
1320
1321    pub(crate) async fn emit_input_rejected(
1322        &self,
1323        reason: String,
1324        coord: Coord,
1325    ) -> Result<DeliveryOutcome, ValidationError> {
1326        self.emit(Event::driver_input_rejected(reason, coord), None)
1327            .await
1328    }
1329
1330    pub(crate) async fn emit_tool_call(
1331        &self,
1332        call: ToolCall,
1333        coord: Coord,
1334    ) -> Result<StrongDecision, ValidationError> {
1335        self.emit_strong(
1336            Event::driver_tool_call(call, coord),
1337            DecisionPoint::ToolCall,
1338        )
1339        .await
1340    }
1341
1342    pub(crate) async fn emit_tool_result(
1343        &self,
1344        result: item::ToolResult,
1345        coord: Coord,
1346    ) -> Result<StrongDecision, ValidationError> {
1347        self.emit_strong(
1348            Event::driver_tool_result(result, coord),
1349            DecisionPoint::ToolResult,
1350        )
1351        .await
1352    }
1353
1354    pub(crate) async fn emit_extension(
1355        &self,
1356        mut event: Event,
1357        coord: Coord,
1358    ) -> Result<DeliveryOutcome, ValidationError> {
1359        event.coord = Some(coord);
1360        self.emit(event, None).await
1361    }
1362
1363    pub(crate) async fn emit_after_tool_commit(
1364        &self,
1365        mut event: Event,
1366        coord: Coord,
1367    ) -> Result<StrongDecision, ValidationError> {
1368        event.coord = Some(coord);
1369        self.emit_strong(event, DecisionPoint::AfterToolCommit)
1370            .await
1371    }
1372
1373    pub(crate) async fn emit(
1374        &self,
1375        event: Event,
1376        decision_point: Option<DecisionPoint>,
1377    ) -> Result<DeliveryOutcome, ValidationError> {
1378        if let Some(decision_point) = decision_point {
1379            return self
1380                .emit_strong(event, decision_point)
1381                .await
1382                .map(Into::into);
1383        }
1384        let _serial = self.serial.lock().await;
1385        if self.control.interrupted() {
1386            return Ok(DeliveryOutcome::Rejected);
1387        }
1388        self.emit_locked(event, None)
1389            .await
1390            .map(|resolution| resolution.outward)
1391    }
1392
1393    async fn emit_strong(
1394        &self,
1395        event: Event,
1396        decision_point: DecisionPoint,
1397    ) -> Result<StrongDecision, ValidationError> {
1398        let _serial = self.serial.lock().await;
1399        if let Some(decision) = self.control.strong_interruption() {
1400            return Ok(decision);
1401        }
1402        Ok(self
1403            .emit_locked(event, Some(decision_point))
1404            .await?
1405            .strong
1406            .expect("a strong decision point always has a decision"))
1407    }
1408
1409    async fn emit_locked(
1410        &self,
1411        event: Event,
1412        decision_point: Option<DecisionPoint>,
1413    ) -> Result<DeliveryResolution, ValidationError> {
1414        if let Err(error) = event.validate(decision_point) {
1415            let _first_event_error = self.control.fail(Some(error));
1416            return Err(error);
1417        }
1418        let decision = decision_point.map(|_| {
1419            Arc::new(Decision {
1420                value: AtomicU8::new(PENDING),
1421                changed: Notify::new(),
1422                cancel: self.control.cancel.clone(),
1423                nonfatal: Arc::clone(&self.control.nonfatal),
1424                #[cfg(test)]
1425                after_pending_check: SyncMutex::new(None),
1426            })
1427        });
1428        let _pending = decision.as_ref().map(|decision| {
1429            self.control.register(decision);
1430            PendingDecision {
1431                control: &self.control,
1432                decision: Arc::clone(decision),
1433            }
1434        });
1435        let delivery = Delivery {
1436            event,
1437            decision_point,
1438            decision: decision.clone(),
1439        };
1440        // An unbounded lane accepts the delivery immediately, so the only two
1441        // reasons not to hand it over are that this Run is already interrupted
1442        // or that the consumer has dropped its stream. Cancellation is checked
1443        // first to keep the pre-existing precedence: an interrupted Run does not
1444        // publish, even when the consumer is still listening.
1445        let delivered = !self.control.cancel.is_cancelled() && self.sender.send(delivery).is_ok();
1446        let outcome = if let Some(decision) = &decision {
1447            if !delivered {
1448                let _already_decided = decision.abandon();
1449            }
1450            let decision = self.control.final_confirm_strong(decision.wait().await);
1451            #[cfg(test)]
1452            self.control.pause_after_final_confirm().await;
1453            DeliveryResolution::strong(decision)
1454        } else {
1455            DeliveryResolution::ordinary(if delivered {
1456                DeliveryOutcome::Delivered
1457            } else {
1458                DeliveryOutcome::Rejected
1459            })
1460        };
1461        Ok(outcome)
1462    }
1463
1464    pub(crate) async fn emit_stop(
1465        &self,
1466        code: StopCode,
1467        coord: Coord,
1468    ) -> Result<DeliveryOutcome, ValidationError> {
1469        if self.control.stop_emitted.swap(true, Ordering::AcqRel) {
1470            return Ok(DeliveryOutcome::Rejected);
1471        }
1472        self.control.latch_stop();
1473        let _serial = self.serial.lock().await;
1474        if self.control.cancel.is_cancelled() {
1475            return Ok(DeliveryOutcome::Rejected);
1476        }
1477        self.emit_locked(Event::driver_stop(code, coord), None)
1478            .await
1479            .map(|resolution| resolution.outward)
1480    }
1481}
1482
1483/// A restricted per-invocation emit failure.
1484#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1485#[non_exhaustive]
1486pub enum ToolEmitError {
1487    /// The invocation's emit window already closed.
1488    Closed,
1489    /// The event was not delivered to the outward consumer.
1490    Rejected,
1491    /// The supplied extension fact was invalid.
1492    Invalid(ValidationError),
1493}
1494
1495impl fmt::Display for ToolEmitError {
1496    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1497        match self {
1498            Self::Closed => formatter.write_str("tool invocation emit window is closed"),
1499            Self::Rejected => formatter.write_str("tool invocation event was not delivered"),
1500            Self::Invalid(error) => write!(formatter, "invalid tool invocation event: {error}"),
1501        }
1502    }
1503}
1504
1505impl Error for ToolEmitError {
1506    fn source(&self) -> Option<&(dyn Error + 'static)> {
1507        match self {
1508            Self::Invalid(error) => Some(error),
1509            Self::Closed | Self::Rejected => None,
1510        }
1511    }
1512}
1513
1514struct Outward {
1515    producer: Arc<Producer>,
1516    coord: Coord,
1517}
1518
1519enum EmitTarget {
1520    Closed,
1521    Open(Outward),
1522}
1523
1524struct EmitterState {
1525    target: EmitTarget,
1526    active: usize,
1527}
1528
1529struct ToolEmitterInner {
1530    state: SyncMutex<EmitterState>,
1531    idle: Notify,
1532    /// Holds one emission inside its open window until a test releases it.
1533    ///
1534    /// The outward lane is unbounded, so a real emission never stays in flight
1535    /// long enough for a test to observe the close/drain barrier it is supposed
1536    /// to cross. This is the same shape as the two `Control` pauses.
1537    #[cfg(test)]
1538    pause: SyncMutex<Option<Arc<TestEmitPause>>>,
1539}
1540
1541impl ToolEmitterInner {
1542    #[cfg(test)]
1543    async fn pause(&self) {
1544        let pause = self
1545            .pause
1546            .lock()
1547            .expect("tool emitter pause lock poisoned")
1548            .take();
1549        if let Some(pause) = pause {
1550            let _observer_may_be_gone = pause.reached.send(());
1551            pause
1552                .resume
1553                .acquire()
1554                .await
1555                .expect("tool emitter pause remains open")
1556                .forget();
1557        }
1558    }
1559
1560    fn enter(&self) -> Option<(ActiveEmit<'_>, Arc<Producer>, Coord)> {
1561        let mut state = self.state.lock().expect("tool emitter lock poisoned");
1562        match &state.target {
1563            EmitTarget::Closed => None,
1564            EmitTarget::Open(outward) => {
1565                let producer = Arc::clone(&outward.producer);
1566                let coord = outward.coord.clone();
1567                state.active += 1;
1568                Some((ActiveEmit { inner: self }, producer, coord))
1569            }
1570        }
1571    }
1572
1573    fn leave(&self) {
1574        let mut state = self.state.lock().expect("tool emitter lock poisoned");
1575        state.active -= 1;
1576        if state.active == 0 {
1577            self.idle.notify_waiters();
1578        }
1579    }
1580
1581    fn close(&self) {
1582        self.state
1583            .lock()
1584            .expect("tool emitter lock poisoned")
1585            .target = EmitTarget::Closed;
1586    }
1587
1588    async fn drain(&self) {
1589        loop {
1590            let idle = self.idle.notified();
1591            tokio::pin!(idle);
1592            let _already_ready = idle.as_mut().enable();
1593            if self
1594                .state
1595                .lock()
1596                .expect("tool emitter lock poisoned")
1597                .active
1598                == 0
1599            {
1600                return;
1601            }
1602            idle.await;
1603        }
1604    }
1605}
1606
1607/// Releases one in-flight emission even when the executor future is dropped.
1608struct ActiveEmit<'a> {
1609    inner: &'a ToolEmitterInner,
1610}
1611
1612impl Drop for ActiveEmit<'_> {
1613    fn drop(&mut self) {
1614        self.inner.leave();
1615    }
1616}
1617
1618/// The only emit capability handed to one tool invocation.
1619///
1620/// The typed constructors make loop-owned categories unrepresentable: an
1621/// executor cannot forge text, thinking, tool, lifecycle, or stop events, and it
1622/// cannot replay an [`Event`] observed from the outward stream. The runtime
1623/// stamps the call's [`Coord`], so neither producer authority nor outward event
1624/// state is ever reachable from an executor.
1625///
1626/// [`emit_audit`](Self::emit_audit) and [`emit_error`](Self::emit_error) are
1627/// async: each call is serialized with other outward emissions and returns once
1628/// the event is enqueued on the unbounded outward lane. Ordinary Audit/Error
1629/// delivery has no consumer acknowledgement; success means the stream remained
1630/// open for the enqueue. This differs from a hook scope's synchronous
1631/// `emit_audit` and `emit_error` methods, which queue locally and return
1632/// immediately because a synchronous callback cannot await.
1633/// Immediately after the paired invocation returns, the runtime closes this
1634/// window and every later call is a [`ToolEmitError::Closed`] no-op.
1635pub struct ToolEmitter {
1636    inner: Arc<ToolEmitterInner>,
1637}
1638
1639impl fmt::Debug for ToolEmitter {
1640    /// Prints the bare type name, which is the honest answer here.
1641    ///
1642    /// This is the one type in the crate with nothing to distinguish two live
1643    /// values by. Its entire state is an emitter-state machine behind a mutex
1644    /// and a `Notify`; whether the window is open changes under the reader's
1645    /// feet, and reporting it would describe a moment that has already passed.
1646    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1647        formatter.debug_struct("ToolEmitter").finish()
1648    }
1649}
1650
1651impl ToolEmitter {
1652    /// Creates an emitter that is already closed and carries no authority.
1653    ///
1654    /// Composition layers and tests that route a call outside a live run use
1655    /// this to satisfy the invocation contract; every emission is a
1656    /// [`ToolEmitError::Closed`] no-op.
1657    #[must_use]
1658    pub fn closed() -> Self {
1659        Self {
1660            inner: Arc::new(ToolEmitterInner {
1661                state: SyncMutex::new(EmitterState {
1662                    target: EmitTarget::Closed,
1663                    active: 0,
1664                }),
1665                idle: Notify::new(),
1666                #[cfg(test)]
1667                pause: SyncMutex::new(None),
1668            }),
1669        }
1670    }
1671
1672    /// Emits one non-model-visible audit fact.
1673    ///
1674    /// # Errors
1675    ///
1676    /// Returns [`ToolEmitError::Invalid`] for an empty audit kind,
1677    /// [`ToolEmitError::Closed`] after the invocation window closed, and
1678    /// [`ToolEmitError::Rejected`] when the outward stream closed before enqueue.
1679    ///
1680    /// # Panics
1681    ///
1682    /// If the lock guarding the invocation's emit window is poisoned, per the
1683    /// crate-level [lock-poisoning contract](crate#lock-poisoning).
1684    pub async fn emit_audit(&self, audit: audit::Event) -> Result<(), ToolEmitError> {
1685        let event = Event::from_audit(audit).map_err(ToolEmitError::Invalid)?;
1686        self.emit_extension(event).await
1687    }
1688
1689    /// Emits one recoverable, non-fatal degradation notice.
1690    ///
1691    /// # Errors
1692    ///
1693    /// Returns [`ToolEmitError::Closed`] after the invocation window closed and
1694    /// [`ToolEmitError::Rejected`] when the outward stream closed before enqueue.
1695    ///
1696    /// # Panics
1697    ///
1698    /// If the lock guarding the invocation's emit window is poisoned, per the
1699    /// crate-level [lock-poisoning contract](crate#lock-poisoning).
1700    pub async fn emit_error(
1701        &self,
1702        error: Arc<dyn Error + Send + Sync>,
1703    ) -> Result<(), ToolEmitError> {
1704        self.emit_extension(Event::from_error(error)).await
1705    }
1706
1707    async fn emit_extension(&self, event: Event) -> Result<(), ToolEmitError> {
1708        let Some((_active, producer, coord)) = self.inner.enter() else {
1709            return Err(ToolEmitError::Closed);
1710        };
1711        #[cfg(test)]
1712        self.inner.pause().await;
1713        let outcome = producer.emit_extension(event, coord).await;
1714        // Both public constructors pre-validate, so the producer's fatal
1715        // validation lane is unreachable here and non-delivery is the only
1716        // remaining failure fact.
1717        if matches!(outcome, Ok(DeliveryOutcome::Delivered)) {
1718            Ok(())
1719        } else {
1720            Err(ToolEmitError::Rejected)
1721        }
1722    }
1723}
1724
1725/// The runtime-owned close side of one invocation's emit window.
1726pub(crate) struct ToolEmitterGate {
1727    inner: Arc<ToolEmitterInner>,
1728}
1729
1730impl ToolEmitterGate {
1731    /// Closes the window, then waits for every already-active emission.
1732    pub(crate) async fn close_and_wait(self) {
1733        self.inner.close();
1734        self.inner.drain().await;
1735    }
1736}
1737
1738/// Mints one invocation-scoped emitter and its runtime-owned close gate.
1739pub(crate) fn tool_emitter(
1740    producer: &Arc<Producer>,
1741    coord: Coord,
1742) -> (ToolEmitter, ToolEmitterGate) {
1743    let inner = Arc::new(ToolEmitterInner {
1744        state: SyncMutex::new(EmitterState {
1745            target: EmitTarget::Open(Outward {
1746                producer: Arc::clone(producer),
1747                coord,
1748            }),
1749            active: 0,
1750        }),
1751        idle: Notify::new(),
1752        #[cfg(test)]
1753        pause: SyncMutex::new(None),
1754    });
1755    (
1756        ToolEmitter {
1757            inner: Arc::clone(&inner),
1758        },
1759        ToolEmitterGate { inner },
1760    )
1761}
1762
1763pub(crate) struct EventSource {
1764    stream: Option<Stream>,
1765    control: Arc<Control>,
1766}
1767
1768#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1769pub(crate) struct StreamTakenError;
1770
1771impl EventSource {
1772    pub(crate) fn take_stream(&mut self) -> Result<Stream, StreamTakenError> {
1773        self.stream.take().ok_or(StreamTakenError)
1774    }
1775
1776    pub(crate) fn request_stop(&self) {
1777        self.control.request_stop();
1778    }
1779
1780    pub(crate) fn terminal_intent(&self) -> TerminalIntent {
1781        self.control.intent()
1782    }
1783
1784    /// Resolves when outward control stops or fails the run.
1785    ///
1786    /// This signal is deliberately independent of the parent-derived cancellation
1787    /// token. Consumer drop must wake the Driver even though it cannot cancel the
1788    /// parent, while explicit parent cancellation stays on the Driver's normal
1789    /// cancellation path so already-durable facts and real fatal errors retain
1790    /// their established priority.
1791    pub(crate) async fn interruption(&self) {
1792        self.control.interruption.cancelled().await;
1793    }
1794
1795    pub(crate) fn latch_failure(&self) -> Option<ValidationError> {
1796        self.control.fail(None)
1797    }
1798
1799    #[cfg(test)]
1800    fn state(&self) -> (bool, bool, bool) {
1801        (
1802            self.control.nonfatal.frozen() == NONFATAL_STOPPED,
1803            self.control.fatal.load(Ordering::Acquire),
1804            self.control.cancel.is_cancelled(),
1805        )
1806    }
1807}
1808
1809/// Creates the outward lane for one Run.
1810///
1811/// The lane is unbounded on purpose. Every blocking boundary Reef has is an
1812/// explicit acknowledgement — the three strong seams wait on their own
1813/// [`Decision`], not on buffer space — so letting a full buffer also stall the
1814/// loop would make delivery latency a second, invisible flow-control mechanism.
1815/// With an unbounded lane a slow or inattentive consumer can never wedge a Run:
1816/// the only way a send fails is that the consumer dropped its stream, which is
1817/// that consumer stating it wants nothing further.
1818pub(crate) fn channel(parent: &Token) -> (Arc<Producer>, EventSource) {
1819    let (sender, receiver) = mpsc::unbounded_channel();
1820    let nonfatal = Arc::new(NonfatalCause {
1821        parent: parent.clone(),
1822        cause: SyncMutex::new(NONFATAL_NONE),
1823    });
1824    let control = Arc::new(Control {
1825        nonfatal,
1826        fatal: AtomicBool::new(false),
1827        fatal_event: SyncMutex::new(None),
1828        stop_emitted: AtomicBool::new(false),
1829        pending: SyncMutex::new(None),
1830        cancel: parent.child_token(),
1831        interruption: Token::new(),
1832        #[cfg(test)]
1833        before_reject_pause: SyncMutex::new(None),
1834        #[cfg(test)]
1835        after_final_confirm_pause: SyncMutex::new(None),
1836    });
1837    let producer = Arc::new(Producer {
1838        sender,
1839        control: control.clone(),
1840        serial: Mutex::new(()),
1841    });
1842    let stream = Stream {
1843        receiver,
1844        control: control.clone(),
1845    };
1846    (
1847        producer,
1848        EventSource {
1849            stream: Some(stream),
1850            control,
1851        },
1852    )
1853}
1854
1855#[cfg(test)]
1856pub(crate) mod testing {
1857    use super::*;
1858
1859    /// The runtime path that publishes one event category.
1860    ///
1861    /// This exists so that "which variants can a consumer actually see" is a
1862    /// value rather than a comment. Nothing in the crate reads it to make a
1863    /// decision; it is read by
1864    /// `driver_tests::every_event_kind_reaches_a_consumer_from_a_real_run`.
1865    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
1866    pub(crate) enum Emission {
1867        /// [`Producer::emit_text`], from streamed or consolidated content.
1868        Content,
1869        /// [`Producer::emit_lifecycle`], from a Turn, Step or Generation boundary.
1870        Lifecycle,
1871        /// [`Producer::emit_tool_call`], at the `ToolCall` strong decision point.
1872        ToolCall,
1873        /// [`Producer::emit_tool_result`], at the `ToolResult` strong decision point.
1874        ToolResult,
1875        /// [`ToolEmitter`], the only extension-owned emission authority.
1876        Extension,
1877        /// [`Producer::emit_stop`], the single privately owned `EventStop`.
1878        Stop,
1879        /// [`Producer::emit_input_admitted`]/[`Producer::emit_input_rejected`],
1880        /// the loop's two statements about a claimed or composed input batch.
1881        Input,
1882    }
1883
1884    /// The runtime path that publishes `kind`.
1885    ///
1886    /// Exhaustive with no wildcard arm on purpose. Adding a variant to [`Kind`]
1887    /// stops the crate compiling here, and the compiler error lands on the one
1888    /// list a new variant has to join — [`ALL_KINDS`] is immediately below it.
1889    /// Once the variant is in that list,
1890    /// `every_event_kind_reaches_a_consumer_from_a_real_run` requires a real
1891    /// [`Driver`] run to publish it, so a variant cannot be declared without
1892    /// being wired.
1893    ///
1894    /// Rust has no stable way to enumerate an enum's variants, so the list itself
1895    /// is written by hand; what is mechanical is that the list cannot be reached
1896    /// without a compiler error first, and cannot be satisfied afterwards without
1897    /// a production emitter.
1898    ///
1899    /// [`Driver`]: crate::runtime::driver::Driver
1900    pub(crate) const fn emission(kind: Kind) -> Emission {
1901        match kind {
1902            Kind::TextDelta | Kind::Text | Kind::ThinkingDelta | Kind::Thinking => {
1903                Emission::Content
1904            }
1905            Kind::TurnStart
1906            | Kind::TurnEnd
1907            | Kind::StepStart
1908            | Kind::StepEnd
1909            | Kind::GenerationEnd => Emission::Lifecycle,
1910            Kind::ToolCall => Emission::ToolCall,
1911            Kind::ToolResult => Emission::ToolResult,
1912            Kind::Audit | Kind::Error => Emission::Extension,
1913            Kind::Stop => Emission::Stop,
1914            Kind::InputAdmitted | Kind::InputRejected => Emission::Input,
1915        }
1916    }
1917
1918    /// Every event category a consumer can observe.
1919    pub(crate) const ALL_KINDS: &[Kind] = &[
1920        Kind::TextDelta,
1921        Kind::Text,
1922        Kind::ThinkingDelta,
1923        Kind::Thinking,
1924        Kind::TurnStart,
1925        Kind::TurnEnd,
1926        Kind::StepStart,
1927        Kind::StepEnd,
1928        Kind::GenerationEnd,
1929        Kind::ToolCall,
1930        Kind::ToolResult,
1931        Kind::Error,
1932        Kind::Audit,
1933        Kind::Stop,
1934        Kind::InputAdmitted,
1935        Kind::InputRejected,
1936    ];
1937
1938    pub(crate) fn text(kind: Kind, text: &str, coord: Coord) -> Event {
1939        Event::driver_text(kind, text.into(), coord, None)
1940    }
1941
1942    pub(crate) fn lifecycle(kind: Kind, outcome: Option<Outcome>, coord: Coord) -> Event {
1943        Event::driver_lifecycle(kind, outcome, coord)
1944    }
1945
1946    pub(crate) fn tool_call(call: ToolCall, coord: Coord) -> Event {
1947        Event::driver_tool_call(call, coord)
1948    }
1949
1950    pub(crate) fn tool_result(result: item::ToolResult, coord: Coord) -> Event {
1951        Event::driver_tool_result(result, coord)
1952    }
1953
1954    pub(crate) fn stop(code: StopCode, coord: Coord) -> Event {
1955        Event::driver_stop(code, coord)
1956    }
1957
1958    pub(crate) fn input_admitted(
1959        origin: InputOrigin,
1960        items: Vec<item::Item>,
1961        coord: Coord,
1962    ) -> Event {
1963        Event::driver_input_admitted(origin, items, coord)
1964    }
1965
1966    pub(crate) fn input_rejected(reason: String, coord: Coord) -> Event {
1967        Event::driver_input_rejected(reason, coord)
1968    }
1969
1970    pub(crate) fn forged(kind: Kind, event: Event) -> Event {
1971        Event { kind, ..event }
1972    }
1973
1974    pub(crate) fn invalid_audit(coord: Coord) -> Event {
1975        Event {
1976            kind: Kind::Audit,
1977            coord: Some(coord),
1978            item_id: None,
1979            payload: Payload::Audit(audit::Event::new(String::new(), None)),
1980        }
1981    }
1982
1983    pub(crate) fn invalid_stop(coord: Coord) -> Event {
1984        Event {
1985            kind: Kind::Stop,
1986            coord: Some(coord),
1987            item_id: None,
1988            payload: Payload::Stop(StopCode(String::new())),
1989        }
1990    }
1991
1992    pub(crate) fn control(source: &EventSource) -> (bool, bool, bool) {
1993        source.state()
1994    }
1995
1996    pub(crate) use super::FreezePoint;
1997
1998    #[derive(Clone)]
1999    pub(crate) struct InterruptionProbe(Arc<Control>);
2000
2001    impl InterruptionProbe {
2002        pub(crate) fn request_stop(&self) {
2003            self.0.request_stop();
2004        }
2005
2006        pub(crate) fn fail(&self) {
2007            let _first_event_error = self.0.fail(Some(ValidationError::PayloadMismatch));
2008        }
2009    }
2010
2011    pub(crate) fn interruption_probe(source: &EventSource) -> InterruptionProbe {
2012        InterruptionProbe(Arc::clone(&source.control))
2013    }
2014
2015    pub(crate) struct FreezePauseProbe {
2016        reached: Arc<std::sync::Barrier>,
2017        resume: Arc<std::sync::Barrier>,
2018    }
2019
2020    impl FreezePauseProbe {
2021        pub(crate) fn wait_until_frozen(&self) {
2022            self.reached.wait();
2023        }
2024
2025        pub(crate) fn resume_rejection(&self) {
2026            self.resume.wait();
2027        }
2028    }
2029
2030    pub(crate) fn pause_before_reject(
2031        source: &EventSource,
2032        point: FreezePoint,
2033    ) -> (InterruptionProbe, FreezePauseProbe) {
2034        let reached = Arc::new(std::sync::Barrier::new(2));
2035        let resume = Arc::new(std::sync::Barrier::new(2));
2036        *source
2037            .control
2038            .before_reject_pause
2039            .lock()
2040            .expect("event freeze pause lock poisoned") = Some(TestFreezePause {
2041            point,
2042            reached: Arc::clone(&reached),
2043            resume: Arc::clone(&resume),
2044        });
2045        (
2046            interruption_probe(source),
2047            FreezePauseProbe { reached, resume },
2048        )
2049    }
2050
2051    pub(crate) struct FinalConfirmPauseProbe(Arc<TestFinalConfirmPause>);
2052
2053    impl FinalConfirmPauseProbe {
2054        pub(crate) async fn wait_until_confirmed(&self) {
2055            self.0
2056                .reached
2057                .acquire()
2058                .await
2059                .expect("event final-confirm pause remains open")
2060                .forget();
2061        }
2062
2063        pub(crate) fn resume_return(&self) {
2064            self.0.resume.add_permits(1);
2065        }
2066    }
2067
2068    pub(crate) fn pause_after_final_confirm(source: &EventSource) -> FinalConfirmPauseProbe {
2069        let pause = Arc::new(TestFinalConfirmPause {
2070            reached: Semaphore::new(0),
2071            resume: Semaphore::new(0),
2072        });
2073        *source
2074            .control
2075            .after_final_confirm_pause
2076            .lock()
2077            .expect("event final-confirm pause lock poisoned") = Some(Arc::clone(&pause));
2078        FinalConfirmPauseProbe(pause)
2079    }
2080
2081    pub(crate) fn intent(source: &EventSource) -> TerminalIntent {
2082        source.terminal_intent()
2083    }
2084
2085    pub(crate) fn has_pending_strong_decision(source: &EventSource) -> bool {
2086        source
2087            .control
2088            .pending
2089            .lock()
2090            .expect("event pending lock poisoned")
2091            .is_some()
2092    }
2093
2094    pub(crate) fn stale_pending_guard_preserves_successor(source: &EventSource) -> (bool, bool) {
2095        let decision = || {
2096            Arc::new(Decision {
2097                value: AtomicU8::new(PENDING),
2098                changed: Notify::new(),
2099                cancel: source.control.cancel.clone(),
2100                nonfatal: Arc::clone(&source.control.nonfatal),
2101                after_pending_check: SyncMutex::new(None),
2102            })
2103        };
2104        let stale = decision();
2105        source.control.register(&stale);
2106        let stale_guard = PendingDecision {
2107            control: &source.control,
2108            decision: Arc::clone(&stale),
2109        };
2110        let successor = decision();
2111        source.control.register(&successor);
2112
2113        drop(stale_guard);
2114        let successor_preserved = source
2115            .control
2116            .pending
2117            .lock()
2118            .expect("event pending lock poisoned")
2119            .as_ref()
2120            .is_some_and(|pending| Arc::ptr_eq(pending, &successor));
2121        let stale_abandoned = stale.decide(ACCEPTED) == Err(DecisionError::AlreadyDecided);
2122        source.control.reject_pending();
2123        (successor_preserved, stale_abandoned)
2124    }
2125
2126    #[derive(Clone)]
2127    pub(crate) struct EmitterProbe(Arc<ToolEmitterInner>);
2128
2129    impl EmitterProbe {
2130        pub(crate) fn state(&self) -> (bool, usize) {
2131            let state = self.0.state.lock().expect("tool emitter lock poisoned");
2132            (matches!(state.target, EmitTarget::Closed), state.active)
2133        }
2134    }
2135
2136    pub(crate) fn emitter_probe(emitter: &ToolEmitter) -> EmitterProbe {
2137        EmitterProbe(Arc::clone(&emitter.inner))
2138    }
2139
2140    /// Holds one emission open inside its window until the test releases it.
2141    #[derive(Clone)]
2142    pub(crate) struct EmitPauseProbe(Arc<TestEmitPause>);
2143
2144    impl EmitPauseProbe {
2145        /// Announces the held emission on `reached` once it is inside the window.
2146        pub(crate) fn new(reached: std::sync::mpsc::Sender<()>) -> Self {
2147            Self(Arc::new(TestEmitPause {
2148                reached,
2149                resume: Semaphore::new(0),
2150            }))
2151        }
2152
2153        /// Arms this pause for the emitter's next emission only.
2154        pub(crate) fn arm(&self, emitter: &ToolEmitter) {
2155            *emitter
2156                .inner
2157                .pause
2158                .lock()
2159                .expect("tool emitter pause lock poisoned") = Some(Arc::clone(&self.0));
2160        }
2161
2162        pub(crate) fn resume(&self) {
2163            self.0.resume.add_permits(1);
2164        }
2165    }
2166
2167    /// Cancels the Run-local token without latching a nonfatal cause.
2168    ///
2169    /// Every public route into this state latches the cause first, which makes
2170    /// the outward hand-over's own cancellation check unobservable from outside.
2171    /// That check is the last thing standing between a cancelled Run and a
2172    /// published event, so it is worth pinning rather than assuming.
2173    pub(crate) fn cancel_lane(source: &EventSource) {
2174        source.control.cancel.cancel();
2175    }
2176
2177    pub(crate) fn fail(source: &EventSource) {
2178        let _first_event_error = source.control.fail(Some(ValidationError::PayloadMismatch));
2179    }
2180
2181    #[derive(Clone)]
2182    pub(crate) struct DecisionProbe(Arc<Decision>);
2183
2184    impl DecisionProbe {
2185        pub(crate) fn plain(cancel: Token) -> Self {
2186            let nonfatal = Arc::new(NonfatalCause {
2187                parent: cancel.clone(),
2188                cause: SyncMutex::new(NONFATAL_NONE),
2189            });
2190            Self(Arc::new(Decision {
2191                value: AtomicU8::new(PENDING),
2192                changed: Notify::new(),
2193                cancel,
2194                nonfatal,
2195                after_pending_check: SyncMutex::new(None),
2196            }))
2197        }
2198
2199        pub(crate) fn paused_after_pending_check(
2200            cancel: Token,
2201        ) -> (Self, Arc<std::sync::Barrier>, Arc<std::sync::Barrier>) {
2202            let checked = Arc::new(std::sync::Barrier::new(2));
2203            let resume = Arc::new(std::sync::Barrier::new(2));
2204            let nonfatal = Arc::new(NonfatalCause {
2205                parent: cancel.clone(),
2206                cause: SyncMutex::new(NONFATAL_NONE),
2207            });
2208            let decision = Arc::new(Decision {
2209                value: AtomicU8::new(PENDING),
2210                changed: Notify::new(),
2211                cancel,
2212                nonfatal,
2213                after_pending_check: SyncMutex::new(Some(WaitBarriers {
2214                    checked: checked.clone(),
2215                    resume: resume.clone(),
2216                })),
2217            });
2218            (Self(decision), checked, resume)
2219        }
2220
2221        pub(crate) fn accept(&self) -> Result<(), DecisionError> {
2222            self.0.decide_consumer(ACCEPTED)
2223        }
2224
2225        pub(crate) fn reject(&self) -> Result<(), DecisionError> {
2226            self.0.decide_consumer(REJECTED)
2227        }
2228
2229        pub(crate) async fn wait(&self) -> StrongDecision {
2230            self.0.wait().await
2231        }
2232    }
2233
2234    pub(crate) fn register_probe(source: &EventSource) -> bool {
2235        let decision = DecisionProbe::plain(source.control.cancel.clone()).0;
2236        source.control.register(&decision);
2237        decision.value.load(Ordering::Acquire) == REJECTED
2238    }
2239
2240    /// Observes one emitter's in-flight emission count so concurrency tests can
2241    /// wait on real state instead of task-scheduling luck.
2242    pub(crate) fn tool_emitter_active(emitter: &ToolEmitter) -> usize {
2243        emitter
2244            .inner
2245            .state
2246            .lock()
2247            .expect("tool emitter lock poisoned")
2248            .active
2249    }
2250}
2251
2252/// The serialized form of [`Kind`] (ADR-019 D5).
2253///
2254/// A kind travels as its own tag and nothing else. [`Event`] itself is not
2255/// serializable and cannot be: its private payload carries an
2256/// `Arc<dyn Error + Send + Sync>`, and its loop-owned variants have no public
2257/// constructors. So a serialized `Kind` is the tag a lifecycle record carries,
2258/// not a protocol, and nothing here should be read as delivering one.
2259///
2260/// `Kind` is `#[non_exhaustive]`, but its serialized form carries no schema
2261/// version. Compatibility is content-driven: an unknown tag on ingress is an
2262/// error rather than a fallback variant, while a recognized tag is not rejected
2263/// merely because a different reef version wrote it.
2264#[cfg(feature = "serde")]
2265mod serde_impl {
2266    use std::fmt::{self, Formatter};
2267
2268    use serde_core::de::{
2269        Deserialize, Deserializer, EnumAccess, Error as DeError, VariantAccess, Visitor,
2270    };
2271    use serde_core::ser::{Serialize, Serializer};
2272
2273    use super::Kind;
2274    use crate::wire::IdentifierSeed;
2275
2276    const NAME: &str = "Kind";
2277    const VARIANTS: &[&str] = &[
2278        "text_delta",
2279        "text",
2280        "thinking_delta",
2281        "thinking",
2282        "turn_start",
2283        "turn_end",
2284        "step_start",
2285        "step_end",
2286        "generation_end",
2287        "tool_call",
2288        "tool_result",
2289        "error",
2290        "audit",
2291        "stop",
2292        "input_admitted",
2293        "input_rejected",
2294    ];
2295
2296    impl Serialize for Kind {
2297        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2298        where
2299            S: Serializer,
2300        {
2301            let (index, tag) = match self {
2302                Self::TextDelta => (0, "text_delta"),
2303                Self::Text => (1, "text"),
2304                Self::ThinkingDelta => (2, "thinking_delta"),
2305                Self::Thinking => (3, "thinking"),
2306                Self::TurnStart => (4, "turn_start"),
2307                Self::TurnEnd => (5, "turn_end"),
2308                Self::StepStart => (6, "step_start"),
2309                Self::StepEnd => (7, "step_end"),
2310                Self::GenerationEnd => (8, "generation_end"),
2311                Self::ToolCall => (9, "tool_call"),
2312                Self::ToolResult => (10, "tool_result"),
2313                Self::Error => (11, "error"),
2314                Self::Audit => (12, "audit"),
2315                Self::Stop => (13, "stop"),
2316                Self::InputAdmitted => (14, "input_admitted"),
2317                Self::InputRejected => (15, "input_rejected"),
2318            };
2319            serializer.serialize_unit_variant(NAME, index, tag)
2320        }
2321    }
2322
2323    impl<'de> Deserialize<'de> for Kind {
2324        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2325        where
2326            D: Deserializer<'de>,
2327        {
2328            deserializer.deserialize_enum(NAME, VARIANTS, KindVisitor)
2329        }
2330    }
2331
2332    struct KindVisitor;
2333
2334    impl<'de> Visitor<'de> for KindVisitor {
2335        type Value = Kind;
2336
2337        fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
2338            formatter.write_str("an outward event kind")
2339        }
2340
2341        fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
2342        where
2343            A: EnumAccess<'de>,
2344        {
2345            let (tag, variant) = data.variant_seed(IdentifierSeed(VARIANTS))?;
2346            variant.unit_variant()?;
2347            match tag.0.as_str() {
2348                "text_delta" => Ok(Kind::TextDelta),
2349                "text" => Ok(Kind::Text),
2350                "thinking_delta" => Ok(Kind::ThinkingDelta),
2351                "thinking" => Ok(Kind::Thinking),
2352                "turn_start" => Ok(Kind::TurnStart),
2353                "turn_end" => Ok(Kind::TurnEnd),
2354                "step_start" => Ok(Kind::StepStart),
2355                "step_end" => Ok(Kind::StepEnd),
2356                "generation_end" => Ok(Kind::GenerationEnd),
2357                "tool_call" => Ok(Kind::ToolCall),
2358                "tool_result" => Ok(Kind::ToolResult),
2359                "error" => Ok(Kind::Error),
2360                "audit" => Ok(Kind::Audit),
2361                "stop" => Ok(Kind::Stop),
2362                "input_admitted" => Ok(Kind::InputAdmitted),
2363                "input_rejected" => Ok(Kind::InputRejected),
2364                unknown => Err(A::Error::unknown_variant(unknown, VARIANTS)),
2365            }
2366        }
2367    }
2368}