reef-core 0.4.0

Provider-neutral primitives for building LLM agents: run lifecycle, transcript, tools, hooks
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
//! Public Run handle and the sole tracked runtime owner.

use std::error::Error;
use std::fmt;
use std::future::Future;
use std::panic::{AssertUnwindSafe, catch_unwind, resume_unwind};
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};

use tokio::sync::Notify;

use super::agent::start::AdmittedStart;
use super::agent::{AttachmentGuard, Revision};
use super::driver;
use super::event::{Event, EventSource, InputOrigin, Producer, StopCode, Stream, ValidationError};
use super::hook::{
    self, BufferedFact, CallbackResources, FactBuffer, LifecycleEnd, LifecycleObservation,
    TranscriptSource,
};
use super::model::Client;
use super::session::{Lease, Session};
use crate::audit;
use crate::state::run_state::{self};
use crate::state::session_state::{self};
use crate::transcript::controller::TranscriptController;
use crate::transcript::item::Item;
use crate::value::lifecycle::{Coord, Outcome};

/// A cloneable handle to one admitted Run.
///
/// A Run exists only because [`Agent::start`](super::agent::Agent::start) or
/// [`Agent::start_observed`](super::agent::Agent::start_observed) admitted a Session,
/// so by the time you hold one the input is already recorded and the loop is already
/// running. Ask it to stop and wait for its [`Terminal`]. When `start` constructed it,
/// also take its [`take_events`](Run::take_events) once; `start_observed` instead returns
/// that unique stream atomically beside the Run.
///
/// Every clone shares one Run. Dropping the last handle asks it to stop; it does
/// not wait, and it does not abandon work already in flight.
///
/// ```
/// # use std::future::{Future, ready};
/// # use std::pin::Pin;
/// # use std::sync::Arc;
/// # use std::task::{Context, Poll};
/// # use reef_core::futures_core::Stream;
/// # use reef_core::runtime::model;
/// # #[derive(Debug)] struct Offline;
/// # #[derive(Debug)] struct Once(bool);
/// # impl Stream for Once {
/// #     type Item = Result<model::Event, std::convert::Infallible>;
/// #     fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
/// #         if std::mem::replace(&mut self.0, true) { return Poll::Ready(None); }
/// #         Poll::Ready(Some(Ok(model::Event::Done { finish_reason: "stop".to_owned(), completion: model::CompletionReason::Stop, provider_data: Vec::new() })))
/// #     }
/// # }
/// # impl model::Client for Offline {
/// #     type Error = std::convert::Infallible;
/// #     type Stream = Once;
/// #     fn info(&self) -> model::Info { model::Info::new("offline".to_owned(), 8_192) }
/// #     fn generate(&self, _: model::Request) -> impl Future<Output = Result<Self::Stream, Self::Error>> + Send { ready(Ok(Once(false))) }
/// # }
/// use reef_core::cancel;
/// use reef_core::runtime::{agent, hook, run, session, tool};
/// use reef_core::value::{content, lifecycle};
///
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
/// # let config = agent::Config::new(Arc::new(Offline), tool::RegistryBuilder::new().build().unwrap(), hook::RegistryBuilder::new());
/// # let agent = agent::Agent::new(config).unwrap();
/// let session = session::Session::new("conversation-1".to_owned(), None);
/// let (started, mut events) = agent
///     .start_observed(session.clone(), vec![content::Part::text("Hi.".to_owned())], cancel::Token::new())
///     .await
///     .unwrap();
///
/// // Events are single-consumer: the atomic handoff means the Run and every
/// // clone report that its stream was already taken.
/// assert!(started.clone().take_events().is_err());
/// while let Some(delivery) = events.recv().await {
///     if delivery.decision_point().is_some() {
///         delivery.accept().unwrap();
///     }
/// }
///
/// // Every waiter gets the same terminal, and waiting again is free.
/// let terminal = started.wait().await;
/// assert_eq!(terminal.outcome(), lifecycle::Outcome::Completed);
/// assert_eq!(started.wait().await.outcome(), terminal.outcome());
/// # }
/// ```
pub struct Run<M: Client> {
    inner: Arc<RunInner<M>>,
}

