a3s-code-core 8.0.3

A3S Code Core - Embeddable AI agent library with tool execution
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
use std::fmt;
use std::future::Future;
use std::marker::PhantomData;
use std::sync::{Arc, Mutex, Weak};

use async_trait::async_trait;
use serde::Serialize;
use tokio_util::sync::CancellationToken;

use super::supervisor::{
    remove_registered_child, EffectSupervisor, SupervisedChild, SupervisorInner,
};
use super::{
    CapabilityCeiling, CapabilityEffect, CapabilityEffectError, CapabilityLease,
    CapabilityScopeError, CapabilitySet, RetainedUseGeneration, ScopeClosePolicy, ScopeCloseReport,
    Sha256Digest, SupervisedTaskId, SupervisedTaskSpawner, UseCapabilityGeneration,
    MAX_CAPABILITY_IDENTIFIER_BYTES,
};

/// Closed scope hierarchy used by the capability lifecycle kernel.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum CapabilityScopeKind {
    Session,
    Run,
    Turn,
    Subtask,
}

impl CapabilityScopeKind {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Session => "session",
            Self::Run => "run",
            Self::Turn => "turn",
            Self::Subtask => "subtask",
        }
    }
}

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

mod sealed {
    pub trait Sealed {}
}

/// Sealed marker implemented only by the four supported scope levels.
pub trait ScopeKind: sealed::Sealed + Send + Sync + 'static {
    const KIND: CapabilityScopeKind;
}

#[derive(Debug)]
pub struct Session;

#[derive(Debug)]
pub struct Run;

#[derive(Debug)]
pub struct Turn;

#[derive(Debug)]
pub struct Subtask;

impl sealed::Sealed for Session {}
impl sealed::Sealed for Run {}
impl sealed::Sealed for Turn {}
impl sealed::Sealed for Subtask {}

impl ScopeKind for Session {
    const KIND: CapabilityScopeKind = CapabilityScopeKind::Session;
}

impl ScopeKind for Run {
    const KIND: CapabilityScopeKind = CapabilityScopeKind::Run;
}

impl ScopeKind for Turn {
    const KIND: CapabilityScopeKind = CapabilityScopeKind::Turn;
}

impl ScopeKind for Subtask {
    const KIND: CapabilityScopeKind = CapabilityScopeKind::Subtask;
}

/// Canonical hierarchical scope identity assigned by the Code host.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(transparent)]
pub struct CapabilityScopeId(Box<str>);

impl CapabilityScopeId {
    fn root(
        kind: CapabilityScopeKind,
        local_id: impl Into<String>,
    ) -> Result<Self, CapabilityScopeError> {
        let local_id = local_id.into();
        validate_scope_local_id(&local_id)?;
        Self::from_complete(format!("{kind}/{local_id}"))
    }

    fn child(
        parent: &Self,
        kind: CapabilityScopeKind,
        local_id: impl Into<String>,
    ) -> Result<Self, CapabilityScopeError> {
        let local_id = local_id.into();
        validate_scope_local_id(&local_id)?;
        Self::from_complete(format!("{}/{kind}/{local_id}", parent.as_str()))
    }

