basis 0.2.0

The basis SDK: workspace discovery, run lifecycle, one event stream, and the two seams. No protocol, no transport, no TTY.
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
//! Structured task ownership for attached agent work.
//!
//! This module deliberately knows nothing about prompts, models, ACP, or
//! transports. It owns only the facts required to make a child lifecycle
//! finite and observable: an owner, a cancellation signal, a terminal result,
//! and a supervisor that remains responsive while work runs.

use std::{
    collections::{HashMap, HashSet},
    fmt,
    future::Future,
    pin::Pin,
    sync::Arc,
    time::Duration,
};

use serde::{Deserialize, Serialize};
use thiserror::Error;
use tokio::{
    sync::{mpsc, oneshot, watch},
    task::AbortHandle,
    time,
};

type TaskFuture = Pin<Box<dyn Future<Output = Result<Vec<u8>, String>> + Send + 'static>>;
type TaskFactory = Box<dyn FnOnce(TaskContext) -> TaskFuture + Send + 'static>;

/// An identifier unique within one [`Supervisor`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct TaskId(u64);

impl TaskId {
    pub const fn as_u64(self) -> u64 {
        self.0
    }
}

impl fmt::Display for TaskId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "task-{}", self.0)
    }
}

/// The only states a task can expose. `Running` is non-terminal; every other
/// state is terminal and is published at most once.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum TaskState {
    Running,
    Succeeded(Vec<u8>),
    Failed(String),
    Cancelled,
    Orphaned,
}

impl TaskState {
    pub const fn is_terminal(&self) -> bool {
        !matches!(self, Self::Running)
    }
}

/// Errors returned while creating or controlling a task.
#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum LifecycleError {
    #[error("the lifecycle supervisor is closed")]
    Closed,
    #[error("the task id space is exhausted")]
    Exhausted,
    #[error("parent task {0} does not exist")]
    ParentNotFound(TaskId),
    #[error("parent task {0} is no longer running")]
    ParentNotRunning(TaskId),
    #[error("a detached task cannot have an attached parent")]
    DetachedHasParent,
    #[error("task {0} belongs to another supervisor")]
    WrongSupervisor(TaskId),
    #[error("task {0} does not exist")]
    TaskNotFound(TaskId),
}

/// Errors returned by a bounded wait. A timed-out wait is safe to retry: the
/// task's terminal state remains in the supervisor and is never consumed.
#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum WaitError {
    #[error("waiting for {task} exceeded {timeout:?}")]
    Timeout { task: TaskId, timeout: Duration },
    #[error("the lifecycle supervisor closed while waiting")]
    Closed,
}

/// A cancellation observation passed to task work.
#[derive(Clone)]
pub struct Cancellation {
    receiver: watch::Receiver<bool>,
}

impl fmt::Debug for Cancellation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Cancellation")
            .field("cancelled", &*self.receiver.borrow())
            .finish()
    }
}

impl Cancellation {
    pub fn is_cancelled(&self) -> bool {
        *self.receiver.borrow()
    }

    /// Waits until cancellation is requested. The watch channel makes the
    /// check-and-wait race-free and safe to cancel and retry.
    pub async fn cancelled(&self) {
        let mut receiver = self.receiver.clone();
        if *receiver.borrow() {
            return;
        }
        let _ = receiver.changed().await;
    }
}

struct CancellationSource {
    sender: watch::Sender<bool>,
    token: Cancellation,
}

impl CancellationSource {
    fn new() -> Self {
        let (sender, receiver) = watch::channel(false);
        Self {
            sender,
            token: Cancellation { receiver },
        }
    }

    fn cancel(&self) {
        self.sender.send_replace(true);
    }
}

/// Context given to one task's work function.
#[derive(Debug)]
pub struct TaskContext {
    id: TaskId,
    cancellation: Cancellation,
}

impl TaskContext {
    pub const fn id(&self) -> TaskId {
        self.id
    }

    pub fn cancellation(&self) -> Cancellation {
        self.cancellation.clone()
    }
}

/// A capability for observing and cancelling one task. Cloning a handle does
/// not clone or rerun the work; all handles observe the same terminal record.
#[derive(Clone)]
pub struct TaskHandle {
    id: TaskId,
    supervisor: Arc<()>,
    commands: mpsc::Sender<Command>,
    completion: watch::Receiver<Option<TaskState>>,
}

impl fmt::Debug for TaskHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TaskHandle").field("id", &self.id).finish()
    }
}

