subc-daemon 0.48.1

Embeddable subc daemon: bootstrap, module supervision, and opaque-byte splice routing.
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
//! Spawn-time authority is a verified in-memory view, never a store read under a module gate.

use super::*;
use crate::config_gate::{program, CapturedInput, GateSnapshot, InputKey};
use crate::supervise::ModuleSpec;

// Copy of the supervisor's configured-ID set, not a read of live config files.
// A stamped supervisor derives that set from approved configuration. Readers
// reject an absent or poisoned source without locking its mutable set.
pub(super) struct ConfiguredModuleSnapshot {
    ids: std::collections::HashSet<String>,
    source: std::sync::Weak<Mutex<std::collections::HashSet<String>>>,
}

#[derive(Clone, Debug, PartialEq)]
pub(crate) struct AdmissionCache {
    state: StoreState,
    file_authoritative: bool,
    unstamp_exit_pending: bool,
    modules: BTreeMap<String, ModuleAdmission>,
    fenced: BTreeSet<String>,
}

#[derive(Clone, Debug, PartialEq)]
struct ModuleAdmission {
    evidence: Option<crate::program_origin::ProgramOriginEvidence>,
    approved_declarations: BTreeMap<String, String>,
    program_base: Digest,
    has_active: bool,
    generation: u64,
    held: bool,
    snapshot: GateSnapshot,
    command: Option<ModuleSpec>,
}

/// The program a spawn of a module is admitted under: the approved program
/// record and the development origin evidence placed for it. A spawn's mark
/// holds only while its module is still admitted under the same program; a
/// placement or an approved change of either supersedes it.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct AdmittedProgram {
    program_base: Digest,
    evidence: Option<crate::program_origin::ProgramOriginEvidence>,
}

/// A module as the first-party mark sees it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum MarkView {
    /// The store is in recovery: nothing about the mark changes now.
    Undecided,
    /// The store is unstamped, or the stamped store does not gate the module
    /// (an approved ungated exception): no spawn of it may carry the mark.
    NotGated,
    /// The stamped store gates the module.
    Gated {
        /// The generation whose program record admits the module now.
        generation: u64,
        /// The module declares daemon-delivered configuration, so a spawn
        /// must acknowledge the active generation to be marked.
        delivers_config: bool,
    },
}

impl AdmissionCache {
    /// What the first-party mark reads about `module` from this view.
    pub(super) fn mark_view(&self, module: &str) -> MarkView {
        match self.state {
            StoreState::Unstamped => MarkView::NotGated,
            StoreState::Stamped => match self.modules.get(module) {
                Some(admission) => MarkView::Gated {
                    generation: admission.generation,
                    delivers_config: admission
                        .snapshot
                        .inputs
                        .contains_key(&InputKey::Declaration(module.to_owned())),
                },
                None => MarkView::NotGated,
            },
            _ => MarkView::Undecided,
        }
    }
    pub(super) fn spawn_generation(&self, module: &str) -> Result<u64> {
        self.decision(module)
            .map(|authority| authority.map_or(0, |authority| authority.generation))
    }
    /// The program a spawn of `module` is admitted under now, while the
    /// stamped store gates it. `None` when nothing about it is decided.
    pub(super) fn admitted_program(&self, module: &str) -> Option<AdmittedProgram> {
        (self.state == StoreState::Stamped)
            .then(|| self.modules.get(module))
            .flatten()
            .map(ModuleAdmission::admitted_program)
    }
    pub(super) fn registration_declarations(&self) -> Option<BTreeMap<String, String>> {
        (self.state == StoreState::Stamped).then(|| {
            self.modules
                .iter()
                .map(|(module, authority)| {
                    (
                        module.clone(),
                        super::super::registration::declaration(&authority.snapshot, module).into(),
                    )
                })
                .collect()
        })
    }
    pub(super) fn is_recovering(&self) -> bool {
        matches!(
            self.state,
            StoreState::StoreMissing | StoreState::StoreUnverified
        )
    }
    pub(super) fn held_modules(&self) -> Vec<String> {
        self.modules
            .iter()
            .filter(|(module, authority)| {
                authority.held || (!authority.has_active && self.fenced.contains(*module))
            })
            .map(|(module, _)| module.clone())
            .collect()
    }
    pub(super) fn transitions_from(&self, previous: &Self) -> (Vec<String>, Vec<String>) {
        let recovery = |state| {
            matches!(
                state,
                StoreState::StoreMissing | StoreState::StoreUnverified
            )
        };
        let held = |cache: &Self, module: &str| {
            recovery(cache.state)
                || cache
                    .modules
                    .get(module)
                    .is_some_and(|authority| authority.held)
        };
        let modules: BTreeSet<_> = self
            .modules
            .keys()
            .chain(previous.modules.keys())
            .cloned()
            .collect();
        let mut holds = Vec::new();
        let mut releases = Vec::new();
        for module in modules {
            match (held(previous, &module), held(self, &module)) {
                (false, true) => holds.push(module),
                (true, false) => releases.push(module),
                _ => {}
            }
        }
        (holds, releases)
    }
    pub(super) fn from_store(store: &ConfigStore) -> Self {
        Self::from_store_at(store, store.loaded_admission_state().1.last_generation)
    }