    fn from_complete(value: String) -> Result<Self, CapabilityScopeError> {
        if value.len() > MAX_CAPABILITY_IDENTIFIER_BYTES {
            return Err(CapabilityScopeError::BoundExceeded {
                field: "scope_id",
                max: MAX_CAPABILITY_IDENTIFIER_BYTES,
            });
        }
        Ok(Self(value.into_boxed_str()))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

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

struct ParentRegistration {
    supervisor: Weak<SupervisorInner>,
    id: u64,
}

pub(super) struct ScopeInner {
    id: CapabilityScopeId,
    kind: CapabilityScopeKind,
    parent_id: Option<CapabilityScopeId>,
    set: Arc<CapabilitySet>,
    ceiling: CapabilityCeiling,
    use_generation: Option<UseCapabilityGeneration>,
    supervisor: EffectSupervisor,
    parent_registration: Mutex<Option<ParentRegistration>>,
}

impl ScopeInner {
    pub(super) fn id(&self) -> &CapabilityScopeId {
        &self.id
    }

    pub(super) fn parent_id(&self) -> Option<&CapabilityScopeId> {
        self.parent_id.as_ref()
    }

    pub(super) fn set(&self) -> &CapabilitySet {
        &self.set
    }

    pub(super) fn ceiling(&self) -> &CapabilityCeiling {
        &self.ceiling
    }

    pub(super) fn use_generation(&self) -> Option<&UseCapabilityGeneration> {
        self.use_generation.as_ref()
    }

    pub(super) fn supervisor_cancellation(&self) -> CancellationToken {
        self.supervisor.cancellation()
    }

    pub(super) fn ensure_active(&self) -> Result<(), CapabilityScopeError> {
        if !self.supervisor.is_open() {
            return Err(CapabilityScopeError::ScopeInactive {
                scope_id: self.id.to_string(),
            });
        }
        Ok(())
    }

    async fn close(&self) -> Result<ScopeCloseReport, CapabilityScopeError> {
        let report = self.supervisor.close().await?;
        self.detach_from_parent();
        Ok(report)
    }

    fn set_parent_registration(&self, supervisor: Weak<SupervisorInner>, id: u64) {
        *self
            .parent_registration
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner) =
            Some(ParentRegistration { supervisor, id });
    }

    fn detach_from_parent(&self) {
        let registration = self
            .parent_registration
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .take();
        if let Some(registration) = registration {
            remove_registered_child(&registration.supervisor, registration.id);
        }
    }
}

impl fmt::Debug for ScopeInner {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ScopeInner")
            .field("id", &self.id)
            .field("kind", &self.kind)
            .field("parent_id", &self.parent_id)
            .field("catalog_digest", &self.set.digest())
            .field("ceiling", &self.ceiling)
            .field("use_generation", &self.use_generation)
            .field("active", &self.supervisor.is_open())
            .finish()
    }
}

struct ChildScopeOwner {
    inner: Arc<ScopeInner>,
}

#[async_trait]
impl SupervisedChild for ChildScopeOwner {
    fn name(&self) -> &str {
        self.inner.id.as_str()
    }

    fn cancel(&self) {
        self.inner.supervisor.cancel();
    }

    async fn close(self: Box<Self>) -> Result<ScopeCloseReport, CapabilityScopeError> {
        self.inner.close().await
    }
}

/// Typed immutable catalog and monotonic governance scope.
///
/// The value is deliberately not `Clone`: its owner must close it explicitly.
/// Borrowed [`CapabilityLease`] values carry the marker type and cannot outlive
/// this owner. Dropping the owner synchronously cancels and aborts supervised
/// tasks; it never starts asynchronous cleanup.
#[must_use = "capability scopes own effects and must be closed explicitly"]
pub struct CapabilityScope<K: ScopeKind> {
    inner: Arc<ScopeInner>,
    _kind: PhantomData<K>,
}

/// Cloneable weak registration handle for one typed capability scope.
///
/// A handle can transfer tasks and reversible effects into an active scope,
/// and the permitted marker-specific methods can derive child scopes. It does
/// not retain the scope, its immutable catalog generation, or an upstream A3S
/// Use lease. Once the owner closes or drops the scope, every operation fails
/// closed.
pub struct CapabilityScopeHandle<K: ScopeKind> {
    inner: Weak<ScopeInner>,
    id: CapabilityScopeId,
    _kind: PhantomData<K>,
}

impl<K: ScopeKind> Clone for CapabilityScopeHandle<K> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            id: self.id.clone(),
            _kind: PhantomData,
        }
    }
}

impl<K: ScopeKind> fmt::Debug for CapabilityScopeHandle<K> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CapabilityScopeHandle")
            .field("marker", &K::KIND)
            .field("id", &self.id)
            .field("active", &self.is_active())
            .finish()
    }
}

impl<K: ScopeKind> fmt::Debug for CapabilityScope<K> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CapabilityScope")
            .field("marker", &K::KIND)
            .field("inner", &self.inner)
            .finish()
    }
}