impl<M: Client> fmt::Debug for Run<M> {
    /// Locates the Run by session and revision, and counts live handles.
    ///
    /// There is no `M: Debug` bound: a Run would otherwise be unprintable for
    /// every provider that has not opted in, and the model is not what
    /// distinguishes one Run from another anyway. The three facts here are all
    /// lock-free, so formatting a Run can never stall the Run.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Run")
            .field("session", &self.inner.session.id())
            .field("revision", &self.inner.revision.id())
            .field(
                "handles",
                &self.inner.public_handles.load(Ordering::Relaxed),
            )
            .finish()
    }
}

impl<M: Client> Clone for Run<M> {
    fn clone(&self) -> Self {
        self.inner.public_handles.fetch_add(1, Ordering::Relaxed);
        Self {
            inner: Arc::clone(&self.inner),
        }
    }
}

impl<M: Client> Drop for Run<M> {
    fn drop(&mut self) {
        if self.inner.public_handles.fetch_sub(1, Ordering::AcqRel) == 1 {
            self.inner.source.request_stop();
        }
    }
}

struct RunInner<M: Client> {
    revision: Revision<M>,
    session: Session,
    source: Arc<EventSource>,
    events: Mutex<Option<Stream>>,
    terminal: Mutex<Option<Arc<Terminal>>>,
    done: Notify,
    public_handles: AtomicUsize,
    task: Mutex<Option<tokio::task::JoinHandle<()>>>,
}

struct TaskExitState {
    entered_task_body: AtomicBool,
    task_panicked: AtomicBool,
    fallback_armed: AtomicBool,
}

/// Publishes the abnormal terminal after the inner future has released resources.
struct TaskFallback<M: Client> {
    inner: Arc<RunInner<M>>,
    identity: Coord,
    state: Arc<TaskExitState>,
}

impl<M: Client> Drop for TaskFallback<M> {
    fn drop(&mut self) {
        if !self.state.fallback_armed.swap(false, Ordering::AcqRel) {
            return;
        }
        let failure: Arc<dyn Error + Send + Sync> =
            if !self.state.entered_task_body.load(Ordering::Acquire) {
                Arc::new(TaskNotStartedError)
            } else if self.state.task_panicked.load(Ordering::Acquire) {
                Arc::new(TaskPanickedError)
            } else {
                Arc::new(TaskAbortedError)
            };
        self.inner.publish(Arc::new(Terminal::failed(
            self.identity.clone(),
            FailureKind::Internal,
            failure,
        )));
    }
}

/// Marks only panics raised while polling the Run's inner task body.
struct PanicMarkerFuture<F, M: Client> {
    // Fields drop in declaration order: inner cleanup must precede fallback
    // publication on every abnormal exit.
    inner: Pin<Box<F>>,
    fallback: TaskFallback<M>,
}

impl<F, M: Client> PanicMarkerFuture<F, M> {
    fn new(inner: F, fallback: TaskFallback<M>) -> Self {
        Self {
            inner: Box::pin(inner),
            fallback,
        }
    }
}

impl<F: Future, M: Client> Future for PanicMarkerFuture<F, M> {
    type Output = F::Output;

    fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.get_mut();
        match catch_unwind(AssertUnwindSafe(|| this.inner.as_mut().poll(context))) {
            Ok(poll) => poll,
            Err(payload) => {
                this.fallback
                    .state
                    .task_panicked
                    .store(true, Ordering::Release);
                resume_unwind(payload);
            }
        }
    }
}

/// Linear owner of the post-admission cleanup chain.
///
/// Options make every step idempotent if an individual destructor itself unwinds.
struct TaskCleanup<M: Client> {
    inner: Arc<RunInner<M>>,
    lease: Option<Lease>,
    attachment: Option<AttachmentGuard<M>>,
    producer: Option<Arc<Producer>>,
    state: Arc<TaskExitState>,
    armed: bool,
}

impl<M: Client> TaskCleanup<M> {
    const fn new(
        inner: Arc<RunInner<M>>,
        lease: Lease,
        attachment: AttachmentGuard<M>,
        producer: Arc<Producer>,
        state: Arc<TaskExitState>,
    ) -> Self {
        Self {
            inner,
            lease: Some(lease),
            attachment: Some(attachment),
            producer: Some(producer),
            state,
            armed: true,
        }
    }

    fn enter_task_body(&mut self) {
        self.state.entered_task_body.store(true, Ordering::Release);
    }