    fn from_store_at(store: &ConfigStore, started_at: u64) -> Self {
        let (state, body) = store.loaded_admission_state();
        let mut cache = Self {
            state,
            file_authoritative: state == StoreState::Unstamped,
            unstamp_exit_pending: false,
            modules: BTreeMap::new(),
            fenced: BTreeSet::new(),
        };
        if cache.state != StoreState::Stamped {
            return cache;
        }
        let Ok(approved) = GateSnapshot::from_store(&body.approved) else {
            cache.state = StoreState::StoreUnverified;
            return cache;
        };
        for module in approved.modules() {
            let versions = body
                .versions
                .iter()
                .find(|(tuple, _)| tuple.module == module && tuple.project.is_none())
                .map(|(_, versions)| versions);
            let pending = versions.and_then(|versions| versions.pending);
            let deferred = pending.is_some_and(|id| {
                id > started_at
                    && body.generations.get(&id).is_some_and(|entry| {
                        super::super::apply::Transition::for_module(
                            &entry.generation.changeset,
                            &module,
                        )
                        .is_ok_and(|transition| {
                            transition == super::super::apply::Transition::DaemonRestart
                        })
                    })
            });
            let generation = versions.and_then(|versions| {
                if deferred {
                    versions.active
                } else {
                    versions.pending.or(versions.active)
                }
            });
            let entry = body
                .generations
                .get(&generation.unwrap_or_else(|| placement::last_approved_generation(body)));
            let mut snapshot = entry
                .and_then(|entry| GateSnapshot::from_store(&entry.configuration).ok())
                .unwrap_or_else(|| approved.clone());
            if cfg!(feature = "dev-placement") {
                placement::overlay_programs(body, &module, &mut snapshot);
            }
            let command = entry
                .and_then(|entry| entry.delivery.as_ref())
                .and_then(|delivery| delivery.daemon.as_ref())
                .and_then(|layer| layer.bytes.as_ref().zip(layer.path.as_ref()))
                .and_then(|(bytes, path)| {
                    std::str::from_utf8(bytes)
                        .ok()
                        .and_then(|doc| crate::daemon_config::parse_with_activity(doc, path).ok())
                })
                .and_then(|(config, _)| {
                    config
                        .modules
                        .into_iter()
                        .find(|configured| configured.module_id == module)
                })
                .map(|configured| configured.module_spec());
            let program_base = program::approved_base(&snapshot, &module);
            let refused = body
                .program_refusals
                .iter()
                .any(|refusal| refusal.module == module && refusal.approved_base == program_base);
            let config_gated = snapshot
                .inputs
                .contains_key(&InputKey::Declaration(module.clone()));
            let channel_unsupported =
                super::super::registration::declaration(&snapshot, &module) == "undeclared";
            cache.modules.insert(
                module.clone(),
                ModuleAdmission {
                    evidence: placement::origin_evidence(body, &module),
                    approved_declarations: body
                        .approved_declarations
                        .get(&module)
                        .cloned()
                        .unwrap_or_default(),
                    program_base,
                    has_active: !config_gated
                        || versions.is_some_and(|versions| versions.active.is_some()),
                    generation: generation.unwrap_or(0),
                    held: refused
                        || channel_unsupported
                        || (deferred && generation.is_none())
                        || (config_gated
                            && versions.is_some_and(|versions| {
                                versions.active.is_none() && versions.pending.is_none()
                            })),
                    snapshot,
                    command,
                },
            );
        }
        cache
    }