impl CapabilityScope<Session> {
    pub fn new_session(
        local_id: impl Into<String>,
        set: Arc<CapabilitySet>,
        ceiling: CapabilityCeiling,
    ) -> Result<Self, CapabilityScopeError> {
        Self::new_session_with_close_policy(local_id, set, ceiling, ScopeClosePolicy::default())
    }

    pub fn new_session_with_close_policy(
        local_id: impl Into<String>,
        set: Arc<CapabilitySet>,
        ceiling: CapabilityCeiling,
        close_policy: ScopeClosePolicy,
    ) -> Result<Self, CapabilityScopeError> {
        Self::new_session_with_close_policy_and_cancellation(
            local_id,
            set,
            ceiling,
            close_policy,
            CancellationToken::new(),
        )
    }

    /// Create a Session scope rooted in a host-owned cancellation tree.
    ///
    /// Every admitted descendant derives its token from this exact root, so a
    /// Run cannot remain active after its host invocation or Session lifetime
    /// has been cancelled.
    pub fn new_session_with_cancellation(
        local_id: impl Into<String>,
        set: Arc<CapabilitySet>,
        ceiling: CapabilityCeiling,
        cancellation: CancellationToken,
    ) -> Result<Self, CapabilityScopeError> {
        Self::new_session_with_close_policy_and_cancellation(
            local_id,
            set,
            ceiling,
            ScopeClosePolicy::default(),
            cancellation,
        )
    }

    pub fn new_session_with_close_policy_and_cancellation(
        local_id: impl Into<String>,
        set: Arc<CapabilitySet>,
        ceiling: CapabilityCeiling,
        close_policy: ScopeClosePolicy,
        cancellation: CancellationToken,
    ) -> Result<Self, CapabilityScopeError> {
        if ceiling.catalog_digest() != set.digest() {
            return Err(CapabilityScopeError::CeilingCatalogMismatch);
        }
        let id = CapabilityScopeId::root(CapabilityScopeKind::Session, local_id)?;
        if cancellation.is_cancelled() {
            return Err(CapabilityScopeError::ScopeInactive {
                scope_id: id.to_string(),
            });
        }
        let supervisor = EffectSupervisor::new(id.to_string(), cancellation, close_policy);
        let use_generation = set.use_capability_generation().cloned();
        Ok(Self {
            inner: Arc::new(ScopeInner {
                id,
                kind: CapabilityScopeKind::Session,
                parent_id: None,
                set,
                ceiling,
                use_generation,
                supervisor,
                parent_registration: Mutex::new(None),
            }),
            _kind: PhantomData,
        })
    }

    /// Admit a Run for a catalog without an upstream A3S Use cursor.
    pub fn admit_run(
        &self,
        local_id: impl Into<String>,
        ceiling: CapabilityCeiling,
    ) -> Result<CapabilityScope<Run>, CapabilityScopeError> {
        if self.inner.use_generation.is_some() {
            return Err(CapabilityScopeError::MissingUseGenerationLease);
        }
        self.create_child(local_id, ceiling, None, None)
    }

    /// Admit a Run while retaining the exact, non-clone A3S Use generation
    /// lease for the complete Run lifetime.
    pub fn admit_use_run<L>(
        &self,
        local_id: impl Into<String>,
        ceiling: CapabilityCeiling,
        lease: L,
    ) -> Result<CapabilityScope<Run>, CapabilityScopeError>
    where
        L: RetainedUseGeneration,
    {
        let Some(expected) = self.inner.use_generation.as_ref() else {
            return Err(CapabilityScopeError::UnexpectedUseGenerationLease);
        };
        let actual = lease.use_generation();
        if actual != expected {
            return Err(CapabilityScopeError::UseGenerationLeaseMismatch {
                expected_generation: expected.generation(),
                actual_generation: actual.generation(),
                revision_mismatch: expected.revision() != actual.revision(),
                registry_revision_mismatch: expected.registry_revision()
                    != actual.registry_revision(),
            });
        }
        self.create_child(
            local_id,
            ceiling,
            Some(Box::new(lease)),
            Some(expected.clone()),
        )
    }
}