    const fn lease(&self) -> &Lease {
        self.lease
            .as_ref()
            .expect("the Run Lease remains owned until terminal cleanup")
    }

    const fn producer(&self) -> &Arc<Producer> {
        self.producer
            .as_ref()
            .expect("the event Producer remains open through RunEnd")
    }

    fn cleanup(&mut self) {
        // Cancellation is intentionally after terminal freeze on the normal path.
        // EventSource owns the Run-local child token, so this does not cancel the
        // caller's parent token.
        self.inner.source.request_stop();
        // Lease::drop performs the same idempotent synchronous release.
        drop(self.lease.take());
        drop(self.attachment.take());
        drop(self.producer.take());
        self.inner.close_events();
    }

    fn complete(mut self, terminal: Terminal) {
        self.cleanup();
        self.armed = false;
        self.state.fallback_armed.store(false, Ordering::Release);
        self.inner.publish(Arc::new(terminal));
    }
}

impl<M: Client> Drop for TaskCleanup<M> {
    fn drop(&mut self) {
        if !self.armed {
            return;
        }
        self.cleanup();
        self.armed = false;
    }
}

impl<M: Client + 'static> Run<M> {
    pub(crate) fn spawn(admitted: AdmittedStart<M>) -> Self {
        Self::spawn_inner(admitted, |events| (Some(events), ())).0
    }

    pub(crate) fn spawn_observed(admitted: AdmittedStart<M>) -> (Self, Stream) {
        Self::spawn_inner(admitted, |events| (None, events))
    }

    fn spawn_inner<R>(
        admitted: AdmittedStart<M>,
        place_stream: impl FnOnce(Stream) -> (Option<Stream>, R),
    ) -> (Self, R) {
        // Parsed from the `AdmittedStart` owner produced by either public Agent
        // start entry point through their one shared admission path.
        let AdmittedStart {
            lease,
            attachment,
            revision,
            session,
            input,
            admitted_items,
            plan,
            identity,
            cancellation,
            producer,
            mut source,
            hooks,
            reservation_resources,
            run_states,
            session_state,
            fact_buffer,
        } = admitted;
        let events = source
            .take_stream()
            .expect("a freshly admitted Run owns its event stream");
        // Select the receiver's owner before spawning: terminal cleanup can only
        // reach the `Option` stored in `RunInner`, never the separately returned value.
        let (run_events, returned) = place_stream(events);
        let source = Arc::new(source);
        let inner = Arc::new(RunInner {
            revision: revision.clone(),
            session: session.clone(),
            source: Arc::clone(&source),
            events: Mutex::new(run_events),
            terminal: Mutex::new(None),
            done: Notify::new(),
            public_handles: AtomicUsize::new(1),
            task: Mutex::new(None),
        });
        // Establish both cleanup and its trailing terminal fallback before spawning.
        // Tokio may discard an unpolled task during runtime shutdown, so constructing
        // either owner inside the async body would lose the pre-poll terminal path.
        let task_state = Arc::new(TaskExitState {
            entered_task_body: AtomicBool::new(false),
            task_panicked: AtomicBool::new(false),
            fallback_armed: AtomicBool::new(true),
        });
        let fallback = TaskFallback {
            inner: Arc::clone(&inner),
            identity: identity.clone(),
            state: Arc::clone(&task_state),
        };
        let mut cleanup =
            TaskCleanup::new(Arc::clone(&inner), lease, attachment, producer, task_state);

        let task_body = async move {
            // This is deliberately the task body's first operation: cleanup can then
            // distinguish an executor dropping an unpolled future from a panic after
            // the task started running.
            cleanup.enter_task_body();
            // The admitted input is already a transcript record (admission commits
            // it in runtime/agent/start.rs), so it reaches the model the same way every
            // other record does. `ephemeral` keeps its actual meaning: content
            // that belongs to one request and to no history.
            let lifecycle = LifecycleFanout {
                hooks: &hooks,
                run_states: &run_states,
                identity: &identity,
                session_state: &session_state,
                session_state_writer: cleanup.lease().state(),
                transcript: cleanup.lease().transcript_reader(),
                emitter: &fact_buffer,
            };
            lifecycle.observe(&LifecycleObservation::RunStart {
                coord: identity.clone(),
                input,
            });

            // Admission and `RunStart` both ran synchronous callbacks into the
            // buffer, and no Producer existed then. Draining before Driver work
            // preserves their producer FIFO; the loop then owns every drain in
            // between, and the second drain below picks up `RunEnd`.
            let report = driver::Report::default();
            let admission_failure = publish_admission(
                cleanup.producer(),
                &fact_buffer,
                &lifecycle,
                &admitted_items,
            )
            .await
            .err();
            let driver_terminal = if let Some(error) = admission_failure {
                driver::Terminal::Failed(driver::Error::Event(error))
            } else {
                let callback_resources = run_states
                    .iter()
                    .map(|run_state| {
                        CallbackResources::new(
                            &identity,
                            run_state,
                            &session_state,
                            Some(cleanup.lease().state()),
                            &fact_buffer,
                        )
                    })
                    .collect::<Vec<_>>();
                let controller = TranscriptController::new(
                    cleanup.lease(),
                    &hooks,
                    &reservation_resources,
                    &identity,
                    &fact_buffer,
                );
                let tool_phase = driver::ToolPhase::new(
                    driver::Outward::new(cleanup.producer(), &fact_buffer),
                    &hooks,
                    &callback_resources,
                    &controller,
                    &identity,
                    Some(session.id().to_owned()),
                );
                let inbox = session.input_mailbox();
                let engine = driver::Driver::new(
                    revision.model().as_ref(),
                    cleanup.lease(),
                    &inbox,
                    revision.tools(),
                    &cancellation,
                )
                .with_tool_phase(tool_phase)
                .with_turn_trigger(admitted_items)
                .with_report(&report);
                engine.run(plan, &source).await
            };

            // `Driver::run` is the sole inner join barrier.
            // Construct one immutable pre-fan-out candidate and give that exact
            // observation to every registration while the Lease remains held.
            let stop_code = report.stop_code();
            let candidate =
                terminal_from_driver(&driver_terminal, identity.clone(), stop_code.clone());
            let observation = LifecycleObservation::RunEnd {
                coord: identity.clone(),
                end: lifecycle_end(&candidate),
                turns: report.turns(),
            };
            lifecycle.observe(&observation);
            // RunEnd audits/panic facts append to the same FactBuffer, and the
            // loop has already published everything queued before it. This is the
            // last drain there is, so it is also what carries any fact the loop
            // queued after its own final publication point.
            let run_end_failure =
                publish_buffered_facts(cleanup.producer(), &fact_buffer, Some(&lifecycle))
                    .await
                    .err();

            // Re-observe only validated control/fatal state after peer fan-out.
            // TerminalLatch preserves the first nonfatal and first fatal rules.
            let mut terminal = driver::TerminalLatch::default();
            terminal.record(driver_terminal);
            if let Some(error) = run_end_failure {
                terminal.record(driver::Terminal::Failed(driver::Error::Event(error)));
            }
            let terminal = terminal_from_driver(&terminal.finish(&source), identity, stop_code);

            // Freeze is complete before cancellation. Cleanup then performs the
            // exact cancel -> release -> detach -> event close -> publish order.
            cleanup.complete(terminal);
        };
        let task = tokio::spawn(PanicMarkerFuture::new(task_body, fallback));
        *inner.task.lock().expect("Run task lock poisoned") = Some(task);

        (Self { inner }, returned)
    }
}