    pub(super) fn from_state(state: &OwnerState) -> Self {
        let mut cache = Self::from_store_at(&state.store, state.delivery.started_at_generation());
        cache.unstamp_exit_pending = cache.file_authoritative && state.authority_exit.is_some();
        if state.recovery_exit_hold {
            cache.state = StoreState::StoreUnverified;
        }
        for (module, program_base) in &state.refused_generations {
            if let Some(authority) = cache
                .modules
                .get_mut(module)
                .filter(|authority| authority.program_base == *program_base)
            {
                authority.held = true;
            }
        }
        cache.fenced.extend(state.delivery.fenced_modules());
        cache
    }

    fn decision(&self, module: &str) -> Result<Option<&ModuleAdmission>> {
        if matches!(
            self.state,
            StoreState::StoreMissing | StoreState::StoreUnverified
        ) {
            return Err(GateError::new(
                "config_gated",
                "configuration store is in recovery",
            ));
        }
        if self.state == StoreState::Unstamped {
            return Ok(None);
        }
        let authority = self
            .modules
            .get(module)
            .ok_or_else(|| GateError::new("config_gated", "module is not approved"))?;
        super::super::registration::require_channel_declaration(&authority.snapshot, module)?;
        if authority.held {
            return Err(GateError::new(
                "config_gated",
                "module has no active or pending approved generation",
            ));
        }
        if self.fenced.contains(module) {
            return Err(GateError::new(
                "config_delivery_deferred",
                "exited delivery target is pending reconciliation",
            ));
        }
        Ok(Some(authority))
    }
}

pub(crate) struct SpawnAdmission {
    authority: Option<ModuleAdmission>,
    pub(crate) launch: Option<program::ProgramLaunch>,
}

impl ModuleAdmission {
    fn admitted_program(&self) -> AdmittedProgram {
        AdmittedProgram {
            program_base: self.program_base.clone(),
            evidence: self.evidence.clone(),
        }
    }
}

#[cfg(all(test, unix))]
mod script_origin_tests {
    use super::*;

    #[test]
    fn script_admission_never_inherits_runner_development_origin_or_mark() {
        let root = cortexkit_test_support::ScratchDir::new("script-origin");
        let path = root.join("bundle.js");
        std::fs::write(&path, b"abc").unwrap();
        let spec = ModuleSpec {
            script: Some(crate::ScriptEntry::new(crate::ScriptRuntime::Bun, path)),
            module_id: "example".into(),
            program: crate::supervise::script::runner_path(crate::ScriptRuntime::Bun).unwrap(),
            args: vec![],
            env: vec![],
            reserved: true,
            reserved_prefixes: vec![],
            protocol: subc_control::ModuleProtocol::Subc,
            overlap: Default::default(),
            carry_containment: false,
        };
        let launch = program::capture(&spec, &[]).unwrap();
        let witness = crate::program_origin::LaunchWitness::capture(&spec).unwrap();
        let digest = subc_config::raw_digest(b"approved-script-and-runner");
        let evidence = crate::program_origin::ProgramOriginEvidence {
            origin: subc_protocol::peer::CallerOrigin::Development,
            module_id: "example".into(),
            published_commit: "a".repeat(40),
            program_digest: digest.clone(),
            launch: witness.clone(),
            hosts_third_party_code: Some(false),
            declarations: Default::default(),
        };
        assert_eq!(
            crate::program_origin::derive_origin(Some(&evidence), "example", &digest, &witness),
            subc_protocol::peer::CallerOrigin::Development
        );
        let admission = SpawnAdmission {
            launch: Some(launch),
            authority: Some(ModuleAdmission {
                evidence: Some(evidence),
                approved_declarations: Default::default(),
                program_base: digest,
                has_active: true,
                generation: 1,
                held: false,
                snapshot: Default::default(),
                command: Some(spec),
            }),
        };
        let record = crate::spawn_authority::SpawnAuthorityRecord::new("script-test", 1, "example");
        admission.initialize_origin(&record, &witness);
        assert_eq!(
            record.capture().unwrap().origin,
            subc_protocol::peer::CallerOrigin::Other
        );
        assert!(!record.origin_qualifies_for_mark());
    }
}

