Skip to main content

bamboo_engine/external_agents/
local_task.rs

1//! Native Child execution in the Host process. Identity, input, history and
2//! terminal publication still belong to the canonical Actor/Session stores.
3//! There is no broker, Worker IPC, or remote fallback in this backend.
4use super::runtime::NativeToolCeilingSource;
5use crate::execution::spawn::{ExternalChildRunner, SessionInboxRuntimeBinding, SpawnJob};
6use crate::runtime::{Agent, ExecuteRequestBuilder};
7use async_trait::async_trait;
8use bamboo_agent_core::tools::ToolExecutor;
9use bamboo_agent_core::{AgentError, AgentEvent, Session};
10use bamboo_domain::{
11    ActorActivationClaim, ActorActivationFinish, ActorDirectoryPort, ChildActorRuntimeWrite,
12    RuntimeSessionPersistence, SessionKind, Storage,
13};
14use bamboo_llm::{Config, ProviderModelRouter};
15use futures::FutureExt;
16use std::{
17    collections::HashMap,
18    path::PathBuf,
19    sync::{
20        atomic::{AtomicBool, Ordering},
21        Arc, Mutex,
22    },
23    time::Duration,
24};
25use tokio::sync::{mpsc, Semaphore};
26use tokio_util::sync::CancellationToken;
27
28#[derive(Clone)]
29pub struct LocalTaskRuntime {
30    pub agent: Arc<Agent>,
31    /// The Host's complete permission-checking base chain, without the Root role fence.
32    pub tools: Arc<dyn ToolExecutor>,
33    pub provider_router: Option<Arc<ProviderModelRouter>>,
34    pub app_data_dir: Option<PathBuf>,
35    pub sessions_cache: crate::SessionCache,
36}
37
38mod local_skill_binding;
39pub use local_skill_binding::{
40    LocalChildSkillAuthority, LocalChildSkillBinding, LocalChildSkillFactory,
41};
42
43#[derive(Default)]
44struct Bindings {
45    skills: Option<Arc<dyn LocalChildSkillFactory>>,
46    runtime: Option<LocalTaskRuntime>,
47    inbox: Option<SessionInboxRuntimeBinding>,
48    store: Option<Arc<bamboo_storage::SessionStoreV2>>,
49    tickets: Option<Arc<bamboo_tickets::TicketService>>,
50    subagent: Option<Arc<dyn bamboo_agent_core::tools::Tool>>,
51    observer: Option<Arc<dyn super::actor_event_stream::ActorEventObserver>>,
52}
53
54/// Constructed only after the actual Agent task was joined and its owned
55/// resources drained. A request to cancel, a PID, and a durable status cannot
56/// manufacture this value.
57#[derive(Clone, Debug)]
58pub struct ConfirmedTaskStop {
59    session_id: String,
60    child_birth: chrono::DateTime<chrono::Utc>,
61    run_id: String,
62    instance_id: uuid::Uuid,
63}
64impl ConfirmedTaskStop {
65    pub(crate) fn session_id(&self) -> &str {
66        &self.session_id
67    }
68    pub(crate) fn child_birth(&self) -> chrono::DateTime<chrono::Utc> {
69        self.child_birth
70    }
71    pub(crate) fn run_id(&self) -> &str {
72        &self.run_id
73    }
74    pub(crate) fn instance_id(&self) -> uuid::Uuid {
75        self.instance_id
76    }
77}
78
79struct ExecutionOutput {
80    session: Session,
81    result: crate::runtime::runner::Result<()>,
82    resources: std::io::Result<bamboo_tools::DrainedLocalTaskResources>,
83}
84#[derive(Clone, Copy, PartialEq, Eq)]
85enum LaunchState {
86    Queued,
87    Preparing,
88    Running,
89    Stopping,
90    Stopped,
91}
92
93struct Execution {
94    owner: ChildActorRuntimeWrite,
95    persistence: Arc<dyn RuntimeSessionPersistence>,
96    cancel: CancellationToken,
97    resources: bamboo_tools::LocalTaskResources,
98    task: tokio::sync::Mutex<Option<tokio::task::JoinHandle<ExecutionOutput>>>,
99    stop: Mutex<Option<ConfirmedTaskStop>>,
100    finalized: AtomicBool,
101    launch: Mutex<LaunchState>,
102    admission: Mutex<Option<tokio::sync::OwnedSemaphorePermit>>,
103    slot: Mutex<Option<tokio::sync::OwnedSemaphorePermit>>,
104    launch_handoff: tokio::sync::watch::Sender<bool>,
105    heartbeat_stop: CancellationToken,
106    heartbeat: tokio::sync::Mutex<Option<tokio::task::JoinHandle<()>>>,
107}
108
109impl Execution {
110    async fn persist_stop_unconfirmed(&self) -> Result<Session, String> {
111        // The same birth/fence-bound writer owns this narrow observation. A
112        // task panic must never checkpoint its partially mutated transcript.
113        let mut current = self
114            .persistence
115            .load_runtime_control_plane(&self.owner.fence.actor_id)
116            .await
117            .map_err(|e| e.to_string())?
118            .ok_or("Child missing while recording unconfirmed stop")?;
119        let same_observation = current
120            .metadata
121            .get("runtime.local_task.state")
122            .map(String::as_str)
123            == Some("stop_unconfirmed")
124            && current.metadata.get("runtime.local_task.run_id") == Some(&self.owner.fence.run_id)
125            && current.metadata.get("runtime.local_task.child_birth")
126                == Some(&self.owner.created_at.to_rfc3339())
127            && current
128                .metadata
129                .get("runtime.local_task.reason")
130                .map(String::as_str)
131                == Some("execution_stop_unconfirmed")
132            && current
133                .metadata
134                .get("runtime.local_task.observed_at")
135                .is_some_and(|value| chrono::DateTime::parse_from_rfc3339(value).is_ok());
136        if !same_observation {
137            record_local_task_observation(
138                &mut current,
139                &self.owner.fence.run_id,
140                self.owner.created_at,
141                "stop_unconfirmed",
142            );
143            current.metadata.insert(
144                "runtime.local_task.reason".into(),
145                "execution_stop_unconfirmed".into(),
146            );
147        }
148        current.metadata.remove("runtime.local_task.instance");
149        self.persistence
150            .save_runtime_control_plane(&mut current)
151            .await
152            .map_err(|e| e.to_string())?;
153        let readback = self
154            .persistence
155            .load_runtime_control_plane(&self.owner.fence.actor_id)
156            .await
157            .map_err(|e| e.to_string())?
158            .ok_or("Child missing after unconfirmed-stop checkpoint")?;
159        if LOCAL_TASK_OBSERVATION_KEYS
160            .iter()
161            .any(|key| current.metadata.get(*key) != readback.metadata.get(*key))
162        {
163            return Err("unconfirmed-stop checkpoint readback differs".into());
164        }
165        Ok(readback)
166    }
167
168    async fn wait_for_handoff(&self) {
169        let mut handoff = self.launch_handoff.subscribe();
170        while !*handoff.borrow_and_update() {
171            // This Execution owns the sender, so cancellation of any other
172            // waiter cannot close it or consume another waiter's wakeup.
173            handoff
174                .changed()
175                .await
176                .expect("execution retains handoff sender");
177        }
178    }
179}
180
181pub struct LocalTaskChildRunner {
182    bindings: Mutex<Bindings>,
183    executions: Mutex<HashMap<String, Arc<Execution>>>,
184    coordinators: Mutex<Vec<CoordinatorHandle>>,
185    coordinator_errors: Mutex<Vec<String>>,
186    concurrency: Arc<Semaphore>,
187    admission: Arc<Semaphore>,
188    preparations: Arc<Semaphore>,
189    closed: AtomicBool,
190    ceiling: Option<Arc<dyn NativeToolCeilingSource>>,
191    permission: Option<Arc<bamboo_tools::permission::PermissionConfig>>,
192    remote_roles: Vec<String>,
193    approval_registry: Option<super::approval_registry::SharedApprovalRegistry>,
194    approval_reviewer: Option<Arc<dyn super::actor_adapter::ChildApprovalReviewer>>,
195}
196
197type CoordinatorHandle = tokio::task::JoinHandle<Result<(), String>>;
198
199/// Shutdown may be cancelled while a publication tail still owns a writer.
200/// Keep the real join handle available to the next shutdown attempt.
201struct RetainedCoordinatorJoin<'a> {
202    queue: &'a Mutex<Vec<CoordinatorHandle>>,
203    handle: Option<CoordinatorHandle>,
204}
205impl Drop for RetainedCoordinatorJoin<'_> {
206    fn drop(&mut self) {
207        if let Some(handle) = self.handle.take() {
208            lock(self.queue).push(handle);
209        }
210    }
211}
212
213fn failure(error: impl std::fmt::Display) -> AgentError {
214    AgentError::LLM(format!("local task backend: {error}"))
215}
216const LOCAL_TASK_OBSERVATION_KEYS: [&str; 6] = [
217    "runtime.local_task.state",
218    "runtime.local_task.run_id",
219    "runtime.local_task.child_birth",
220    "runtime.local_task.observed_at",
221    "runtime.local_task.reason",
222    "runtime.local_task.instance",
223];
224
225fn record_local_task_observation(
226    session: &mut Session,
227    run_id: &str,
228    child_birth: chrono::DateTime<chrono::Utc>,
229    state: &str,
230) {
231    for key in LOCAL_TASK_OBSERVATION_KEYS {
232        session.metadata.remove(key);
233    }
234    session
235        .metadata
236        .insert("runtime.local_task.state".into(), state.into());
237    session
238        .metadata
239        .insert("runtime.local_task.run_id".into(), run_id.into());
240    session.metadata.insert(
241        "runtime.local_task.child_birth".into(),
242        child_birth.to_rfc3339(),
243    );
244    session.metadata.insert(
245        "runtime.local_task.observed_at".into(),
246        chrono::Utc::now().to_rfc3339(),
247    );
248}
249
250fn copy_local_task_observation(from: &Session, to: &mut Session) {
251    for key in LOCAL_TASK_OBSERVATION_KEYS {
252        match from.metadata.get(key) {
253            Some(value) => {
254                to.metadata.insert(key.into(), value.clone());
255            }
256            None => {
257                to.metadata.remove(key);
258            }
259        }
260    }
261}
262
263fn record_stop_metadata(session: &mut Session, proof: &ConfirmedTaskStop) {
264    record_local_task_observation(session, &proof.run_id, proof.child_birth, "stopped");
265    session.metadata.insert(
266        "runtime.local_task.instance".into(),
267        proof.instance_id.to_string(),
268    );
269    session
270        .metadata
271        .insert("runtime.local_task.run_id".into(), proof.run_id.clone());
272    if session
273        .metadata
274        .get(bamboo_subagent::proto::WORKFLOW_USAGE_REQUESTED_KEY)
275        .is_some_and(|v| v == "true")
276    {
277        session.metadata.insert(
278            bamboo_subagent::proto::WORKFLOW_TERMINAL_OBSERVATION_KEY.into(),
279            proof.run_id.clone(),
280        );
281    }
282}
283
284fn reconcile_question_handoff(session: &mut Session, previous_request: Option<&str>) {
285    let issued_here = session
286        .metadata
287        .get(bamboo_domain::PARENT_QUESTION_REQUEST_KEY)
288        .is_some_and(|request| Some(request.as_str()) != previous_request);
289    if issued_here {
290        // Preserve this run's handoff even if a fast parent answer already
291        // cleared pending_question before the Agent returned.
292        session.metadata.insert(
293            "runtime.actor_parent_question_handoff".into(),
294            "true".into(),
295        );
296    } else {
297        session
298            .metadata
299            .remove("runtime.actor_parent_question_handoff");
300    }
301}
302
303fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
304    mutex.lock().unwrap_or_else(|error| error.into_inner())
305}
306
307impl LocalTaskChildRunner {
308    fn retain_shutdown_error(&self, error: String) {
309        let mut errors = lock(&self.coordinator_errors);
310        if !errors.contains(&error) {
311            errors.push(error);
312        }
313    }
314
315    pub fn new(
316        config: &Config,
317        ceiling: Option<Arc<dyn NativeToolCeilingSource>>,
318        permission: Option<Arc<bamboo_tools::permission::PermissionConfig>>,
319    ) -> Self {
320        Self {
321            bindings: Mutex::new(Bindings::default()),
322            executions: Mutex::new(HashMap::new()),
323            coordinators: Mutex::new(Vec::new()),
324            coordinator_errors: Mutex::new(Vec::new()),
325            concurrency: Arc::new(Semaphore::new(
326                config
327                    .subagents()
328                    .max_concurrent
329                    .unwrap_or(super::actor_adapter::DEFAULT_MAX_CONCURRENT_ACTORS)
330                    .max(1),
331            )),
332            admission: Arc::new(Semaphore::new(
333                config
334                    .subagents()
335                    .max_concurrent
336                    .unwrap_or(super::actor_adapter::DEFAULT_MAX_CONCURRENT_ACTORS)
337                    .max(1)
338                    .saturating_add(128),
339            )),
340            preparations: Arc::new(Semaphore::new(128)),
341            closed: AtomicBool::new(false),
342            ceiling,
343            permission,
344            approval_registry: None,
345            approval_reviewer: None,
346            remote_roles: config
347                .subagents()
348                .remote_placements
349                .iter()
350                .map(|p| p.role.clone())
351                .chain(
352                    config
353                        .subagents()
354                        .schedulable_placements
355                        .iter()
356                        .map(|p| p.role.clone()),
357                )
358                .collect(),
359        }
360    }
361    pub fn with_approval(
362        mut self,
363        registry: Option<super::approval_registry::SharedApprovalRegistry>,
364        reviewer: Option<Arc<dyn super::actor_adapter::ChildApprovalReviewer>>,
365    ) -> Self {
366        self.approval_registry = registry;
367        self.approval_reviewer = reviewer;
368        self
369    }
370    async fn stop_unstarted(
371        &self,
372        execution: &Execution,
373        session: &mut Session,
374        run_id: &str,
375    ) -> Result<(), String> {
376        {
377            let mut state = lock(&execution.launch);
378            match *state {
379                LaunchState::Queued | LaunchState::Preparing => *state = LaunchState::Stopping,
380                LaunchState::Stopped => return Ok(()),
381                _ => return Err("local execution launch or stop is already in progress".into()),
382            }
383        }
384        let drained = execution
385            .resources
386            .close_and_drain()
387            .await
388            .map_err(|e| e.to_string())?;
389        let identity = drained.identity();
390        if identity.session_id != session.id
391            || identity.run_id != run_id
392            || identity.child_birth != session.created_at
393        {
394            return Err("local resource identity changed during rollback".into());
395        }
396        let proof = ConfirmedTaskStop {
397            session_id: session.id.clone(),
398            child_birth: session.created_at,
399            run_id: run_id.into(),
400            instance_id: identity.owner_id,
401        };
402        record_stop_metadata(session, &proof);
403        *lock(&execution.stop) = Some(proof);
404        *lock(&execution.launch) = LaunchState::Stopped;
405        Ok(())
406    }
407    fn execution(&self, session: &Session, run_id: &str) -> Result<Arc<Execution>, String> {
408        let execution = lock(&self.executions)
409            .get(&session.id)
410            .cloned()
411            .ok_or("local execution ownership is missing")?;
412        if execution.owner.created_at != session.created_at
413            || execution.owner.fence.run_id != run_id
414        {
415            return Err("local execution birth or generation changed".into());
416        }
417        Ok(execution)
418    }
419    fn runtime(&self) -> Result<LocalTaskRuntime, String> {
420        lock(&self.bindings)
421            .runtime
422            .clone()
423            .ok_or("Host local task runtime is unavailable".into())
424    }
425}
426
427#[async_trait]
428impl ExternalChildRunner for LocalTaskChildRunner {
429    fn supports_native_ticket_budget(&self) -> bool {
430        true
431    }
432
433    fn set_local_child_skill_factory(&self, factory: Option<Arc<dyn LocalChildSkillFactory>>) {
434        lock(&self.bindings).skills = factory;
435    }
436    fn set_local_task_runtime(&self, runtime: Option<LocalTaskRuntime>) {
437        lock(&self.bindings).runtime = runtime;
438    }
439    fn set_session_inbox_runtime(&self, inbox: Option<SessionInboxRuntimeBinding>) {
440        lock(&self.bindings).inbox = inbox;
441    }
442    fn set_actor_directory_store(&self, store: Option<Arc<bamboo_storage::SessionStoreV2>>) {
443        lock(&self.bindings).store = store;
444    }
445    fn set_ticket_service(&self, service: Option<Arc<bamboo_tickets::TicketService>>) {
446        let mut bindings = lock(&self.bindings);
447        // Serialize this check with the successful drain's cache release. A
448        // late scope publisher must not reattach a writer to a closed runner.
449        if service.is_some() && self.closed.load(Ordering::Acquire) {
450            return;
451        }
452        bindings.tickets = service;
453    }
454    fn set_canonical_subagent_tool(&self, tool: Option<Arc<dyn bamboo_agent_core::tools::Tool>>) {
455        lock(&self.bindings).subagent = tool;
456    }
457    fn set_actor_event_observer(
458        &self,
459        observer: Option<Arc<dyn super::actor_event_stream::ActorEventObserver>>,
460    ) {
461        lock(&self.bindings).observer = observer;
462    }
463
464    async fn should_handle(&self, session: &Session) -> bool {
465        session.kind == SessionKind::Child
466            && session
467                .metadata
468                .get("external.agent_id")
469                .is_none_or(|id| id == super::config::LOCAL_ACTOR_AGENT_ID)
470            && !self
471                .remote_roles
472                .iter()
473                .any(|role| session.metadata.get("subagent_type") == Some(role))
474    }
475    async fn validate_required_child_context_route(&self, session: &Session) -> Result<(), String> {
476        // Admission probes use a synthetic Child before its durable birth.
477        // Check only its configured route here; execution separately proves
478        // the canonical Child, lineage and activation ownership.
479        if session
480            .metadata
481            .get("external.agent_id")
482            .is_some_and(|id| id != super::config::LOCAL_ACTOR_AGENT_ID)
483            || self
484                .remote_roles
485                .iter()
486                .any(|role| session.metadata.get("subagent_type") == Some(role))
487            || self.ceiling.is_none()
488        {
489            return Err(
490                "required_child_context_unsupported: local native ceiling unavailable".into(),
491            );
492        }
493        self.runtime()?;
494        let bindings = lock(&self.bindings);
495        if bindings.store.is_none() || bindings.inbox.is_none() {
496            return Err("canonical local Child storage is unavailable".into());
497        }
498        Ok(())
499    }
500
501    async fn prepare_child_execution(
502        &self,
503        session: &Session,
504        run_id: &str,
505        cancel: CancellationToken,
506    ) -> Result<Option<Arc<dyn RuntimeSessionPersistence>>, String> {
507        let _preparation = self
508            .preparations
509            .clone()
510            .try_acquire_owned()
511            .map_err(|_| "local Child preparation capacity exhausted")?;
512        if self.closed.load(Ordering::Acquire) {
513            return Err("local task backend is shutting down".into());
514        }
515        // Keep scheduler backpressure: an accepted setup waits for bounded
516        // capacity instead of detaching an unbounded pending coordinator.
517        let admission = tokio::select! {
518            biased;
519            _ = cancel.cancelled() => return Err("local Child cancelled before admission".into()),
520            permit = self.admission.clone().acquire_owned() => permit.map_err(|_| "local task backend is shutting down")?,
521        };
522        let runtime = self.runtime()?;
523        let (store, inbox) = {
524            let bindings = lock(&self.bindings);
525            (
526                bindings
527                    .store
528                    .clone()
529                    .ok_or("canonical local Actor store unavailable")?,
530                bindings
531                    .inbox
532                    .clone()
533                    .ok_or("canonical local Inbox unavailable")?,
534            )
535        };
536        if !inbox.router.owns_run(&session.id, run_id).await {
537            return Err("local Child activation is not owned by this Host run".into());
538        }
539        if lock(&self.executions).contains_key(&session.id) {
540            return Err("previous local execution has not been finalized".into());
541        }
542        let durable = store
543            .load_session(&session.id)
544            .await
545            .map_err(|e| e.to_string())?
546            .ok_or("canonical Child is missing")?;
547        if durable.created_at != session.created_at
548            || durable.parent_created_at != session.parent_created_at
549            || durable.parent_session_id != session.parent_session_id
550            || durable.root_session_id != session.root_session_id
551            || durable.project_id_meta() != session.project_id_meta()
552        {
553            return Err("canonical Child birth or lineage changed".into());
554        }
555        if durable
556            .metadata
557            .get("runtime.local_task.state")
558            .is_some_and(|state| state != "stopped")
559        {
560            return Err("previous local task has no confirmed stop; recovery is blocked".into());
561        }
562        store
563            .ensure_actor(&session.id)
564            .await
565            .map_err(|e| e.to_string())?;
566        store
567            .bind_control_plane(
568                &session.id,
569                bamboo_domain::ActorControlPlaneBinding {
570                    policy_revision: self.permission.as_ref().map(|p| p.policy_revision()),
571                    placement_intent: Some(bamboo_domain::ActorPlacementIntent::Local),
572                },
573            )
574            .await
575            .map_err(|e| e.to_string())?;
576        let locked = inbox
577            .parent_question_lock
578            .as_ref()
579            .ok_or("canonical local write coordinator unavailable")?;
580        let now = chrono::Utc::now();
581        let claimed = store
582            .claim_activation(&ActorActivationClaim {
583                actor_id: session.id.clone(),
584                run_id: run_id.into(),
585                lease_owner: format!("host-task-{}", uuid::Uuid::new_v4()),
586                lease_expires_at: now + chrono::Duration::seconds(30),
587                inbox_generation: session
588                    .session_inbox_admission()
589                    .map_or(0, |state| state.last_admitted_sequence),
590                placement_ref: None,
591                now,
592            })
593            .await
594            .map_err(|e| e.to_string())?;
595        let setup = async {
596            let owner = ChildActorRuntimeWrite::from_session(claimed.fence(), session)
597                .map_err(|e| e.to_string())?;
598            let cache = runtime.sessions_cache.clone();
599            let persistence: Arc<dyn RuntimeSessionPersistence> = Arc::new(
600                locked
601                    .bind_child_actor_writer(
602                        owner.clone(),
603                        store.clone(),
604                        Arc::new(move |saved| {
605                            cache.insert(
606                                saved.id.clone(),
607                                Arc::new(crate::SessionSnapshot::new(saved.clone())),
608                            );
609                        }),
610                    )
611                    .map_err(|e| e.to_string())?,
612            );
613            store
614                .start_activation(&owner.fence, now)
615                .await
616                .map_err(|e| e.to_string())?;
617            Ok::<_, String>((owner, persistence))
618        }
619        .await;
620        let (owner, persistence) = match setup {
621            Ok(bound) => bound,
622            Err(error) => {
623                return match store
624                    .finish_activation(
625                        &claimed.fence(),
626                        chrono::Utc::now(),
627                        ActorActivationFinish::Failed,
628                    )
629                    .await
630                {
631                    Ok(_) => Err(error),
632                    Err(rollback) => Err(format!(
633                        "{error}; exact claim rollback unconfirmed: {rollback}"
634                    )),
635                };
636            }
637        };
638        let heartbeat_stop = CancellationToken::new();
639        let heartbeat = {
640            let store = store.clone();
641            let fence = owner.fence.clone();
642            let done = heartbeat_stop.clone();
643            let cancel = cancel.clone();
644            tokio::spawn(async move {
645                let mut interval = tokio::time::interval(Duration::from_secs(5));
646                interval.tick().await;
647                loop {
648                    tokio::select! { _ = done.cancelled() => break, _ = interval.tick() => {} }
649                    let now = chrono::Utc::now();
650                    if store
651                        .renew_activation(&fence, now, now + chrono::Duration::seconds(30))
652                        .await
653                        .is_err()
654                    {
655                        cancel.cancel();
656                        break;
657                    }
658                }
659            })
660        };
661        let execution = Arc::new(Execution {
662            owner,
663            persistence: persistence.clone(),
664            cancel,
665            resources: bamboo_tools::LocalTaskResources::new(
666                &session.id,
667                run_id,
668                session.created_at,
669            ),
670            task: tokio::sync::Mutex::new(None),
671            stop: Mutex::new(None),
672            finalized: AtomicBool::new(false),
673            launch: Mutex::new(LaunchState::Queued),
674            admission: Mutex::new(Some(admission)),
675            slot: Mutex::new(None),
676            launch_handoff: tokio::sync::watch::channel(false).0,
677            heartbeat_stop,
678            heartbeat: tokio::sync::Mutex::new(Some(heartbeat)),
679        });
680        lock(&self.executions).insert(session.id.clone(), execution);
681        Ok(Some(persistence))
682    }
683
684    async fn execute_external_child(
685        &self,
686        session: &mut Session,
687        job: &SpawnJob,
688        event_tx: mpsc::Sender<AgentEvent>,
689        cancel_token: CancellationToken,
690    ) -> crate::runtime::runner::Result<()> {
691        let runtime = self.runtime().map_err(failure)?;
692        let (binding, tickets) = {
693            let b = lock(&self.bindings);
694            (
695                b.inbox
696                    .clone()
697                    .ok_or_else(|| failure("Inbox unavailable"))?,
698                b.tickets.clone(),
699            )
700        };
701        let run_id = binding
702            .router
703            .current_run_id(&session.id)
704            .await
705            .ok_or_else(|| failure("activation missing"))?;
706        let execution = self.execution(session, &run_id).map_err(failure)?;
707        {
708            let mut state = lock(&execution.launch);
709            if *state != LaunchState::Queued {
710                return Err(failure("duplicate or closed local task launch"));
711            }
712            *state = LaunchState::Preparing;
713        }
714        let result = async {
715        let slot = tokio::select! { biased; _ = cancel_token.cancelled() => return Err(AgentError::Cancelled), slot = self.concurrency.clone().acquire_owned() => slot.map_err(failure)? };
716        *lock(&execution.slot) = Some(slot);
717        crate::session_app::child_session::named_profile::validate_named_profile(session)
718            .map_err(failure)?;
719        if let (Some(policy), Some(workspace)) = (&self.permission, &session.workspace) {
720            policy.register_session_workspace(session.id.clone(), workspace);
721        }
722        let strict = skill_host::strict_child(session)?;
723        let names = if strict { match &self.ceiling {
724            Some(source) => Some(source.observe(session).await.map_err(failure)?),
725            None => return Err(failure("strict native tool ceiling unavailable")),
726        }} else { None };
727        let mut ticket_plan = None;
728        if session.metadata.contains_key(crate::ticket_worker_plan::TICKET_LOCAL_PLAN_KEY) {
729            let service = tickets.clone().ok_or_else(||failure("Ticket authority unavailable"))?;
730            crate::ticket_runtime::admit_ticket_run(&service, &binding, session, &run_id).await.map_err(failure)?;
731            let assignment = session.metadata[crate::ticket_worker_plan::TICKET_LOCAL_PLAN_KEY].clone();
732            let plan = Arc::new(crate::ticket_worker_plan::TicketWorkerPlan::from_runtime_receipt(service, &assignment).map_err(failure)?);
733            session.agent_runtime_state.get_or_insert_with(Default::default).run_id = run_id.clone();
734            plan.bind_session(session).map_err(failure)?;
735            ticket_plan = Some(plan);
736        }
737        let mut tools: Arc<dyn ToolExecutor> = runtime.tools.clone();
738        let store = lock(&self.bindings).store.clone().ok_or_else(||failure("local store unavailable"))?;
739        let factory = if strict { None } else { lock(&self.bindings).skills.clone() };
740        let mut child_skill_host = None;
741        let mut child_skill_authority = None;
742        if let Some(factory) = factory {
743            let authority = LocalChildSkillAuthority::bind(store.clone(), &execution);
744            let binding = factory.bind(authority.clone(), session, tools).await?;
745            child_skill_authority = Some(authority);
746            tools = binding.tools;
747            child_skill_host = Some(binding.host);
748        }
749        let names = names.unwrap_or_else(||tools.list_tools().into_iter().map(|s|s.function.name).collect());
750        tools = Arc::new(tool_policy::LocalChildTools::new(tools, names.clone(), session, store.clone(), execution.owner.clone(), job.disabled_tools.as_deref())?.with_canonical_subagent(lock(&self.bindings).subagent.clone()));
751        if session.metadata.contains_key(crate::ticket_worker_plan::TICKET_LOCAL_PLAN_KEY) {
752            tools = Arc::new(crate::ticket_worker_plan::files::LocalFileExecutor::new(
753                tools, tickets.clone().ok_or_else(||failure("Ticket authority unavailable"))?, session.clone(), run_id.clone(), &names
754            ).map_err(failure)?);
755        }
756        if let Some(authority) = child_skill_authority { authority.finalize_tools(tools.as_ref()); }
757        let (local_event_tx, local_event_rx) = mpsc::channel(256);
758        let mut request = ExecuteRequestBuilder::new("", local_event_tx.clone(), cancel_token.clone())
759            .tools(tools)
760            .model(job.model.clone());
761        if strict { request = request.selected_skill_ids(Vec::new()); }
762        else {
763            if let Some(ids) = session.metadata.get("selected_skill_ids").and_then(|raw|bamboo_skills::selection::parse_selected_skill_ids_metadata(raw)) { request = request.selected_skill_ids(ids); }
764            if let Some(mode) = session.metadata.get("skill_mode").or_else(||session.metadata.get("mode")).map(|v|v.trim()).filter(|v|!v.is_empty()) { request = request.selected_skill_mode(mode); }
765        }
766        if let Some(data_dir) = runtime.app_data_dir.clone() {
767            request = request.app_data_dir(data_dir);
768        }
769        if let Some(disabled) = &job.disabled_tools {
770            request = request.disabled_tools(disabled.iter().cloned().collect());
771        }
772        if let Some(reference) = crate::session_app::provider_model::session_effective_model_ref(session) {
773            if let Some(router) = &runtime.provider_router {
774                request = request.model(reference.model.clone())
775                    .provider_override(router.route(&reference).map_err(failure)?)
776                    .provider_name(reference.provider.clone());
777                if let Some(kind) = router.provider_type_for(&reference) {
778                    request = request.provider_type(kind);
779                }
780            }
781        }
782        if let Some(effort) = session.reasoning_effort {
783            request = request.reasoning_effort(effort);
784        }
785        if let Some(plan) = ticket_plan {
786            // Admission above binds this exact canonical Child/Run/dispatch.
787            // Carry its Host ceiling into the request even if queued execution
788            // observes a later relaxation of the global configuration.
789            if let Some(cap) = crate::ticket_runtime::read_dispatch(session).map_err(failure)?.and_then(|binding| binding.max_rounds) {
790                if cap == 0 { return Err(failure("zero Host round ceiling")); }
791                request = request.run_budget(bamboo_config::RunBudgetConfig { max_rounds: Some(cap), ..Default::default() });
792            }
793            request = request.ticket_worker_plan(plan);
794        }
795        let mut owned_session = session.clone();
796        // The question fact survives its answer for replay/deduplication. The
797        // handoff is only for the run that issued that fact, not every later
798        // run that happens to retain it in canonical history.
799        let parent_question_at_start = owned_session.metadata.get(bamboo_domain::PARENT_QUESTION_REQUEST_KEY).cloned();
800        owned_session.metadata.remove("runtime.actor_parent_question_handoff");
801        owned_session.metadata.remove(bamboo_subagent::proto::WORKFLOW_TERMINAL_OBSERVATION_KEY);
802        owned_session.metadata.remove(bamboo_subagent::proto::WORKFLOW_USAGE_OBSERVATION_KEY);
803        record_local_task_observation(&mut owned_session, &run_id, execution.owner.created_at, "running");
804        execution
805            .persistence
806            .checkpoint_runtime_session(&mut owned_session)
807            .await
808            .map_err(failure)?;
809        let mut agent = runtime
810            .agent
811            .with_execution_persistence(execution.persistence.clone());
812        if strict {
813            agent = agent.with_skill_execution_host(skill_host::StrictChildSkills::bind(store, &execution));
814        } else if let Some(host) = child_skill_host {
815            agent = agent.with_skill_execution_host(host);
816        }
817        let resources = execution.resources.clone();
818        let task_cancel = cancel_token.clone();
819        let mut handle = execution.task.lock().await;
820        {
821            let mut state = lock(&execution.launch);
822            if *state != LaunchState::Preparing { return Err(failure("local launch gate is closed")); }
823            if cancel_token.is_cancelled() || self.closed.load(Ordering::Acquire) { return Err(AgentError::Cancelled); }
824            *state = LaunchState::Running;
825        }
826        let approval_proxy: Option<Arc<dyn bamboo_tools::ApprovalProxy>> = match (&self.permission, &self.approval_reviewer) {
827            (Some(policy), Some(reviewer)) => Some(Arc::new(approval::LocalApprovalProxy::new(approval::LocalApprovalContext {
828                store: lock(&self.bindings).store.clone().expect("prepared store"), owner: execution.owner.clone(), router: binding.router.clone(), cancel: cancel_token.clone(), policy: policy.clone(), reviewer: reviewer.clone(), registry: self.approval_registry.clone(),
829            }))),
830            _ => None,
831        };
832        let (event_store, event_observer) = { let bindings=lock(&self.bindings); (bindings.store.clone().expect("prepared store"), bindings.observer.clone()) };
833        let event_owner = execution.owner.clone();
834        let event_cancel = cancel_token.clone();
835        let task = tokio::spawn(async move {
836            let forward = tokio::spawn(events::forward(event_store, event_owner, event_observer, local_event_rx, event_tx, event_cancel));
837            let result = std::panic::AssertUnwindSafe(
838                resources.scope(bamboo_tools::with_approval_proxy(approval_proxy, async {
839                    if let Some(audit) = bamboo_domain::PermissionAuditSnapshot::from_metadata(&owned_session.metadata) {
840                        local_event_tx.send(AgentEvent::PermissionPostureActivated { session_id: owned_session.id.clone(), policy_revision: audit.policy_revision, requested_mode: audit.resolution.requested.as_str().to_owned(), effective_mode: audit.resolution.effective.as_str().to_owned(), executor_mapping: audit.executor_mapping }).await.map_err(failure)?;
841                    }
842                    drop(local_event_tx);
843                    // This owned execution has now taken over the admitted
844                    // resume. Mirror the normal Root execution seam: retained
845                    // answer/retry handoff markers are not future pending work.
846                    // Do not consume them while queued or during preparation.
847                    crate::session_app::execute::consume_pending_clarification_resume(&mut owned_session);
848                    agent.execute(&mut owned_session, request.build()).await
849                })),
850            )
851            .catch_unwind()
852            .await;
853            // This is a private execution token. Finalization cancels remaining
854            // safe auxiliary requests even when the main loop returned normally.
855            task_cancel.cancel();
856            if result.is_err() { resources.record_unconfirmed("Agent task panicked; physical effects remain unconfirmed"); }
857            let mut drained = resources.close_and_drain().await;
858            let mut result = match result {
859                Ok(result) => result,
860                Err(_) => {
861                    // The loop itself may have unwound a Tokio filesystem or
862                    // custom-tool future outside registered builtin resources.
863                    // Joining the task proves exit, not those physical effects.
864                    drained = Err(std::io::Error::other("Agent task panicked; physical effects remain unconfirmed"));
865                    Err(failure("Agent task panicked"))
866                },
867            };
868            match forward.await {
869                Ok(Ok(())) => {},
870                Ok(Err(error)) => result = Err(failure(format!("local event publication failed: {error}"))),
871                Err(error) => { drained = Err(std::io::Error::other(format!("local event owner panicked: {error}"))); result = Err(failure(error)); },
872            }
873            reconcile_question_handoff(&mut owned_session, parent_question_at_start.as_deref());
874            ExecutionOutput {
875                session: owned_session,
876                result,
877                resources: drained,
878            }
879        });
880        *handle = Some(task);
881        let joined = handle.as_mut().expect("owned task").await;
882        handle.take();
883        let mut output = joined.map_err(|error| failure(format!("Agent task join failed: {error}")))?;
884        *session = output.session;
885        let drained = output
886            .resources
887            .map_err(|error| failure(format!("resource stop unconfirmed: {error}")))?;
888        let identity = drained.identity();
889        if identity.session_id != session.id
890            || identity.run_id != run_id
891            || identity.child_birth != session.created_at
892        {
893            return Err(failure("resource owner changed"));
894        }
895        let proof = ConfirmedTaskStop {
896            session_id: session.id.clone(),
897            child_birth: session.created_at,
898            run_id: run_id.clone(),
899            instance_id: identity.owner_id,
900        };
901        record_stop_metadata(session, &proof);
902        // A Host-limited Ticket which exhausted its rounds did not complete
903        // its contract. Preserve the real stop proof, then use the existing
904        // failure delivery path instead of attempting a success Submission
905        // from a summary turn which may contain only more tool calls.
906        if output.result.is_ok()
907            && session.metadata.get("runtime.completion_reason").map(String::as_str)
908                == Some("max_rounds_reached")
909            && crate::ticket_runtime::read_dispatch(session).map_err(failure)?
910                .is_some_and(|dispatch| dispatch.max_rounds.is_some())
911        {
912            output.result = Err(AgentError::Budget("Ticket run round budget exhausted".into()));
913        }
914        if session.metadata.get(bamboo_subagent::proto::WORKFLOW_USAGE_REQUESTED_KEY).is_some_and(|v|v == "true") {
915            if let Some(runtime) = session.agent_runtime_state.as_ref().filter(|runtime|runtime.run_id == run_id) {
916                let usage = bamboo_subagent::proto::WorkflowAgentUsage { kind: bamboo_subagent::proto::WorkflowAgentUsage::TYPE.into(), activation_run_id: run_id.clone(), child_session_id: session.id.clone(), child_created_at: session.created_at, prompt_tokens: runtime.round.total_prompt_tokens, completion_tokens: runtime.round.total_completion_tokens };
917                session.metadata.insert(bamboo_subagent::proto::WORKFLOW_USAGE_OBSERVATION_KEY.into(), serde_json::to_string(&usage).map_err(failure)?);
918            }
919        }
920        *lock(&execution.stop) = Some(proof.clone());
921        *lock(&execution.launch) = LaunchState::Stopped;
922        let stopped_tickets = lock(&self.bindings).tickets.clone();
923        if let Some(tickets) = stopped_tickets {
924            if session
925                .metadata
926                .contains_key(crate::ticket_worker_plan::TICKET_LOCAL_PLAN_KEY)
927            {
928                crate::ticket_runtime::checkpoint_owned_task_stop(
929                    &tickets,
930                    &binding,
931                    session,
932                    &run_id,
933                    &proof,
934                    output.result.is_ok(),
935                )
936                .await
937                .map_err(failure)?;
938            }
939        }
940        output.result
941        }.await;
942        // No-work stop is proved by permanently closing the launch gate and
943        // draining the resource domain, never by inventing a PID or a task join.
944        let result = async {
945            let unstarted = *lock(&execution.launch) == LaunchState::Preparing;
946            if unstarted {
947                self.stop_unstarted(&execution, session, &run_id)
948                    .await
949                    .map_err(failure)?;
950            }
951            if unstarted
952                && crate::ticket_runtime::read_dispatch(session)
953                    .ok()
954                    .flatten()
955                    .is_some_and(|d| d.receipt.is_some())
956            {
957                let proof = lock(&execution.stop)
958                    .clone()
959                    .ok_or_else(|| failure("local stop proof missing"))?;
960                if let Some(tickets) = tickets {
961                    crate::ticket_runtime::checkpoint_owned_task_stop(
962                        &tickets, &binding, session, &run_id, &proof, false,
963                    )
964                    .await
965                    .map_err(failure)?;
966                }
967            }
968            result
969        }
970        .await;
971        match result {
972            Err(error) if lock(&execution.stop).is_none() => {
973                match execution.persist_stop_unconfirmed().await {
974                    Ok(observed) => {
975                        copy_local_task_observation(&observed, session);
976                        Err(error)
977                    }
978                    Err(checkpoint) => Err(failure(format!(
979                        "{error}; unconfirmed-stop observation was not durably confirmed: {checkpoint}"
980                    ))),
981                }
982            }
983            result => result,
984        }
985    }
986
987    async fn abandon_child_execution(&self, session: &Session, run_id: &str) -> Result<(), String> {
988        let execution = self.execution(session, run_id)?;
989        execution.cancel.cancel();
990        execution.launch_handoff.send_replace(true);
991        let mut stopped = session.clone();
992        if let Err(error) = self.stop_unstarted(&execution, &mut stopped, run_id).await {
993            return match execution.persist_stop_unconfirmed().await {
994                Ok(_) => Err(error),
995                Err(checkpoint) => Err(format!(
996                    "{error}; unconfirmed-stop observation was not durably confirmed: {checkpoint}"
997                )),
998            };
999        }
1000        stopped.set_last_run_status("error");
1001        stopped.set_last_run_error("initial local Child checkpoint failed");
1002        execution
1003            .persistence
1004            .checkpoint_runtime_session(&mut stopped)
1005            .await
1006            .map_err(|e| e.to_string())?;
1007        self.finish_child_execution(&stopped, run_id, true).await
1008    }
1009
1010    fn quarantine_child_execution(&self, session: &Session, run_id: &str) {
1011        if let Ok(execution) = self.execution(session, run_id) {
1012            execution.cancel.cancel();
1013            let mut state = lock(&execution.launch);
1014            if matches!(*state, LaunchState::Queued | LaunchState::Preparing) {
1015                *state = LaunchState::Stopping;
1016            }
1017            execution.launch_handoff.send_replace(true);
1018        }
1019    }
1020
1021    fn track_child_task(
1022        &self,
1023        session_id: &str,
1024        run_id: &str,
1025        handle: tokio::task::JoinHandle<()>,
1026    ) -> Option<tokio::task::JoinHandle<()>> {
1027        let execution = lock(&self.executions).get(session_id).cloned();
1028        if let Some(execution) = execution.filter(|e| e.owner.fence.run_id == run_id) {
1029            // Admission remains occupied through the SDK publication tail.
1030            // The retained supervisor owns and joins the actual coordinator;
1031            // completed permits are returned without waiting for a later spawn.
1032            let permit = lock(&execution.admission).take();
1033            let retained_execution = execution.clone();
1034            let supervisor = tokio::spawn(async move {
1035                let mut result = handle.await.map_err(|error| error.to_string());
1036                if !retained_execution.finalized.load(Ordering::Acquire) {
1037                    // A coordinator exiting does not make an unconfirmed or
1038                    // unpublished execution eligible for replacement.
1039                    if let Some(permit) = permit {
1040                        *lock(&retained_execution.admission) = Some(permit);
1041                    }
1042                    if lock(&retained_execution.stop).is_none() {
1043                        retained_execution.cancel.cancel();
1044                        // The coordinator may have unwound while its separate
1045                        // Agent task still owned a canonical writer. Cancellation
1046                        // alone does not stop those writes: join that task and
1047                        // all registered resources before recording the final
1048                        // unknown observation. This recovery does not mint a
1049                        // normal execution/publication stop receipt.
1050                        let mut orphaned_task = retained_execution.task.lock().await;
1051                        if let Some(task) = orphaned_task.take() {
1052                            if let Err(error) = task.await {
1053                                retained_execution.resources.record_unconfirmed(format!(
1054                                    "orphaned Agent task join failed: {error}"
1055                                ));
1056                            }
1057                        }
1058                        drop(orphaned_task);
1059                        let _ = retained_execution.resources.close_and_drain().await;
1060                        if let Err(error) = retained_execution.persist_stop_unconfirmed().await {
1061                            result = Err(format!(
1062                                "{}unconfirmed-stop observation was not durably confirmed: {error}",
1063                                result
1064                                    .err()
1065                                    .map(|error| format!("{error}; "))
1066                                    .unwrap_or_default()
1067                            ));
1068                        }
1069                    }
1070                }
1071                result
1072            });
1073            let mut handles = lock(&self.coordinators);
1074            let mut pending = Vec::with_capacity(handles.len() + 1);
1075            for mut handle in handles.drain(..) {
1076                if handle.is_finished() {
1077                    match (&mut handle).now_or_never() {
1078                        Some(Err(error)) => lock(&self.coordinator_errors).push(error.to_string()),
1079                        Some(Ok(Err(error))) => lock(&self.coordinator_errors).push(error),
1080                        Some(Ok(Ok(()))) => {}
1081                        None => pending.push(handle),
1082                    }
1083                } else {
1084                    pending.push(handle);
1085                }
1086            }
1087            pending.push(supervisor);
1088            *handles = pending;
1089            execution.launch_handoff.send_replace(true);
1090            None
1091        } else {
1092            Some(handle)
1093        }
1094    }
1095
1096    async fn prepare_durable_child_delivery(
1097        &self,
1098        session: &Session,
1099        run_id: &str,
1100    ) -> Result<bool, String> {
1101        if !self.should_handle(session).await {
1102            return Ok(false);
1103        }
1104        let execution = self.execution(session, run_id)?;
1105        if lock(&execution.stop).is_none() {
1106            return Err("local execution stop is unconfirmed; terminal publication blocked".into());
1107        }
1108        Ok(true)
1109    }
1110    async fn commit_durable_child_delivery(
1111        &self,
1112        session: &Session,
1113        run_id: &str,
1114    ) -> Result<(), String> {
1115        if !self.should_handle(session).await {
1116            return Ok(());
1117        }
1118        let execution = self.execution(session, run_id)?;
1119        if lock(&execution.stop).is_none() {
1120            return Err("local task stop receipt missing".into());
1121        }
1122        let mut final_session = session.clone();
1123        crate::execution::ChildCompletionSource::publish_after_durable_delivery(
1124            &mut final_session,
1125            run_id,
1126        )?;
1127        execution
1128            .persistence
1129            .checkpoint_runtime_session(&mut final_session)
1130            .await
1131            .map_err(|e| e.to_string())?;
1132        let store = lock(&self.bindings)
1133            .store
1134            .clone()
1135            .ok_or("local store unavailable")?;
1136        let readback = store
1137            .load_session(&session.id)
1138            .await
1139            .map_err(|e| e.to_string())?
1140            .ok_or("Child missing after terminal checkpoint")?;
1141        if readback.created_at != session.created_at
1142            || readback
1143                .metadata
1144                .get("runtime.local_task.state")
1145                .map(String::as_str)
1146                != Some("stopped")
1147            || readback.metadata.get("runtime.local_task.instance")
1148                != final_session.metadata.get("runtime.local_task.instance")
1149            || readback.metadata.get("runtime.local_task.run_id") != Some(&run_id.to_string())
1150            || crate::execution::ChildCompletionSource::from_committed_session(&readback)
1151                != crate::execution::ChildCompletionSource::from_committed_session(&final_session)
1152        {
1153            return Err("local terminal checkpoint readback differs".into());
1154        }
1155        let tickets = lock(&self.bindings).tickets.clone();
1156        if let Some(tickets) = tickets.filter(|_| {
1157            crate::ticket_runtime::read_dispatch(&readback)
1158                .ok()
1159                .flatten()
1160                .is_some_and(|d| d.receipt.is_some())
1161        }) {
1162            crate::ticket_runtime::checkpoint_ticket_result(
1163                &tickets,
1164                store.as_ref(),
1165                &readback,
1166                run_id,
1167            )
1168            .await
1169            .map_err(|e| e.to_string())?;
1170        }
1171        Ok(())
1172    }
1173    async fn finish_child_execution(
1174        &self,
1175        session: &Session,
1176        run_id: &str,
1177        history_committed: bool,
1178    ) -> Result<(), String> {
1179        let execution = self.execution(session, run_id)?;
1180        // SDK registers the real coordinator immediately after spawning it.
1181        // Keep this record visible until its handle has another strong owner.
1182        execution.wait_for_handoff().await;
1183        if !history_committed || lock(&execution.stop).is_none() {
1184            return Err("local Child finalization remains unconfirmed".into());
1185        }
1186        execution.heartbeat_stop.cancel();
1187        if let Some(handle) = execution.heartbeat.lock().await.take() {
1188            handle.await.map_err(|e| e.to_string())?;
1189        }
1190        let store = lock(&self.bindings)
1191            .store
1192            .clone()
1193            .ok_or("local store unavailable")?;
1194        let outcome = match session.last_run_status().as_deref() {
1195            Some("completed" | "suspended") => ActorActivationFinish::Succeeded,
1196            Some("cancelled") => ActorActivationFinish::Cancelled,
1197            _ => ActorActivationFinish::Failed,
1198        };
1199        store
1200            .finish_activation(&execution.owner.fence, chrono::Utc::now(), outcome)
1201            .await
1202            .map_err(|e| e.to_string())?;
1203        lock(&execution.slot).take();
1204        lock(&self.executions).remove(&session.id);
1205        execution.finalized.store(true, Ordering::Release);
1206        Ok(())
1207    }
1208    async fn shutdown(&self) -> Result<(), String> {
1209        self.closed.store(true, Ordering::Release);
1210        self.admission.close();
1211        // Preparations take a permit before observing closed. Holding all of
1212        // them here closes the snapshot race with an already admitted claim
1213        // and serializes shutdown callers through all joins and cache release.
1214        let _preparations = self
1215            .preparations
1216            .acquire_many(128)
1217            .await
1218            .map_err(|e| e.to_string())?;
1219        let executions: Vec<_> = lock(&self.executions).values().cloned().collect();
1220        for execution in &executions {
1221            execution.cancel.cancel();
1222        }
1223        for execution in &executions {
1224            execution.wait_for_handoff().await;
1225        }
1226        loop {
1227            let next = lock(&self.coordinators).pop();
1228            let Some(coordinator) = next else { break };
1229            let mut retained = RetainedCoordinatorJoin {
1230                queue: &self.coordinators,
1231                handle: Some(coordinator),
1232            };
1233            let result = retained
1234                .handle
1235                .as_mut()
1236                .expect("retained coordinator")
1237                .await;
1238            retained.handle.take();
1239            // Record each observed error before the next await, so cancelling
1240            // this caller cannot discard a completed coordinator's failure.
1241            match result {
1242                Ok(Ok(())) => {}
1243                Ok(Err(error)) => self.retain_shutdown_error(error),
1244                Err(error) => self.retain_shutdown_error(error.to_string()),
1245            }
1246        }
1247        for execution in executions {
1248            execution.wait_for_handoff().await;
1249            execution.heartbeat_stop.cancel();
1250            if let Some(heartbeat) = execution.heartbeat.lock().await.take() {
1251                if let Err(error) = heartbeat.await {
1252                    self.retain_shutdown_error(error.to_string());
1253                }
1254            }
1255            if let Some(task) = execution.task.lock().await.take() {
1256                if let Err(error) = task.await {
1257                    self.retain_shutdown_error(error.to_string());
1258                }
1259            }
1260            if let Err(error) = execution.resources.close_and_drain().await {
1261                self.retain_shutdown_error(error.to_string());
1262            }
1263            if lock(&execution.stop).is_none() {
1264                self.retain_shutdown_error(format!(
1265                    "{} local stop remains unconfirmed",
1266                    execution.owner.fence.actor_id
1267                ));
1268            }
1269        }
1270        // A setup accepted before shutdown may harvest an older coordinator
1271        // while handing off. Read this queue only after all handoffs/joins, so
1272        // its retained error cannot be lost between the two snapshots.
1273        // A consumed failed join cannot be re-confirmed by a later empty
1274        // queue. Keep observed drain failures on this closed runtime, including
1275        // across cancellation; repeated shutdown is not permission to forget.
1276        let errors = lock(&self.coordinator_errors).clone();
1277        if errors.is_empty() {
1278            // Only a confirmed physical drain, including publication-tail
1279            // joins, can relinquish this cached canonical writer. Unknown stop
1280            // or a failed drain keeps the original service and its real lock.
1281            let retired_ticket_service = lock(&self.bindings).tickets.take();
1282            drop(retired_ticket_service);
1283            Ok(())
1284        } else {
1285            Err(errors.join("; "))
1286        }
1287    }
1288}
1289
1290mod approval;
1291mod events;
1292mod skill_host;
1293mod tool_policy;
1294
1295#[cfg(test)]
1296mod tests;
1297
1298#[cfg(test)]
1299mod question_handoff_tests {
1300    use super::*;
1301
1302    #[test]
1303    fn answered_question_fact_does_not_suspend_successor_run() {
1304        let mut session = Session::new("child", "model");
1305        session.metadata.insert(
1306            bamboo_domain::PARENT_QUESTION_REQUEST_KEY.into(),
1307            "durable-question".into(),
1308        );
1309        session.metadata.insert(
1310            "runtime.actor_parent_question_handoff".into(),
1311            "true".into(),
1312        );
1313        reconcile_question_handoff(&mut session, Some("durable-question"));
1314        assert!(!session
1315            .metadata
1316            .contains_key("runtime.actor_parent_question_handoff"));
1317    }
1318
1319    #[test]
1320    fn newly_issued_question_keeps_handoff_after_fast_answer() {
1321        let mut session = Session::new("child", "model");
1322        session.metadata.insert(
1323            bamboo_domain::PARENT_QUESTION_REQUEST_KEY.into(),
1324            "durable-question".into(),
1325        );
1326        assert!(session.pending_question.is_none());
1327        reconcile_question_handoff(&mut session, None);
1328        assert_eq!(
1329            session
1330                .metadata
1331                .get("runtime.actor_parent_question_handoff")
1332                .map(String::as_str),
1333            Some("true")
1334        );
1335    }
1336}