impl<M: Client> Run<M> {
    /// Returns the immutable Agent revision frozen for this Run.
    #[must_use]
    pub fn revision(&self) -> Revision<M> {
        self.inner.revision.clone()
    }

    /// Returns the Session owned by this Run.
    #[must_use]
    pub fn session(&self) -> Session {
        self.inner.session.clone()
    }

    /// Takes the unique outward event consumer.
    ///
    /// # Errors
    ///
    /// [`EventsTakenError`] if the [`Stream`] was returned atomically by
    /// [`Agent::start_observed`](super::agent::Agent::start_observed), or has already
    /// been taken by an earlier call through this handle or any clone. Events are
    /// single-consumer, so this is not contention that clears: the one consumer
    /// already exists, and whoever holds it is the only party that can observe the
    /// Run's events.
    ///
    /// # Panics
    ///
    /// If the lock guarding the not-yet-taken [`Stream`] is poisoned, per the
    /// crate-level [lock-poisoning contract](crate#lock-poisoning). It is held
    /// only for the take itself, so nothing a caller or a hook does runs under
    /// it.
    pub fn take_events(&self) -> Result<Stream, EventsTakenError> {
        self.inner
            .events
            .lock()
            .expect("Run event lock poisoned")
            .take()
            .ok_or(EventsTakenError)
    }