impl TaskHandle {
    pub const fn id(&self) -> TaskId {
        self.id
    }

    /// Returns the latest state without waiting.
    pub fn state(&self) -> TaskState {
        self.completion
            .borrow()
            .clone()
            .unwrap_or(TaskState::Running)
    }

    /// Waits for a terminal state. The result is repeatable, and a timeout
    /// does not consume it.
    pub async fn wait(&self, timeout: Duration) -> Result<TaskState, WaitError> {
        let mut completion = self.completion.clone();
        let task = self.id;
        let wait = async move {
            loop {
                if let Some(state) = completion.borrow().clone() {
                    return Ok(state);
                }
                completion.changed().await.map_err(|_| WaitError::Closed)?;
            }
        };

        match time::timeout(timeout, wait).await {
            Ok(result) => result,
            Err(_) => Err(WaitError::Timeout { task, timeout }),
        }
    }

    /// Requests cancellation of this task and all attached descendants.
    pub async fn cancel(&self) -> Result<(), LifecycleError> {
        let (reply, result) = oneshot::channel();
        self.commands
            .send(Command::Cancel { id: self.id, reply })
            .await
            .map_err(|_| LifecycleError::Closed)?;
        result.await.map_err(|_| LifecycleError::Closed)?
    }
}

/// The lifecycle supervisor. It is an actor-style command loop: state changes
/// are synchronous inside the loop, while task work runs outside it. This is
/// what keeps cancellation, completion, and control messages moving while a
/// caller waits for a child.
#[derive(Clone)]
pub struct Supervisor {
    commands: mpsc::Sender<Command>,
    identity: Arc<()>,
}

impl fmt::Debug for Supervisor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Supervisor").finish_non_exhaustive()
    }
}

impl Supervisor {
    pub fn new() -> Self {
        let (commands, receiver) = mpsc::channel(128);
        let identity = Arc::new(());
        tokio::spawn(run_supervisor(
            receiver,
            commands.downgrade(),
            Arc::clone(&identity),
        ));
        Self { commands, identity }
    }

    /// Starts work and returns its handle without waiting for completion.
    ///
    /// A child is attached when `parent` is present and `detached` is false.
    /// Detached work must be a new root; accepting a parent for it would make
    /// ownership ambiguous and is rejected structurally.
    pub async fn spawn<F, Fut>(
        &self,
        parent: Option<&TaskHandle>,
        detached: bool,
        work: F,
    ) -> Result<TaskHandle, LifecycleError>
    where
        F: FnOnce(TaskContext) -> Fut + Send + 'static,
        Fut: Future<Output = Result<Vec<u8>, String>> + Send + 'static,
    {
        self.spawn_with_behavior(parent, detached, CancelBehavior::Abort, work)
            .await
    }

    /// Starts cooperatively cancellable work.
    ///
    /// Unlike [`spawn`](Self::spawn), cancellation signals the task and waits
    /// for its future to finish instead of aborting it. The future must observe
    /// [`TaskContext::cancellation`] and finish; this form is for work such as
    /// an agent turn that has its own cancellation token and cleanup contract.
    pub async fn spawn_cooperative<F, Fut>(
        &self,
        parent: Option<&TaskHandle>,
        detached: bool,
        work: F,
    ) -> Result<TaskHandle, LifecycleError>
    where
        F: FnOnce(TaskContext) -> Fut + Send + 'static,
        Fut: Future<Output = Result<Vec<u8>, String>> + Send + 'static,
    {
        self.spawn_with_behavior(parent, detached, CancelBehavior::Cooperative, work)
            .await
    }

    async fn spawn_with_behavior<F, Fut>(
        &self,
        parent: Option<&TaskHandle>,
        detached: bool,
        cancel_behavior: CancelBehavior,
        work: F,
    ) -> Result<TaskHandle, LifecycleError>
    where
        F: FnOnce(TaskContext) -> Fut + Send + 'static,
        Fut: Future<Output = Result<Vec<u8>, String>> + Send + 'static,
    {
        let parent_id = match parent {
            Some(parent) => {
                if !Arc::ptr_eq(&self.identity, &parent.supervisor) {
                    return Err(LifecycleError::WrongSupervisor(parent.id));
                }
                Some(parent.id)
            }
            None => None,
        };

        if detached && parent_id.is_some() {
            return Err(LifecycleError::DetachedHasParent);
        }

        let factory: TaskFactory = Box::new(move |context| Box::pin(work(context)));
        let (reply, result) = oneshot::channel();
        self.commands
            .send(Command::Spawn(SpawnRequest {
                parent: parent_id,
                cancel_behavior,
                factory,
                reply,
            }))
            .await
            .map_err(|_| LifecycleError::Closed)?;
        result.await.map_err(|_| LifecycleError::Closed)?
    }
}