impl CapabilityScope<Run> {
    pub fn turn(
        &self,
        local_id: impl Into<String>,
        ceiling: CapabilityCeiling,
    ) -> Result<CapabilityScope<Turn>, CapabilityScopeError> {
        self.create_child(local_id, ceiling, None, self.inner.use_generation.clone())
    }

    pub fn subtask(
        &self,
        local_id: impl Into<String>,
        ceiling: CapabilityCeiling,
    ) -> Result<CapabilityScope<Subtask>, CapabilityScopeError> {
        self.create_child(local_id, ceiling, None, self.inner.use_generation.clone())
    }
}

impl CapabilityScope<Turn> {
    pub fn subtask(
        &self,
        local_id: impl Into<String>,
        ceiling: CapabilityCeiling,
    ) -> Result<CapabilityScope<Subtask>, CapabilityScopeError> {
        self.create_child(local_id, ceiling, None, self.inner.use_generation.clone())
    }
}

impl CapabilityScope<Subtask> {
    /// Start one model/tool Turn inside a delegated execution scope.
    ///
    /// This transition makes the hierarchy recursively composable: a child
    /// Agent can own Turns, whose tool calls can in turn create Subtasks.
    pub fn turn(
        &self,
        local_id: impl Into<String>,
        ceiling: CapabilityCeiling,
    ) -> Result<CapabilityScope<Turn>, CapabilityScopeError> {
        self.create_child(local_id, ceiling, None, self.inner.use_generation.clone())
    }

    pub fn subtask(
        &self,
        local_id: impl Into<String>,
        ceiling: CapabilityCeiling,
    ) -> Result<CapabilityScope<Subtask>, CapabilityScopeError> {
        self.create_child(local_id, ceiling, None, self.inner.use_generation.clone())
    }
}

impl CapabilityScopeHandle<Run> {
    pub fn turn(
        &self,
        local_id: impl Into<String>,
        ceiling: CapabilityCeiling,
    ) -> Result<CapabilityScope<Turn>, CapabilityScopeError> {
        self.create_child(local_id, ceiling)
    }

    pub fn turn_inheriting(
        &self,
        local_id: impl Into<String>,
    ) -> Result<CapabilityScope<Turn>, CapabilityScopeError> {
        self.create_child_inheriting(local_id)
    }

    pub fn subtask(
        &self,
        local_id: impl Into<String>,
        ceiling: CapabilityCeiling,
    ) -> Result<CapabilityScope<Subtask>, CapabilityScopeError> {
        self.create_child(local_id, ceiling)
    }

    pub fn subtask_inheriting(
        &self,
        local_id: impl Into<String>,
    ) -> Result<CapabilityScope<Subtask>, CapabilityScopeError> {
        self.create_child_inheriting(local_id)
    }
}

impl CapabilityScopeHandle<Turn> {
    pub fn subtask(
        &self,
        local_id: impl Into<String>,
        ceiling: CapabilityCeiling,
    ) -> Result<CapabilityScope<Subtask>, CapabilityScopeError> {
        self.create_child(local_id, ceiling)
    }

    pub fn subtask_inheriting(
        &self,
        local_id: impl Into<String>,
    ) -> Result<CapabilityScope<Subtask>, CapabilityScopeError> {
        self.create_child_inheriting(local_id)
    }
}

impl CapabilityScopeHandle<Subtask> {
    pub fn turn(
        &self,
        local_id: impl Into<String>,
        ceiling: CapabilityCeiling,
    ) -> Result<CapabilityScope<Turn>, CapabilityScopeError> {
        self.create_child(local_id, ceiling)
    }

    pub fn turn_inheriting(
        &self,
        local_id: impl Into<String>,
    ) -> Result<CapabilityScope<Turn>, CapabilityScopeError> {
        self.create_child_inheriting(local_id)
    }

    pub fn subtask(
        &self,
        local_id: impl Into<String>,
        ceiling: CapabilityCeiling,
    ) -> Result<CapabilityScope<Subtask>, CapabilityScopeError> {
        self.create_child(local_id, ceiling)
    }