    /// Requests a normal stop without waiting or spawning cleanup work.
    ///
    /// # Panics
    ///
    /// If an event-control lock is poisoned, per the crate-level
    /// [lock-poisoning contract](crate#lock-poisoning).
    pub fn request_stop(&self) {
        self.inner.source.request_stop();
    }

    /// Requests a normal stop and waits for complete cleanup.
    ///
    /// # Panics
    ///
    /// If an event-control or Run terminal lock is poisoned, per the crate-level
    /// [lock-poisoning contract](crate#lock-poisoning).
    pub async fn stop(&self) -> Arc<Terminal> {
        self.request_stop();
        self.wait().await
    }

    /// Waits for the shared terminal without requesting a stop.
    ///
    /// Every waiter, on this handle or any clone, receives the same
    /// [`Terminal`], and waiting again after it has resolved returns
    /// immediately. If its [`outcome`](Terminal::outcome) is
    /// [`Failed`](Outcome::Failed), read [`Terminal::failure_kind`] and
    /// [`Terminal::failure`] rather than reporting the outcome alone.
    ///
    /// # Panics
    ///
    /// If the Run terminal lock is poisoned, per the crate-level
    /// [lock-poisoning contract](crate#lock-poisoning).
    pub async fn wait(&self) -> Arc<Terminal> {
        loop {
            let notified = self.inner.done.notified();
            tokio::pin!(notified);
            notified.as_mut().enable();
            if let Some(terminal) = self.inner.terminal() {
                return terminal;
            }
            notified.await;
        }
    }

    /// Abandons an event consumer still owned by this Run, requests stop, and waits.
    ///
    /// A stream returned by [`Agent::start_observed`](super::agent::Agent::start_observed)
    /// is caller-owned, so this method closes the producer but cannot discard that
    /// stream or its already queued events; the caller may drain them to EOF.
    ///
    /// # Panics
    ///
    /// If a Run or event-control lock is poisoned, per the crate-level
    /// [lock-poisoning contract](crate#lock-poisoning).
    pub async fn close(&self) -> Arc<Terminal> {
        self.inner.close_events();
        self.stop().await
    }

    #[cfg(test)]
    pub(super) fn terminal_ready(&self) -> bool {
        self.inner.terminal().is_some()
    }

    #[cfg(test)]
    pub(super) async fn join_tracked_task(&self) -> Result<(), tokio::task::JoinError> {
        let task = self
            .inner
            .task
            .lock()
            .expect("Run task lock poisoned")
            .take()
            .expect("the sole tracked Run task is joined at most once");
        task.await
    }
}

impl<M: Client> RunInner<M> {
    fn close_events(&self) {
        drop(self.events.lock().expect("Run event lock poisoned").take());
    }

    fn terminal(&self) -> Option<Arc<Terminal>> {
        self.terminal
            .lock()
            .expect("Run terminal lock poisoned")
            .clone()
    }

    fn publish(&self, terminal: Arc<Terminal>) {
        let mut slot = self.terminal.lock().expect("Run terminal lock poisoned");
        debug_assert!(slot.is_none(), "the sole Run task publishes once");
        *slot = Some(terminal);
        drop(slot);
        self.done.notify_waiters();
    }
}

/// The Run-scoped half of the observer lifecycle fan-out.
///
/// The driver owns every Turn/Step/Generation/ToolCall observation because it
/// owns those boundaries; `RunStart` and `RunEnd` are the two the Run task owns,
/// and both need the same borrowed resource set. Binding it once keeps the two
/// fan-outs from drifting apart.
pub(super) struct LifecycleFanout<'a> {
    hooks: &'a hook::RuntimeRegistry,
    run_states: &'a [run_state::Store],
    identity: &'a Coord,
    session_state: &'a session_state::Reader,
    session_state_writer: &'a session_state::Writer,
    transcript: crate::transcript::store::SnapshotReader,
    emitter: &'a FactBuffer,
}