impl Default for Supervisor {
    fn default() -> Self {
        Self::new()
    }
}

enum Command {
    Spawn(SpawnRequest),
    Complete {
        id: TaskId,
        outcome: Result<Vec<u8>, String>,
    },
    Cancel {
        id: TaskId,
        reply: oneshot::Sender<Result<(), LifecycleError>>,
    },
}

struct SpawnRequest {
    parent: Option<TaskId>,
    cancel_behavior: CancelBehavior,
    factory: TaskFactory,
    reply: oneshot::Sender<Result<TaskHandle, LifecycleError>>,
}

#[derive(Clone, Copy)]
enum CancelBehavior {
    Abort,
    Cooperative,
}

struct TaskRecord {
    parent: Option<TaskId>,
    children: HashSet<TaskId>,
    cancellation: CancellationSource,
    cancel_behavior: CancelBehavior,
    cancel_requested: bool,
    completion: watch::Sender<Option<TaskState>>,
    work: Option<TaskState>,
    terminal: Option<TaskState>,
    worker: AbortHandle,
}

async fn run_supervisor(
    mut commands: mpsc::Receiver<Command>,
    command_sender: mpsc::WeakSender<Command>,
    identity: Arc<()>,
) {
    let mut next_id = 1_u64;
    let mut records = HashMap::new();

    while let Some(command) = commands.recv().await {
        match command {
            Command::Spawn(request) => spawn_task(
                &mut next_id,
                &mut records,
                &command_sender,
                identity.clone(),
                request,
            ),
            Command::Complete { id, outcome } => {
                complete_task(id, outcome, &mut records);
            }
            Command::Cancel { id, reply } => {
                let result = if records.contains_key(&id) {
                    cancel_tree(id, &mut records);
                    Ok(())
                } else {
                    Err(LifecycleError::TaskNotFound(id))
                };
                let _ = reply.send(result);
            }
        }
    }

    for record in records.values_mut() {
        record.cancellation.cancel();
        record.worker.abort();
        if record.terminal.is_none() {
            record.terminal = Some(TaskState::Orphaned);
            let _ = record.completion.send(Some(TaskState::Orphaned));
        }
    }
}

fn spawn_task(
    next_id: &mut u64,
    records: &mut HashMap<TaskId, TaskRecord>,
    command_sender: &mpsc::WeakSender<Command>,
    identity: Arc<()>,
    request: SpawnRequest,
) {
    let SpawnRequest {
        parent,
        cancel_behavior,
        factory,
        reply,
    } = request;
    let Some(command_sender) = command_sender.upgrade() else {
        let _ = reply.send(Err(LifecycleError::Closed));
        return;
    };

    if let Some(parent_id) = parent {
        let Some(parent_record) = records.get(&parent_id) else {
            let _ = reply.send(Err(LifecycleError::ParentNotFound(parent_id)));
            return;
        };
        if parent_record.work.is_some() || parent_record.terminal.is_some() {
            let _ = reply.send(Err(LifecycleError::ParentNotRunning(parent_id)));
            return;
        }
    }

    let raw_id = *next_id;
    *next_id = match next_id.checked_add(1) {
        Some(next) => next,
        None => {
            let _ = reply.send(Err(LifecycleError::Exhausted));
            return;
        }
    };
    let id = TaskId(raw_id);
    let cancellation = CancellationSource::new();
    let task_context = TaskContext {
        id,
        cancellation: cancellation.token.clone(),
    };
    let (completion_sender, completion_receiver) = watch::channel(None);
    let worker_commands = command_sender.downgrade();
    let work = tokio::spawn(factory(task_context));
    let worker = work.abort_handle();
    tokio::spawn(async move {
        let outcome = match work.await {
            Ok(outcome) => outcome,
            Err(error) if error.is_cancelled() => return,
            Err(_) => Err("task panicked".to_string()),
        };
        if let Some(commands) = worker_commands.upgrade() {
            let _ = commands.send(Command::Complete { id, outcome }).await;
        }
    });

    let handle = TaskHandle {
        id,
        supervisor: identity,
        commands: command_sender,
        completion: completion_receiver,
    };
    records.insert(
        id,
        TaskRecord {
            parent,
            children: HashSet::new(),
            cancellation,
            cancel_behavior,
            cancel_requested: false,
            completion: completion_sender,
            work: None,
            terminal: None,
            worker,
        },
    );
    if let Some(parent_id) = parent {
        records
            .get_mut(&parent_id)
            .expect("validated parent remains in the supervisor")
            .children
            .insert(id);
    }
    let _ = reply.send(Ok(handle));
}