impl SpawnAdmission {
    pub(crate) fn initialize_origin(
        &self,
        record: &crate::spawn_authority::SpawnAuthorityRecord,
        witness: &crate::program_origin::LaunchWitness,
    ) {
        if let Some(authority) = &self.authority {
            record.initialize_origin(
                if self
                    .launch
                    .as_ref()
                    .is_some_and(|launch| launch.spec.script.is_some())
                {
                    subc_protocol::peer::CallerOrigin::Other
                } else {
                    crate::program_origin::derive_origin(
                        authority.evidence.as_ref(),
                        record.module_id(),
                        &authority.program_base,
                        witness,
                    )
                },
                authority.approved_declarations.clone(),
                authority
                    .evidence
                    .as_ref()
                    .and_then(|evidence| evidence.hosts_third_party_code),
            );
        }
    }
    pub(crate) fn generation(&self) -> u64 {
        self.authority
            .as_ref()
            .map_or(0, |authority| authority.generation)
    }
    /// The program this spawn is admitted under, when the stamped store
    /// gated its module.
    pub(crate) fn admitted_program(&self) -> Option<AdmittedProgram> {
        self.authority
            .as_ref()
            .map(ModuleAdmission::admitted_program)
    }
    /// The stamped store gated this module at admission.
    pub(crate) fn gated(&self) -> bool {
        self.authority.is_some()
    }
    pub(crate) fn registration_declaration(&self, module: &str) -> Option<String> {
        self.authority.as_ref().map(|authority| {
            super::super::registration::declaration(&authority.snapshot, module).into()
        })
    }
    pub(crate) fn approved_base(&self) -> Option<&Digest> {
        self.authority
            .as_ref()
            .map(|authority| &authority.program_base)
    }
}

impl RuntimeOwner {
    /// Only a committed, still-pending unstamp may stage enabled state while held.
    pub(crate) fn can_stage_unstamp_enable(&self) -> bool {
        self.published
            .read()
            .map(|cache| cache.unstamp_exit_pending)
            .unwrap_or(false)
    }
    /// A committed unstamp permits its definition reconciliation while the
    /// separate recovery admission hold still prevents every child spawn.
    pub(crate) fn file_configuration_is_gated(&self, module: &str) -> bool {
        self.published
            .read()
            .map(|cache| {
                !cache.file_authoritative
                    && match cache.state {
                        StoreState::Stamped => cache.modules.contains_key(module),
                        _ => true,
                    }
            })
            .unwrap_or(true)
    }
    pub(crate) fn observe_supervisor_configured_ids(
        &self,
        ids: Option<&std::collections::HashSet<String>>,
        source: std::sync::Weak<Mutex<std::collections::HashSet<String>>>,
    ) {
        *self
            .configured_modules
            .write()
            .unwrap_or_else(|p| p.into_inner()) = ids.map(|ids| ConfiguredModuleSnapshot {
            ids: ids.clone(),
            source,
        });
    }

    pub(crate) fn module_is_gated(&self, module: &str) -> bool {
        if self.inner.is_poisoned() {
            return true;
        }
        {
            let Ok(cache) = self.published.read() else {
                return true;
            };
            match cache.state {
                StoreState::Unstamped => return false,
                StoreState::Stamped if !cache.modules.contains_key(module) => {}
                _ => return true,
            }
        }
        self.configured_modules
            .read()
            .map(|snapshot| {
                snapshot.as_ref().is_none_or(|snapshot| {
                    snapshot
                        .source
                        .upgrade()
                        .is_none_or(|source| source.is_poisoned())
                        || snapshot.ids.contains(module)
                })
            })
            .unwrap_or(true)
    }

    pub(crate) fn with_legacy_nonce_authority<T>(
        &self,
        module: &str,
        commit: impl FnOnce() -> T,
    ) -> std::result::Result<Option<T>, ()> {
        // Stamping takes this same owner mutex and publishes admission before
        // releasing it. Keep it through the syscall-free accounting mutation,
        // without an OwnerGuard whose drop would wake the delivery worker.
        let _state = self.inner.try_lock().map_err(|_| ())?;
        Ok((!self.module_is_gated(module)).then(commit))
    }
    pub(crate) fn checked_admission_hold(&self, module: Option<&str>) -> Result<()> {
        {
            let mut state = self.lock()?;
            Self::check_authority(&mut state, false)?;
        }
        match module {
            Some(module) => self.check_module_hold(module),
            None => {
                if self
                    .published
                    .read()
                    .is_ok_and(|cache| cache.state == StoreState::Stamped)
                {
                    let _ = self.status();
                }
                self.check_rescan_hold()
            }
        }
    }
    pub(crate) fn take_admission_transitions(&self) -> Result<(Vec<String>, Vec<String>)> {
        let mut state = self.lock()?;
        Ok((
            std::mem::take(&mut state.admission_holds),
            std::mem::take(&mut state.admission_releases),
        ))
    }
    #[cfg(all(test, unix))]
    pub(crate) fn set_spawn_exec_hook_for_test(&self, hook: impl FnOnce() + Send + 'static) {
        *self.spawn_exec_hook.lock().unwrap() = Some(Box::new(hook));
    }
    #[cfg(test)]
    pub(crate) fn before_spawn_exec_for_test(&self) {
        let hook = self.spawn_exec_hook.lock().unwrap().take();
        if let Some(hook) = hook {
            hook();
        }
    }
    pub(crate) fn exit_is_held(&self, module: &str) -> bool {
        self.published
            .read()
            .map(|cache| {
                matches!(
                    cache.state,
                    StoreState::StoreMissing | StoreState::StoreUnverified
                ) || cache.modules.get(module).is_some_and(|authority| {
                    authority.held || (!authority.has_active && cache.fenced.contains(module))
                })
            })
            .unwrap_or(true)
    }
    fn refuse_program(
        &self,
        module: &str,
        base: &Digest,
        inputs: &BTreeMap<InputKey, CapturedInput>,
    ) -> Result<bool> {
        let identity = subc_config::raw_digest(
            &serde_json::to_vec(&inputs.iter().collect::<Vec<_>>()).map_err(GateError::invalid)?,
        );
        self.record_program_refusal(module, base, identity)
    }