impl LifecycleFanout<'_> {
    fn observe_audit(&self, event: &audit::Event) {
        for adapter in self.hooks.observer_hooks() {
            let run_state = self
                .run_states
                .get(adapter.index())
                .expect("Run resources cover every hook registration");
            let resources = CallbackResources::new(
                self.identity,
                run_state,
                self.session_state,
                Some(self.session_state_writer),
                self.emitter,
            );
            adapter.invoke_audit_event(resources, &self.transcript, event);
        }
    }

    fn observe(&self, observation: &LifecycleObservation) {
        for adapter in self.hooks.observer_hooks() {
            let run_state = self
                .run_states
                .get(adapter.index())
                .expect("Run resources cover every hook registration");
            let resources = CallbackResources::new(
                self.identity,
                run_state,
                self.session_state,
                Some(self.session_state_writer),
                self.emitter,
            );
            adapter.invoke_lifecycle(
                resources,
                TranscriptSource::Reader(&self.transcript),
                None,
                observation,
            );
        }
    }
}

/// Attempts to publish admission's outward projections before the loop begins.
///
/// Two facts became true in order. The queued callback facts come from
/// [`RunHooks::prepare`](super::hook::RunHooks::prepare) and
/// [`ObserverHooks::run_admitted`](super::hook::ObserverHooks::run_admitted), which ran with no Producer in existence;
/// the admitted record then opens the Run's first Turn, and its best-effort
/// `InputAdmitted` projection lets an uninterrupted renderer explain input that
/// `prepare` may have rewritten before commit. The authoritative record is already
/// in the Transcript: task destruction before this future is polled, or any other
/// latched interruption, suppresses publication under C18/C20 without undoing it.
///
/// Nothing is published when admission recorded nothing, which happens when the
/// caller submitted no parts and no registration composed any.
async fn publish_admission(
    producer: &Producer,
    buffer: &FactBuffer,
    lifecycle: &LifecycleFanout<'_>,
    admitted: &[Item],
) -> Result<(), ValidationError> {
    publish_buffered_facts(producer, buffer, Some(lifecycle)).await?;
    if admitted.is_empty() {
        return Ok(());
    }
    producer
        .emit_input_admitted(
            InputOrigin::Start,
            admitted.to_vec(),
            lifecycle.identity.clone(),
        )
        .await?;
    Ok(())
}

/// Publishes the Run-owner half of the buffered-fact drain.
///
/// The loop owns the drains taken between `RunStart` and `RunEnd`; this one
/// covers the two edges the loop cannot reach, where the only coordinate that
/// applies is the Run itself and so no event carries one.
pub(super) async fn publish_buffered_facts(
    producer: &Producer,
    buffer: &FactBuffer,
    observers: Option<&LifecycleFanout<'_>>,
) -> Result<(), ValidationError> {
    for fact in buffer.take_facts() {
        let event = match fact {
            BufferedFact::Audit(audit) => {
                // `OnAuditEvent` observes the fact before it is published, so an
                // observer and the outward consumer see the same value and the
                // observer cannot answer an event the consumer already saw.
                if let Some(observers) = observers {
                    observers.observe_audit(&audit);
                }
                Event::from_audit(audit)?
            }
            BufferedFact::Error(error) => Event::from_error(error),
        };
        producer
            .emit(event, None)
            .await
            .expect("a successfully constructed ordinary fact remains valid");
    }
    Ok(())
}

fn terminal_from_driver(
    terminal: &driver::Terminal,
    coord: Coord,
    stop_code: Option<StopCode>,
) -> Terminal {
    match terminal {
        driver::Terminal::Completed => Terminal::new(Outcome::Completed, coord, None),
        // Only a `RunHooks::decide_stop` stop carries a code; a consumer-requested stop
        // has nothing to name itself with.
        driver::Terminal::Stopped => Terminal::new(Outcome::Stopped, coord, stop_code),
        driver::Terminal::Cancelled => Terminal::new(Outcome::Cancelled, coord, None),
        driver::Terminal::Failed(error) => {
            let failure = DriverError::from_loop(error);
            Terminal::failed(coord, failure.kind, Arc::new(failure))
        }
    }
}