fn complete_task(
    id: TaskId,
    outcome: Result<Vec<u8>, String>,
    records: &mut HashMap<TaskId, TaskRecord>,
) {
    let (cancel_children, children) = {
        let Some(record) = records.get_mut(&id) else {
            return;
        };
        if record.terminal.is_some() {
            return;
        }

        let state = if record.cancel_requested {
            TaskState::Cancelled
        } else {
            match outcome {
                Ok(bytes) => TaskState::Succeeded(bytes),
                Err(error) => TaskState::Failed(error),
            }
        };
        let cancel_children = matches!(state, TaskState::Failed(_));
        record.work = Some(state);
        (
            cancel_children,
            record.children.iter().copied().collect::<Vec<_>>(),
        )
    };

    if cancel_children {
        for child in children {
            cancel_tree(child, records);
        }
    }
    finalize_if_ready(id, records);
}

fn cancel_tree(id: TaskId, records: &mut HashMap<TaskId, TaskRecord>) {
    let children = records
        .get(&id)
        .map(|record| record.children.iter().copied().collect::<Vec<_>>())
        .unwrap_or_default();
    for child in children {
        cancel_tree(child, records);
    }

    if let Some(record) = records.get_mut(&id)
        && record.terminal.is_none()
    {
        record.cancellation.cancel();
        record.cancel_requested = true;
        if matches!(record.cancel_behavior, CancelBehavior::Abort) {
            record.worker.abort();
            record.work = Some(TaskState::Cancelled);
        }
    }
    finalize_if_ready(id, records);
}