    pub(crate) fn record_program_refusal(
        &self,
        module: &str,
        checked_base: &Digest,
        identity: Digest,
    ) -> Result<bool> {
        let mut state = self.lock()?;
        let base = AdmissionCache::from_state(&state)
            .modules
            .get(module)
            .map(|authority| authority.program_base.clone());
        if let Some(base) = base.filter(|current| current == checked_base) {
            state
                .refused_generations
                .insert(module.to_owned(), base.clone());
            let held_modules = AdmissionCache::from_state(&state)
                .held_modules()
                .into_iter()
                .collect();
            state
                .store
                .record_program_refusal(module, base, identity, &held_modules)?;
            return Ok(true);
        }
        Ok(false)
    }
    /// Run before taking a module gate; hashing and integrity checks may block.
    pub(crate) fn prepare_spawn(&self, spec: &ModuleSpec) -> Result<SpawnAdmission> {
        let authority = {
            let mut state = OwnerGuard(
                self.inner.try_lock().map_err(|error| {
                    if matches!(error, std::sync::TryLockError::Poisoned(_)) {
                        return GateError::new(
                            "config_unavailable",
                            "configuration owner is poisoned",
                        );
                    }
                    GateError::new(
                        "config_delivery_deferred",
                        "configuration publication is busy",
                    )
                })?,
                &self.published,
                &self.delivery_changed,
                &self.module_gates,
                self,
            );
            // Store recovery is a launch hold released by the recovery worker.
            // A failed program capture or refusal write is not such a hold.
            if let Err(error) = Self::check_authority(&mut state, false) {
                if AdmissionCache::from_state(&state).is_recovering() {
                    return Err(GateError::new("config_gated", error.detail));
                }
                return Err(error);
            }
            AdmissionCache::from_state(&state)
                .decision(&spec.module_id)?
                .cloned()
        };
        let launch = if let Some(authority) = &authority {
            let entry = authority
                .snapshot
                .inputs
                .get(&InputKey::Entry(spec.module_id.clone()))
                .and_then(|input| match &input.value {
                    subc_config::RecordedValue::Value { value } => Some(value),
                    _ => None,
                })
                .ok_or_else(|| {
                    GateError::new("config_gated", "approved module entry is missing")
                })?;
            let covered = program::program_files(entry)?;
            let command = authority.command.as_ref().ok_or_else(|| {
                GateError::new("config_gated", "approved launch command is unavailable")
            })?;
            let approved: BTreeMap<_, _> = authority.snapshot.inputs.iter()
                .filter(|(key, _)| matches!(key, InputKey::Program { module, .. } if module == &spec.module_id))
                .map(|(key, input)| (key.clone(), input.clone())).collect();
            let launch = match program::capture(command, &covered) {
                Ok(launch) => launch,
                Err(error) => {
                    if program::definite_program_change(&approved) {
                        if !self.record_program_refusal(
                            &spec.module_id,
                            &authority.program_base,
                            subc_config::raw_digest(error.detail.as_bytes()),
                        )? {
                            return Err(GateError::new(
                                "config_delivery_deferred",
                                "program approval changed during capture",
                            ));
                        }
                        return Err(GateError::new("program_refused", error.detail));
                    }
                    return Err(GateError::new("config_delivery_deferred", error.detail));
                }
            };
            if launch.inputs != approved {
                if !self.refuse_program(&spec.module_id, &authority.program_base, &launch.inputs)? {
                    return Err(GateError::new(
                        "config_delivery_deferred",
                        "program approval changed during capture",
                    ));
                }
                return Err(GateError::new(
                    "program_refused",
                    format!(
                        "{}: covered program identity is not approved",
                        spec.module_id
                    ),
                ));
            }
            Some(launch)
        } else {
            None
        };
        Ok(SpawnAdmission { authority, launch })
    }