fn lifecycle_end(terminal: &Terminal) -> LifecycleEnd {
    match terminal.outcome {
        Outcome::Completed => LifecycleEnd::Completed,
        Outcome::Stopped => LifecycleEnd::Stopped {
            code: terminal.stop_code.clone(),
        },
        Outcome::Cancelled => LifecycleEnd::Cancelled {
            error: Arc::new(CanceledError),
        },
        Outcome::Failed => LifecycleEnd::Failed {
            error: terminal
                .failure
                .as_ref()
                .expect("a failed terminal always retains failure detail")
                .clone(),
        },
    }
}

/// Immutable terminal fact shared by every waiter.
///
/// [`outcome`](Terminal::outcome) is four words wide, so on its own it does not
/// say much: **if it is [`Outcome::Failed`], the reason is one call away.**
/// [`failure_kind`](Terminal::failure_kind) is the matchable classification and
/// [`failure`](Terminal::failure) is the error itself, whose
/// [`source`](Error::source) chain reaches the concrete provider or hook error
/// underneath.
///
/// ```
/// # use reef_core::runtime::run;
/// # use reef_core::value::lifecycle;
/// # fn report(terminal: &run::Terminal) -> String {
/// if terminal.outcome() == lifecycle::Outcome::Failed {
///     // Never report `Failed` on its own: these two say what happened.
///     format!(
///         "failed ({:?}): {}",
///         terminal.failure_kind(),
///         terminal.failure().map_or_else(|| "no detail".to_owned(), ToString::to_string),
///     )
/// } else {
///     format!("{:?}", terminal.outcome())
/// }
/// # }
/// ```
pub struct Terminal {
    outcome: Outcome,
    coord: Coord,
    stop_code: Option<StopCode>,
    failure: Option<Arc<dyn Error + Send + Sync>>,
    failure_kind: Option<FailureKind>,
}

impl fmt::Debug for Terminal {
    /// States how the Run ended, rendering the failure through `Display`.
    ///
    /// The failure is an arbitrary third-party error whose `Debug` this crate
    /// neither writes nor reviews; `Display` is the operator diagnostic the type
    /// is contracted to produce, so that is what a terminal reports.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Terminal")
            .field("outcome", &self.outcome)
            .field("coord", &self.coord)
            .field("stop_code", &self.stop_code)
            .field(
                "failure",
                &self.failure.as_ref().map(|failure| failure.to_string()),
            )
            .field("failure_kind", &self.failure_kind)
            .finish()
    }
}

impl Terminal {
    fn new(outcome: Outcome, coord: Coord, stop_code: Option<StopCode>) -> Self {
        Self {
            outcome,
            coord,
            stop_code,
            failure: None,
            failure_kind: None,
        }
    }

    fn failed(coord: Coord, kind: FailureKind, failure: Arc<dyn Error + Send + Sync>) -> Self {
        Self {
            outcome: Outcome::Failed,
            coord,
            stop_code: None,
            failure: Some(failure),
            failure_kind: Some(kind),
        }
    }

    /// Returns the authoritative portable outcome.
    #[must_use]
    pub const fn outcome(&self) -> Outcome {
        self.outcome
    }

    /// Returns the Run coordinate.
    #[must_use]
    pub const fn coord(&self) -> &Coord {
        &self.coord
    }

    /// Returns an explicit hook stop code when one ended the Run.
    #[must_use]
    pub const fn stop_code(&self) -> Option<&StopCode> {
        self.stop_code.as_ref()
    }

    /// Returns execution failure detail for a failed Run.
    ///
    /// `Some` exactly when [`outcome`](Self::outcome) is
    /// [`Failed`](Outcome::Failed). Its [`Display`](fmt::Display) is already the
    /// complete rendered reason, stage and payload together — reef renders each
    /// failure where it is latched, because the crate-private stage error cannot
    /// outlive the Run and a classification alone does not diagnose anything.
    /// [`source`](Error::source) is therefore for *inspecting* the failure rather
    /// than for re-rendering it: it reaches an underlying model-client, hook,
    /// transcript, or other error that caused the Run to fail. A nonfatal
    /// [`tool::ProviderError`](super::tool::ProviderError) does not appear here;
    /// obtain it from the outward event's
    /// [`as_error`](super::event::Event::as_error) accessor. A chain walk that
    /// concatenates every link will see the tail of the first message repeated,
    /// which is why this is worth stating.
    #[must_use]
    pub fn failure(&self) -> Option<&(dyn Error + Send + Sync + 'static)> {
        self.failure.as_deref()
    }