    pub fn subtask_inheriting(
        &self,
        local_id: impl Into<String>,
    ) -> Result<CapabilityScope<Subtask>, CapabilityScopeError> {
        self.create_child_inheriting(local_id)
    }
}

impl<K: ScopeKind> CapabilityScopeHandle<K> {
    pub fn id(&self) -> &CapabilityScopeId {
        &self.id
    }

    pub const fn kind(&self) -> CapabilityScopeKind {
        K::KIND
    }

    pub fn is_active(&self) -> bool {
        self.inner
            .upgrade()
            .is_some_and(|inner| inner.supervisor.is_open())
    }

    pub fn cancellation(&self) -> Result<CancellationToken, CapabilityScopeError> {
        let inner = self.upgrade()?;
        inner.ensure_active()?;
        Ok(inner.supervisor.cancellation())
    }

    pub fn register_effect<E>(&self, effect: E) -> Result<(), CapabilityScopeError>
    where
        E: CapabilityEffect,
    {
        let inner = self.upgrade()?;
        inner.ensure_active()?;
        inner.supervisor.register_effect(Box::new(effect))
    }

    pub fn spawn_task<F>(
        &self,
        name: impl Into<String>,
        task: F,
    ) -> Result<SupervisedTaskId, CapabilityScopeError>
    where
        F: Future<Output = Result<(), CapabilityEffectError>> + Send + 'static,
    {
        let inner = self.upgrade()?;
        inner.ensure_active()?;
        inner.supervisor.spawn_task(name, task)
    }

    pub fn cancel(&self) -> Result<(), CapabilityScopeError> {
        let inner = self.upgrade()?;
        inner.ensure_active()?;
        inner.supervisor.cancel();
        Ok(())
    }

    fn create_child<C: ScopeKind>(
        &self,
        local_id: impl Into<String>,
        ceiling: CapabilityCeiling,
    ) -> Result<CapabilityScope<C>, CapabilityScopeError> {
        let parent = self.upgrade()?;
        create_child_scope(
            &parent,
            local_id,
            ceiling,
            None,
            parent.use_generation.clone(),
        )
    }

    fn create_child_inheriting<C: ScopeKind>(
        &self,
        local_id: impl Into<String>,
    ) -> Result<CapabilityScope<C>, CapabilityScopeError> {
        let parent = self.upgrade()?;
        create_child_scope(
            &parent,
            local_id,
            parent.ceiling.clone(),
            None,
            parent.use_generation.clone(),
        )
    }

    fn upgrade(&self) -> Result<Arc<ScopeInner>, CapabilityScopeError> {
        self.inner
            .upgrade()
            .ok_or_else(|| CapabilityScopeError::ScopeInactive {
                scope_id: self.id.to_string(),
            })
    }
}

impl<K: ScopeKind> CapabilityScope<K> {
    pub fn id(&self) -> &CapabilityScopeId {
        &self.inner.id
    }

    pub const fn kind(&self) -> CapabilityScopeKind {
        K::KIND
    }

    pub fn parent_id(&self) -> Option<&CapabilityScopeId> {
        self.inner.parent_id.as_ref()
    }

    pub fn catalog_digest(&self) -> &Sha256Digest {
        self.inner.set.digest()
    }

    pub fn ceiling(&self) -> &CapabilityCeiling {
        &self.inner.ceiling
    }

    pub fn use_generation(&self) -> Option<&UseCapabilityGeneration> {
        self.inner.use_generation.as_ref()
    }

    pub fn is_active(&self) -> bool {
        self.inner.supervisor.is_open()
    }

    pub fn cancellation(&self) -> CancellationToken {
        self.inner.supervisor.cancellation()
    }

    pub fn handle(&self) -> CapabilityScopeHandle<K> {
        CapabilityScopeHandle {
            inner: Arc::downgrade(&self.inner),
            id: self.inner.id.clone(),
            _kind: PhantomData,
        }
    }