    pub(crate) fn approved_script(
        &self,
        module: &str,
        path: &std::path::Path,
    ) -> Option<CapturedInput> {
        self.published
            .read()
            .ok()?
            .admission
            .modules
            .get(module)?
            .snapshot
            .inputs
            .get(&InputKey::Program {
                module: module.into(),
                path: path.to_string_lossy().into_owned(),
            })
            .cloned()
    }

    /// Called under exactly one module gate. Only the verified memory copy is read.
    pub(crate) fn check_spawn(&self, module: &str, admission: &SpawnAdmission) -> Result<()> {
        let cache = self
            .published
            .read()
            .map_err(|_| GateError::new("config_gated", "admission authority is unavailable"))?;
        let current = cache.decision(module)?;
        let witness = |authority: &ModuleAdmission| {
            (
                authority.program_base.clone(),
                authority.generation,
                authority.evidence.clone(),
                authority.approved_declarations.clone(),
            )
        };
        if current.map(witness) != admission.authority.as_ref().map(witness) {
            return Err(GateError::new(
                "config_delivery_deferred",
                "configuration changed during spawn preparation",
            ));
        }
        Ok(())
    }

    pub(crate) fn check_module_hold(&self, module: &str) -> Result<()> {
        self.published
            .read()
            .map_err(|_| GateError::new("config_gated", "admission authority is unavailable"))?
            .decision(module)
            .map(|_| ())
    }

    pub(crate) fn has_recorded_admission_hold(&self, module: &str) -> bool {
        !self.inner.is_poisoned()
            && self.published.read().is_ok_and(|view| {
                view.admission.is_recovering()
                    || view
                        .admission
                        .held_modules()
                        .iter()
                        .any(|held| held == module)
            })
    }

    pub(crate) fn with_recorded_admission_hold<T>(
        &self,
        module: &str,
        program_base: Option<&Digest>,
        park: impl FnOnce(Option<String>) -> T,
    ) -> Result<Option<T>> {
        if self.inner.is_poisoned() {
            return Err(GateError::new(
                "config_unavailable",
                "configuration owner is poisoned",
            ));
        }
        let view = self.published.read().map_err(|_| {
            GateError::new(
                "config_unavailable",
                "configuration publication is poisoned",
            )
        })?;
        if program_base.is_some_and(|expected| {
            view.admission
                .modules
                .get(module)
                .is_none_or(|current| &current.program_base != expected)
        }) {
            return Ok(None);
        }
        if !view.admission.is_recovering()
            && !view.admission.fenced.contains(module)
            && !view
                .admission
                .held_modules()
                .iter()
                .any(|held| held == module)
        {
            return Ok(None);
        }
        let refusal = view
            .decision(module)
            .err()
            .filter(|error| error.code == subc_control::REGISTRATION_CHANNEL_UNSUPPORTED)
            .map(|error| error.code);
        // Pin the current recorded hold through the park. A child's content
        // refusal is eligible only while that same program remains approved.
        // A child's exit blocks replacement starts until the worker records which
        // configuration generation failed; completing that record queues release.
        Ok(Some(park(refusal)))
    }

    #[cfg(test)]
    pub(crate) fn pause_before_config_park_for_test(&self) {
        let hook = self.config_park_hook.lock().unwrap().take();
        if let Some(hook) = hook {
            hook();
        }
    }

    pub(crate) fn check_rescan_hold(&self) -> Result<()> {
        let cache = self
            .published
            .read()
            .map_err(|_| GateError::new("config_gated", "admission authority is unavailable"))?;
        if matches!(
            cache.state,
            StoreState::StoreMissing | StoreState::StoreUnverified
        ) {
            return Err(GateError::new(
                "config_gated",
                "configuration store is in recovery",
            ));
        }
        if cache.state == StoreState::Stamped {
            return Err(GateError::new(
                "config_gated",
                "stamped configuration changes require plan and apply, not rescan",
            ));
        }
        Ok(())
    }
}