    /// Returns the portable classification of a failed Run.
    #[must_use]
    pub const fn failure_kind(&self) -> Option<FailureKind> {
        self.failure_kind
    }
}

/// The unique event consumer was already taken or abandoned.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct EventsTakenError;

impl fmt::Display for EventsTakenError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("Run events were already consumed")
    }
}

impl Error for EventsTakenError {}

/// A spawned Run task was dropped by its executor after entering its task body.
///
/// Unlike [`TaskPanickedError`], no panic escaped from a poll of the Run task body.
/// Runtime shutdown is one way this can happen, including shutdown caused by an
/// unrelated panic in a thread hosting the runtime. The Run's terminal is failed,
/// and its Session lease and Agent attachment are released synchronously.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TaskAbortedError;

impl fmt::Display for TaskAbortedError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("Run task was aborted after it started")
    }
}

impl Error for TaskAbortedError {}

/// A spawned Run task was dropped by its executor before entering its task body.
///
/// This can happen when an async runtime shuts down after accepting the spawn but
/// before polling the task. The Run has been admitted, so its terminal is failed
/// and its Session lease and Agent attachment are released synchronously.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TaskNotStartedError;

impl fmt::Display for TaskNotStartedError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("Run task was dropped before it started")
    }
}

impl Error for TaskNotStartedError {}

/// A Run task panicked after entering its task body.
///
/// Its synchronous cleanup publishes this error because the panic bypassed the
/// driver's normal terminal classification. Reef resumes the original panic to
/// the executor after recording this terminal classification.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TaskPanickedError;

impl fmt::Display for TaskPanickedError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("Run task panicked")
    }
}

impl Error for TaskPanickedError {}

#[derive(Debug)]
struct CanceledError;

impl fmt::Display for CanceledError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("Run canceled")
    }
}

impl Error for CanceledError {}

/// The portable classification of a failed Run.
///
/// A Run can fail for reasons that call for very different handling — a
/// provider outage, a malformed provider stream, a hook defect, a transcript
/// conflict — and the concrete failure types belong to crate-private stages that
/// a consumer could not downcast to even if they were exposed. This enum is the
/// stable, matchable summary; [`Terminal::failure`] carries the exact text.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum FailureKind {
    /// A transcript snapshot or mutation failed.
    Transcript,
    /// Resolving the Step's tools failed, usually a name collision.
    ToolResolution,
    /// The transcript could not be frozen into a valid model request.
    Request,
    /// The provider adapter itself failed.
    Model,
    /// The provider's normalized event stream violated the grammar.
    Stream,
    /// An outward event could not be constructed or delivered.
    Event,
    /// A hook callback failed.
    Hook,
    /// Routing or executing a tool batch failed.
    ToolExecution,
    /// Committing a tool batch failed.
    ToolCommit,
    /// A claimed input batch produced an invalid admission decision.
    Input,
    /// A runtime invariant produced a failure with no external cause.
    ///
    /// This is a defect in Reef, not in the caller or the provider.
    Internal,
}

/// The retained reason a Run driver failed.
///
/// The message is rendered from the concrete stage failure at the moment it is
/// latched, because the crate-private staged error itself is not `Clone` and
/// cannot outlive the driver. Rendering eagerly keeps the whole reason — stage,
/// payload, and any hook attribution — instead of the classification alone.
///
/// `cause` keeps the same failure as a *value*. Reading a message is enough to
/// diagnose a Run; deciding what to do about one is not, so the concrete stage
/// failure is retained and returned from [`Error::source`]. A provider error is
/// the consumer's own type, so `source()` is downcastable back to it.
#[derive(Debug)]
struct DriverError {
    kind: FailureKind,
    message: String,
    cause: Option<Arc<dyn Error + Send + Sync>>,
}

impl DriverError {
    fn from_loop(error: &driver::Error) -> Self {
        Self {
            kind: error.classify(),
            message: error.to_string(),
            cause: error.cause(),
        }
    }
}

impl fmt::Display for DriverError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.message)
    }
}

impl Error for DriverError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.cause
            .as_ref()
            .map(|cause| cause.as_ref() as &(dyn Error + 'static))
    }
}