    pub fn lease(&self) -> Result<CapabilityLease<'_, K>, CapabilityScopeError> {
        self.inner.ensure_active()?;
        Ok(CapabilityLease::new(&self.inner))
    }

    pub fn register_effect<E>(&self, effect: E) -> Result<(), CapabilityScopeError>
    where
        E: CapabilityEffect,
    {
        self.inner.supervisor.register_effect(Box::new(effect))
    }

    pub fn spawn_task<F>(
        &self,
        name: impl Into<String>,
        task: F,
    ) -> Result<SupervisedTaskId, CapabilityScopeError>
    where
        F: Future<Output = Result<(), CapabilityEffectError>> + Send + 'static,
    {
        self.inner.supervisor.spawn_task(name, task)
    }

    pub(crate) fn task_spawner(&self) -> SupervisedTaskSpawner {
        self.inner.supervisor.task_spawner()
    }

    pub fn cancel(&self) {
        self.inner.supervisor.cancel();
    }

    pub async fn close(&self) -> Result<ScopeCloseReport, CapabilityScopeError> {
        self.inner.close().await
    }

    fn create_child<C: ScopeKind>(
        &self,
        local_id: impl Into<String>,
        ceiling: CapabilityCeiling,
        generation_lease: Option<Box<dyn RetainedUseGeneration>>,
        use_generation: Option<UseCapabilityGeneration>,
    ) -> Result<CapabilityScope<C>, CapabilityScopeError> {
        create_child_scope(
            &self.inner,
            local_id,
            ceiling,
            generation_lease,
            use_generation,
        )
    }
}

impl<K: ScopeKind> Drop for CapabilityScope<K> {
    fn drop(&mut self) {
        self.inner.supervisor.cancel();
    }
}

fn create_child_scope<C: ScopeKind>(
    parent: &Arc<ScopeInner>,
    local_id: impl Into<String>,
    ceiling: CapabilityCeiling,
    generation_lease: Option<Box<dyn RetainedUseGeneration>>,
    use_generation: Option<UseCapabilityGeneration>,
) -> Result<CapabilityScope<C>, CapabilityScopeError> {
    parent.ensure_active()?;
    ceiling.ensure_within(&parent.ceiling)?;
    let id = CapabilityScopeId::child(&parent.id, C::KIND, local_id)?;
    let cancellation = parent.supervisor.cancellation().child_token();
    let supervisor =
        EffectSupervisor::new(id.to_string(), cancellation, parent.supervisor.policy());
    if let Some(lease) = generation_lease {
        supervisor.register_generation_lease(lease)?;
    }
    let child = Arc::new(ScopeInner {
        id,
        kind: C::KIND,
        parent_id: Some(parent.id.clone()),
        set: Arc::clone(&parent.set),
        ceiling,
        use_generation,
        supervisor,
        parent_registration: Mutex::new(None),
    });
    let registration_id = parent.supervisor.register_child(Box::new(ChildScopeOwner {
        inner: Arc::clone(&child),
    }))?;
    child.set_parent_registration(parent.supervisor.downgrade(), registration_id);
    Ok(CapabilityScope {
        inner: child,
        _kind: PhantomData,
    })
}

fn validate_scope_local_id(value: &str) -> Result<(), CapabilityScopeError> {
    if value.is_empty() {
        return Err(CapabilityScopeError::InvalidScopeId {
            reason: "it is empty",
        });
    }
    if value.len() > MAX_CAPABILITY_IDENTIFIER_BYTES {
        return Err(CapabilityScopeError::BoundExceeded {
            field: "scope_local_id",
            max: MAX_CAPABILITY_IDENTIFIER_BYTES,
        });
    }
    if !value.bytes().all(|byte| {
        byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'-' | b'_' | b'.')
    }) || !value
        .as_bytes()
        .first()
        .is_some_and(u8::is_ascii_alphanumeric)
        || !value
            .as_bytes()
            .last()
            .is_some_and(u8::is_ascii_alphanumeric)
    {
        return Err(CapabilityScopeError::InvalidScopeId {
            reason: "it contains non-canonical characters or boundaries",
        });
    }
    Ok(())
}