fn finalize_if_ready(id: TaskId, records: &mut HashMap<TaskId, TaskRecord>) {
    let Some((parent, state, completion)) = records.get_mut(&id).and_then(|record| {
        if record.terminal.is_some() || record.work.is_none() || !record.children.is_empty() {
            return None;
        }
        let state = record.work.take().expect("checked above");
        record.terminal = Some(state.clone());
        Some((record.parent, state, record.completion.clone()))
    }) else {
        return;
    };

    let _ = completion.send(Some(state));
    if let Some(parent_id) = parent {
        if let Some(parent_record) = records.get_mut(&parent_id) {
            parent_record.children.remove(&id);
        }
        finalize_if_ready(parent_id, records);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn a_finished_task_can_be_waited_on_repeatedly() {
        let supervisor = Supervisor::new();
        let task = supervisor
            .spawn(None, false, |_context| async { Ok(b"done".to_vec()) })
            .await
            .expect("spawn succeeds");

        let first = task.wait(Duration::from_secs(1)).await.expect("finishes");
        let second = task.wait(Duration::from_secs(1)).await.expect("repeats");

        assert_eq!(first, TaskState::Succeeded(b"done".to_vec()));
        assert_eq!(first, second);
    }

    #[tokio::test]
    async fn a_timed_out_wait_does_not_consume_completion() {
        let supervisor = Supervisor::new();
        let task = supervisor
            .spawn(None, false, |_context| async {
                tokio::time::sleep(Duration::from_millis(20)).await;
                Ok(Vec::new())
            })
            .await
            .expect("spawn succeeds");

        assert!(matches!(
            task.wait(Duration::from_millis(1)).await,
            Err(WaitError::Timeout { .. })
        ));
        assert_eq!(
            task.wait(Duration::from_secs(1)).await.expect("finishes"),
            TaskState::Succeeded(Vec::new())
        );
    }

    #[tokio::test]
    async fn cancellation_is_downward_and_settles_waiters() {
        let supervisor = Supervisor::new();
        let parent = supervisor
            .spawn(None, false, |context| async move {
                context.cancellation().cancelled().await;
                Ok(Vec::new())
            })
            .await
            .expect("parent spawns");
        let child = supervisor
            .spawn(Some(&parent), false, |context| async move {
                context.cancellation().cancelled().await;
                Ok(Vec::new())
            })
            .await
            .expect("child spawns");

        parent.cancel().await.expect("cancellation accepted");

        assert_eq!(
            parent
                .wait(Duration::from_secs(1))
                .await
                .expect("parent settles"),
            TaskState::Cancelled
        );
        assert_eq!(
            child
                .wait(Duration::from_secs(1))
                .await
                .expect("child settles"),
            TaskState::Cancelled
        );
    }

    #[tokio::test]
    async fn an_attached_child_keeps_a_successful_parent_scope_open() {
        let supervisor = Supervisor::new();
        let (release_parent, parent_gate) = oneshot::channel();
        let parent = supervisor
            .spawn(None, false, move |_context| async move {
                parent_gate
                    .await
                    .map_err(|_| "parent gate closed".to_string())?;
                Ok(b"parent".to_vec())
            })
            .await
            .expect("parent spawns");
        let child = supervisor
            .spawn(Some(&parent), false, |_context| async {
                tokio::time::sleep(Duration::from_millis(20)).await;
                Ok(b"child".to_vec())
            })
            .await
            .expect("child spawns while parent is running");

        release_parent.send(()).expect("parent gate is open");

        assert_eq!(
            child
                .wait(Duration::from_secs(1))
                .await
                .expect("child finishes"),
            TaskState::Succeeded(b"child".to_vec())
        );
        assert_eq!(
            parent
                .wait(Duration::from_secs(1))
                .await
                .expect("parent waits for child"),
            TaskState::Succeeded(b"parent".to_vec())
        );
    }

    #[tokio::test]
    async fn a_parent_cannot_accept_work_after_its_work_finished() {
        let supervisor = Supervisor::new();
        let parent = supervisor
            .spawn(None, false, |_context| async { Ok(Vec::new()) })
            .await
            .expect("parent spawns");
        parent.wait(Duration::from_secs(1)).await.expect("finishes");

        let error = supervisor
            .spawn(Some(&parent), false, |_context| async { Ok(Vec::new()) })
            .await
            .expect_err("a terminal parent cannot own a child");
        assert_eq!(error, LifecycleError::ParentNotRunning(parent.id()));
    }

    #[tokio::test]
    async fn a_detached_task_must_be_a_new_root() {
        let supervisor = Supervisor::new();
        let parent = supervisor
            .spawn(None, false, |_context| async { Ok(Vec::new()) })
            .await
            .expect("parent spawns");

        let error = supervisor
            .spawn(Some(&parent), true, |_context| async { Ok(Vec::new()) })
            .await
            .expect_err("detached children are ambiguous");
        assert_eq!(error, LifecycleError::DetachedHasParent);
    }

    #[tokio::test]
    async fn handles_cannot_cross_supervisors() {
        let first = Supervisor::new();
        let second = Supervisor::new();
        let parent = first
            .spawn(None, false, |_context| async { Ok(Vec::new()) })
            .await
            .expect("parent spawns");

        let error = second
            .spawn(Some(&parent), false, |_context| async { Ok(Vec::new()) })
            .await
            .expect_err("foreign handles are rejected");
        assert_eq!(error, LifecycleError::WrongSupervisor(parent.id()));
    }

    #[tokio::test]
    async fn cooperative_cancellation_waits_for_cleanup() {
        let supervisor = Supervisor::new();
        let (cleanup_started, cleanup_seen) = oneshot::channel();
        let (release_cleanup, cleanup_gate) = oneshot::channel();
        let task = supervisor
            .spawn_cooperative(None, false, move |context| async move {
                context.cancellation().cancelled().await;
                cleanup_started.send(()).expect("observer is waiting");
                cleanup_gate
                    .await
                    .map_err(|_| "cleanup gate closed".to_string())?;
                Ok(Vec::new())
            })
            .await
            .expect("task spawns");

        task.cancel().await.expect("cancellation accepted");
        cleanup_seen.await.expect("cleanup starts");
        assert_eq!(task.state(), TaskState::Running);

        release_cleanup.send(()).expect("cleanup is waiting");
        assert_eq!(
            task.wait(Duration::from_secs(1)).await.expect("settles"),
            TaskState::Cancelled
        );
    }

    #[tokio::test]
    async fn a_panicking_task_reaches_a_terminal_failure() {
        let supervisor = Supervisor::new();
        let task = supervisor
            .spawn(None, false, |_context| async {
                panic!("boom");
                #[allow(unreachable_code)]
                Ok(Vec::new())
            })
            .await
            .expect("task spawns");

        assert_eq!(
            task.wait(Duration::from_secs(1)).await.expect("settles"),
            TaskState::Failed("task panicked".to_string())
        );
    }
}