Skip to main content

bamboo_engine/external_agents/
actor_adapter.rs

1//! Actor external child runner.
2//!
3//! Runs a child session as an independent **actor**: a separate OS process with its own
4//! isolated context, speaking the `bamboo-subagent` WebSocket protocol. This is the
5//! engine-side adapter on the `wants_external` seam: it spawns the worker binary, waits for
6//! it to self-register into the Tier-1 file fabric, connects, sends the assignment, and
7//! forwards the child's `AgentEvent`s back onto the parent's `event_tx`.
8//!
9//! The built-in **local actor** instance of this runner is the default runtime for
10//! every sub-agent (the in-process runtime was removed). The expert `externalAgents`
11//! tables can additionally route specific roles to other actor/a2a agents.
12
13use std::collections::HashMap;
14use std::path::PathBuf;
15use std::sync::Arc;
16use std::time::Duration;
17
18use async_trait::async_trait;
19use bamboo_agent_core::{AgentError, AgentEvent, Role, Session};
20use bamboo_domain::poison::PoisonRecover;
21use tokio::sync::mpsc;
22use tokio_util::sync::CancellationToken;
23
24use bamboo_subagent::fleet::{spawn_worker_on_bus, SpawnedChild};
25use bamboo_subagent::proto::{AgentRecord, ChildFrame, ParentFrame, RunSpec, TerminalStatus};
26use bamboo_subagent::provision::{
27    ChildIdentity, ExecutorSpec, ModelRefSpec, Placement, ProvisionSpec, ScopedCredential,
28};
29use bamboo_subagent::transport::{client_config_trusting_cert, ChildClient};
30
31use crate::runtime::execution::{ExternalChildRunner, SpawnJob};
32
33/// Default cap on simultaneously running actor processes.
34pub const DEFAULT_MAX_CONCURRENT_ACTORS: usize = 8;
35
36/// Max nesting depth for direct nested execution (Phase 6). A worker whose
37/// session `spawn_depth` is below this gets its own spawn stack + the real
38/// SubAgent tool; at/over it, neither (and the tool itself refuses). Mirrors
39/// `bamboo_server_tools::DEFAULT_MAX_SPAWN_DEPTH` (kept in sync; engine can't
40/// depend on server-tools). Root orchestrator = 0 ⇒ 4 levels of sub-agents.
41pub const MAX_SPAWN_DEPTH: u32 = 4;
42
43/// Default cap on idle pooled (warm, reusable) workers kept per fingerprint.
44const DEFAULT_MAX_IDLE_PER_KEY: usize = 4;
45
46/// How long a pooled worker waits for its next assignment before reclaiming
47/// itself (must comfortably exceed the gap between sibling spawns).
48const POOLED_IDLE_TIMEOUT_SECS: u64 = 300;
49
50/// Deadline for a local worker's FIRST frame after a Run is dispatched. A warm
51/// worker answers in seconds; a cold spawn within tens. Total silence past this
52/// means the worker is dead (e.g. a pooled worker that exited right after its
53/// liveness check) and its Run is queued with nobody to serve it — trip it so the
54/// runner respawns once instead of hanging forever. Generous, to never false-trip
55/// a slow-but-healthy cold start.
56const WORKER_FIRST_FRAME_TIMEOUT: Duration = Duration::from_secs(60);
57
58/// A warm worker on the mailbox bus, parked for reuse between runs. It stays
59/// dialed-in + subscribed to `mailbox_id`; the next interchangeable child
60/// delivers its `Run` there instead of spawning a fresh process. Dropping it
61/// kills a local kill-on-drop subprocess; a remote / schedulable handle is
62/// process-less (`kill()` is a no-op — it self-manages via its idle timeout).
63struct PooledWorker {
64    worker: SpawnedChild,
65    /// The bus mailbox this worker subscribes to (where its `Run`s are delivered).
66    mailbox_id: String,
67}
68
69/// A role pinned to a remote resident worker (remote-actor-plan §3.4 / P1.5,
70/// #193), resolved at runner-build time from `SubagentsConfig.remote_placements`:
71/// the env-named bearer is already READ into `token` here (the raw token never
72/// rides the config), and `ca_cert_file` is the path to a PEM pinning a
73/// self-signed worker cert (`None` ⇒ default webpki roots / plaintext `ws://`).
74#[derive(Debug, Clone)]
75pub struct ResolvedRemotePlacement {
76    pub endpoint: String,
77    pub token: Option<String>,
78    pub ca_cert_file: Option<PathBuf>,
79    /// Display name for the machine this role runs on — the matching cluster
80    /// node's `label`/host, surfaced on the UI placement badge. `None` ⇒ derive
81    /// from the endpoint host.
82    pub host_label: Option<String>,
83}
84
85/// A role routed to a SCHEDULED worker (remote-actor-plan §3.4 / P2b, #181),
86/// resolved at runner-build time from `SubagentsConfig.schedulable_placements`.
87/// Names the logical `pool` (= the bus role) whose LIVE connected workers are the
88/// scheduling candidates — the runner picks one via the bus presence query
89/// (`BrokerClient::list_connected`). Phase 3 retired the old HTTP registry, so a
90/// pool is now just a role on the bus.
91#[derive(Debug, Clone)]
92pub struct ResolvedSchedulablePlacement {
93    pub pool: String,
94    /// Display name for the machine this pool's workers run on — the matching
95    /// cluster node's `label`/host, surfaced on the UI placement badge. `None` ⇒
96    /// fall back to the pool name.
97    pub host_label: Option<String>,
98}
99
100/// How `execute_external_child` should obtain its worker connection, decided
101/// once from `spec.placement`. Splits the divergent acquire/connect + retire
102/// logic three ways while the shared middle (Run dispatch, live registration,
103/// drive, close) stays identical. `Local` is the unchanged pre-#193 path;
104/// `Remote` is the unchanged #194 path; `Schedulable` (#181, P2b) is new.
105enum PlacementKind {
106    Local,
107    Remote,
108    Schedulable,
109}
110
111/// Spawns and drives a child session as an independent actor: a `bamboo-subagent` worker process.
112pub struct ActorChildRunner {
113    agent_id: String,
114    worker_bin: PathBuf,
115    worker_args: Vec<String>,
116    fabric_dir: PathBuf,
117    executor: ExecutorSpec,
118    /// Per-provider credentials snapshotted from the parent config at build
119    /// time; the spec carries only the ONE the child's provider needs.
120    credentials: Vec<ScopedCredential>,
121    /// Parent's default provider (used when the child has no explicit one).
122    default_provider: String,
123    /// The mailbox bus to run local children over (the unified transport). Local
124    /// sub-agents require it; `None` only when no broker could be embedded.
125    bus: Option<bamboo_subagent::BusEndpoint>,
126    /// Backpressure: bounds the number of concurrently *running* actors; further
127    /// runs wait for a slot instead of exploding the process table. (Idle pooled
128    /// workers do not hold a slot.)
129    concurrency: std::sync::Arc<tokio::sync::Semaphore>,
130    /// Warm-worker pool keyed by a reuse fingerprint
131    /// (role/provider/model/workspace/disabled-tools/baked-caps). A finished run
132    /// parks its bus worker here so the next interchangeable child reuses it
133    /// (delivers its `Run` to the same mailbox) instead of spawning a fresh
134    /// process — collapsing N sibling sub-agents onto a few warm workers.
135    pool: Arc<tokio::sync::Mutex<HashMap<String, Vec<PooledWorker>>>>,
136    max_idle_per_key: usize,
137    /// Host-side decision for a child's gated-tool approval request (Phase 2).
138    /// `None` ⇒ fail-closed DENY (the safe default). A wired decider (policy or
139    /// human-routing bridge) returns approve/deny over the actor WS.
140    approval_decider: Option<Arc<dyn ChildApprovalDecider>>,
141    /// Per-run escalation host bridge for non-bypass child-approval routing (#68;
142    /// Phase 6, Part B). The owning worker's `run()` installs its OWN host bridge
143    /// here via `set_escalation_bridge`; `execute_external_child` CAPTURES it at
144    /// grandchild-spawn time and hands the owned value to `drive()`, which uses it
145    /// to RE-PROXY a child's approval request UP to the parent run — chaining up
146    /// every level until a bypass level (model-review) or the top orchestrator
147    /// (human) decides, then relaying the reply back down. Was a process-global
148    /// slot; now per-runner so a fire-and-forget grandchild that OUTLIVES the run
149    /// that spawned it keeps that run's bridge for its whole lifetime instead of
150    /// reading a stale/overwritten global at approval time (→ fail-closed deny).
151    escalation_bridge: Arc<std::sync::Mutex<Option<bamboo_subagent::executor::HostBridge>>>,
152    /// Roles pinned to a REMOTE resident worker (#193), keyed by sub-agent role
153    /// (the child's `subagent_type`). A role present here routes through the
154    /// dedicated remote branch in `execute_external_child` (Bearer-authenticated
155    /// `wss://` connect, no spawn, no pool, no kill) instead of the local
156    /// subprocess + warm-pool path. Empty (the default) = all-local behavior.
157    remote_placements: HashMap<String, ResolvedRemotePlacement>,
158    /// Roles routed to a REGISTRY-SCHEDULED worker (#181, P2b), keyed by sub-agent
159    /// role. A role present here (AND not already in `remote_placements`, which
160    /// wins) routes through the dedicated SCHEDULABLE branch in
161    /// `execute_external_child`: query the registry for live workers in the pool,
162    /// pick one (round-robin), connect over `wss://` — no spawn, no pool, no kill,
163    /// and NO local-subprocess fallback (no live worker ⇒ a clear error). Empty
164    /// (the default) = all-local behavior.
165    schedulable_placements: HashMap<String, ResolvedSchedulablePlacement>,
166    /// Per-pool round-robin cursor for schedulable scheduling (#181, P2b). Bumped
167    /// once per pick so successive sibling spawns SPREAD across a pool's live
168    /// workers instead of all landing on the first candidate. Best-effort spread,
169    /// not a load balancer — the registry's live set can change between picks.
170    schedule_cursor: Arc<std::sync::Mutex<HashMap<String, usize>>>,
171}
172
173/// Decides how the host answers a child worker's gated-tool approval request
174/// (Phase 2: child → parent approval delegation). Async so an implementation
175/// can consult a policy or defer to a human. With no decider wired the host
176/// replies with a fail-closed DENY.
177///
178/// NOTE: `decide` is awaited inside the per-child frame pump, so an
179/// implementation must resolve promptly (e.g. a policy lookup). A human-in-the-
180/// loop decision that may block indefinitely should instead be delivered
181/// out-of-band as a `ParentFrame::ApprovalReply` via the live steering channel
182/// (`super::live`), which `drive()` already forwards to the worker without
183/// stalling the pump.
184#[async_trait]
185pub trait ChildApprovalDecider: Send + Sync {
186    /// Decide whether `child_session_id` may perform the gated action described
187    /// by `request` (`{tool_name, permission, resource}`).
188    async fn decide(&self, child_session_id: &str, request: &serde_json::Value) -> bool;
189}
190
191/// Resolve a child approval request to approve/deny. Fail-closed (DENY) when no
192/// decider is wired — the single, testable seam for the host-side decision.
193async fn decide_child_approval(
194    decider: Option<&Arc<dyn ChildApprovalDecider>>,
195    child_session_id: &str,
196    request: &serde_json::Value,
197) -> bool {
198    match decider {
199        Some(decider) => decider.decide(child_session_id, request).await,
200        None => false,
201    }
202}
203
204/// How long the host waits for a human approval decision before failing the
205/// child's gated tool closed (DENY). Bounds an unanswered request so it can't
206/// hang the worker indefinitely.
207const CHILD_APPROVAL_TIMEOUT: Duration = Duration::from_secs(300);
208
209/// Extract `(tool_name, permission, resource)` from a worker's approval request
210/// body (`{tool_name, permission, resource}`); missing fields default to empty.
211fn approval_request_fields(body: &serde_json::Value) -> (String, String, String) {
212    let field = |k: &str| {
213        body.get(k)
214            .and_then(|v| v.as_str())
215            .unwrap_or("")
216            .to_string()
217    };
218    (field("tool_name"), field("permission"), field("resource"))
219}
220
221/// Off-loop reviewer for a child's gated-tool approval request (Phase 6, Part B).
222///
223/// Installed (process-global) by a BYPASSED self-orchestrating worker so its
224/// children's forced-ask (dangerous) gated actions — which still raise
225/// `ConfirmationRequired` even under bypass — get an LLM reasonableness check
226/// rather than a blind pass. `review` is an LLM call: `drive()` invokes it in a
227/// SPAWNED task (NEVER in the frame pump) and delivers the verdict async via the
228/// live channel, so the agent loop is never blocked.
229#[async_trait]
230pub trait ChildApprovalReviewer: Send + Sync {
231    /// Judge whether the gated action `request` (`{tool_name, permission,
232    /// resource}`) is reasonable for `child_session_id`'s task. `true` = approve.
233    async fn review(&self, child_session_id: &str, request: &serde_json::Value) -> bool;
234}
235
236fn child_approval_reviewer_slot() -> &'static std::sync::OnceLock<Arc<dyn ChildApprovalReviewer>> {
237    static SLOT: std::sync::OnceLock<Arc<dyn ChildApprovalReviewer>> = std::sync::OnceLock::new();
238    &SLOT
239}
240
241/// Install the process-global child-approval reviewer (idempotent; first wins).
242pub fn set_child_approval_reviewer(reviewer: Arc<dyn ChildApprovalReviewer>) {
243    let _ = child_approval_reviewer_slot().set(reviewer);
244}
245
246/// The process-global child-approval reviewer, if installed.
247pub fn child_approval_reviewer() -> Option<Arc<dyn ChildApprovalReviewer>> {
248    child_approval_reviewer_slot().get().cloned()
249}
250
251impl ActorChildRunner {
252    #[allow(clippy::too_many_arguments)]
253    pub fn new(
254        agent_id: String,
255        worker_bin: PathBuf,
256        worker_args: Vec<String>,
257        fabric_dir: PathBuf,
258        executor: ExecutorSpec,
259        credentials: Vec<ScopedCredential>,
260        default_provider: String,
261        max_concurrent: usize,
262    ) -> Self {
263        Self {
264            agent_id,
265            worker_bin,
266            worker_args,
267            fabric_dir,
268            executor,
269            credentials,
270            default_provider,
271            bus: None,
272            concurrency: std::sync::Arc::new(tokio::sync::Semaphore::new(max_concurrent.max(1))),
273            pool: Arc::new(tokio::sync::Mutex::new(HashMap::new())),
274            max_idle_per_key: DEFAULT_MAX_IDLE_PER_KEY,
275            approval_decider: None,
276            escalation_bridge: Arc::new(std::sync::Mutex::new(None)),
277            remote_placements: HashMap::new(),
278            schedulable_placements: HashMap::new(),
279            schedule_cursor: Arc::new(std::sync::Mutex::new(HashMap::new())),
280        }
281    }
282
283    /// Run children over the mailbox bus (the unified actor+mailbox transport).
284    /// When set, local children dial this bus and are driven by mailbox id; when
285    /// unset they use the legacy direct-WS path. The server passes its in-process
286    /// broker here (`subagents.broker`); tests without a broker leave it unset.
287    pub fn with_bus(mut self, bus: Option<bamboo_subagent::BusEndpoint>) -> Self {
288        self.bus = bus.filter(|b| !b.endpoint.trim().is_empty());
289        self
290    }
291
292    /// Wire the host-side decider for child gated-tool approval requests
293    /// (Phase 2). Without this the host fail-closed DENYs every request.
294    pub fn with_approval_decider(mut self, decider: Arc<dyn ChildApprovalDecider>) -> Self {
295        self.approval_decider = Some(decider);
296        self
297    }
298
299    /// Pin specific sub-agent roles to remote resident workers (#193). The map
300    /// is keyed by role (`subagent_type`); a child whose role is present connects
301    /// over `wss://` to the resolved endpoint instead of spawning a local
302    /// subprocess. Default (empty) keeps every role on the local path — exactly
303    /// today's behavior.
304    pub fn with_remote_placements(
305        mut self,
306        placements: HashMap<String, ResolvedRemotePlacement>,
307    ) -> Self {
308        self.remote_placements = placements;
309        self
310    }
311
312    /// Route specific sub-agent roles to a registry-SCHEDULED worker (#181, P2b).
313    /// The map is keyed by role (`subagent_type`); a child whose role is present
314    /// (and NOT already pinned by `remote_placements`, which takes precedence) is
315    /// run on a live worker discovered from the registry instead of a local
316    /// subprocess. Default (empty) keeps every role on the local path.
317    pub fn with_schedulable_placements(
318        mut self,
319        placements: HashMap<String, ResolvedSchedulablePlacement>,
320    ) -> Self {
321        self.schedulable_placements = placements;
322        self
323    }
324
325    /// Reuse fingerprint: two children are interchangeable on one warm worker iff
326    /// they share role, provider, model, workspace, disabled-tool set, AND every
327    /// capability the worker BAKES at provision time (`BambooRuntimeExecutor`
328    /// stamps these once and reuses them across runs): nesting depth, nested-spawn
329    /// stack, bypass mode, permission enforcement, and the depth cap. Omitting any
330    /// of these lets the pool hand a run a worker baked for a DIFFERENT posture —
331    /// e.g. a depth-1 worker (with its own spawn stack) reused for a depth-4
332    /// child would re-stamp `spawn_depth=1` and pass the depth-cap check, breaking
333    /// the recursion bound; or a bypass worker reused for a non-bypass child. So
334    /// these MUST split the pool bucket. Everything else (assignment, history) is
335    /// shipped per-run in the `RunSpec` and does not affect the fingerprint.
336    /// Reuse fingerprint (role/provider/model/workspace/disabled-tools/baked
337    /// caps): two children with the same fingerprint are interchangeable on one
338    /// warm worker, so they share a pool bucket. Any axis the worker bakes ONCE
339    /// at provision time MUST be in here, else a worker baked for one posture
340    /// gets reused for another (see the `fingerprint_*` tests).
341    fn fingerprint(spec: &ProvisionSpec) -> String {
342        let role = spec.identity.role.as_str();
343        let (provider, model) = spec
344            .model
345            .as_ref()
346            .map(|m| (m.provider.as_str(), m.model.as_str()))
347            .unwrap_or(("", ""));
348        let workspace = spec.workspace.as_deref().unwrap_or("");
349        let mut tools = spec.disabled_tools.clone().unwrap_or_default();
350        tools.sort();
351        let caps = &spec.capabilities;
352        format!(
353            "{role}\u{1}{provider}\u{1}{model}\u{1}{workspace}\u{1}{}\u{1}d={}\u{1}ns={}\u{1}by={}\u{1}ep={}\u{1}md={}\u{1}nha={}\u{1}gro={}",
354            tools.join(","),
355            spec.identity.depth,
356            caps.nested_spawn,
357            caps.bypass,
358            caps.enforce_permissions,
359            caps.max_spawn_depth.unwrap_or(0),
360            // #73 review (P1): a worker bakes `no_human_review` ONCE from this flag
361            // at build() and never re-reads it per run, so the pool MUST NOT hand a
362            // worker baked for one approval posture to a run of the opposite one —
363            // else a scheduled-root worker reused for an interactive child would
364            // silently model-review instead of asking the human (and vice-versa,
365            // reintroducing the 300s-deny). Split the bucket on it.
366            caps.no_human_approver,
367            // #71: the read-only Bash checker is baked once at build() from this
368            // flag, so a guardian-reviewer worker must NOT be reused for an
369            // ordinary child (which expects unrestricted Bash), and vice-versa.
370            caps.guardian_read_only,
371        )
372    }
373
374    /// Check out a warm bus worker for `key`, reusing a live parked one if any,
375    /// else spawning a fresh one that dials the bus. The returned worker is OWNED
376    /// by the caller for the run's duration (checkout removes it from the pool, so
377    /// a concurrent sibling gets a different worker or spawns its own — one run per
378    /// worker at a time, matching the pre-bus pool semantics).
379    async fn acquire_bus_worker(
380        &self,
381        key: &str,
382        spec: &ProvisionSpec,
383    ) -> crate::runtime::runner::Result<PooledWorker> {
384        // Drain the bucket, skipping (and reaping) any worker whose process exited
385        // while parked. A live one is handed straight out for reuse.
386        loop {
387            let candidate = {
388                let mut pool = self.pool.lock().await;
389                pool.get_mut(key).and_then(|bucket| bucket.pop())
390            };
391            let Some(mut candidate) = candidate else { break };
392            if candidate.worker.is_alive() {
393                return Ok(candidate);
394            }
395            candidate.worker.kill().await;
396        }
397
398        let spawned = spawn_worker_on_bus(&self.worker_bin, &self.worker_args, spec)
399            .await
400            .map_err(|e| AgentError::LLM(format!("actor spawn (bus) failed: {e}")))?;
401        let mailbox_id = spawned.record.agent_id.clone();
402        Ok(PooledWorker {
403            worker: spawned,
404            mailbox_id,
405        })
406    }
407
408    /// Park a warm bus worker for reuse after a clean run; if its bucket is full
409    /// (or it died), kill it instead. The worker stays dialed-in + subscribed
410    /// while parked, so a reusing child just delivers a new `Run` to its mailbox.
411    async fn release_bus_worker(&self, key: &str, mut worker: PooledWorker) {
412        if !worker.worker.is_alive() {
413            worker.worker.kill().await;
414            return;
415        }
416        let mut pool = self.pool.lock().await;
417        let bucket = pool.entry(key.to_string()).or_default();
418        if bucket.len() >= self.max_idle_per_key {
419            drop(pool);
420            worker.worker.kill().await;
421            return;
422        }
423        bucket.push(worker);
424    }
425
426    /// Assemble the parent-resolved provisioning document for this child.
427    fn build_spec(&self, session: &Session, job: &SpawnJob) -> ProvisionSpec {
428        let mut spec = ProvisionSpec::new(
429            ChildIdentity {
430                child_id: job.child_session_id.clone(),
431                parent_id: Some(job.parent_session_id.clone()),
432                project_key: None,
433                role: session
434                    .metadata
435                    .get("subagent_type")
436                    .cloned()
437                    .unwrap_or_else(|| "worker".to_string()),
438                // The child session already carries the correct depth
439                // (create_child_action's new_child_of did parent.spawn_depth+1);
440                // stamp it so the worker can re-establish it on its run session
441                // and enforce the max-depth cap across the actor boundary.
442                depth: session.spawn_depth,
443            },
444            self.executor.clone(),
445            self.fabric_dir.to_string_lossy().into_owned(),
446        );
447        spec.workspace = session.workspace.clone();
448        // Unified transport: when a bus is configured, the child dials it (no
449        // listen socket / file discovery) and the parent drives it by mailbox id.
450        spec.bus = self.bus.clone();
451        // Final model: the session's pinned model_ref (create.model / routing already applied),
452        // falling back to the job's bare model on the parent's default provider.
453        spec.model = session
454            .model_ref
455            .as_ref()
456            .map(|r| ModelRefSpec {
457                provider: r.provider.clone(),
458                model: r.model.clone(),
459            })
460            .or_else(|| {
461                let m = job.model.trim();
462                (!m.is_empty()).then(|| ModelRefSpec {
463                    provider: self.default_provider.clone(),
464                    model: m.to_string(),
465                })
466            });
467        spec.disabled_tools = job.disabled_tools.clone();
468        // Least-privilege secrets: only the credential for the child's provider.
469        let provider = spec
470            .model
471            .as_ref()
472            .map(|m| m.provider.as_str())
473            .filter(|p| !p.trim().is_empty())
474            .unwrap_or(&self.default_provider);
475        if let Some(cred) = self.credentials.iter().find(|c| c.provider == provider) {
476            spec.secrets.provider_credentials.push(cred.clone());
477        } else {
478            tracing::warn!(
479                "actor child {}: no credential found for provider '{}'",
480                job.child_session_id,
481                provider
482            );
483        }
484        // Phase 6 (direct nested execution): a worker BELOW the depth cap may
485        // orchestrate its OWN children — on startup it builds its own spawn
486        // stack and runs the real SubAgent tool (no host proxy). The cap (the
487        // SubAgent tool refuses to spawn at/over `max_spawn_depth`) bounds the
488        // recursion. Driven purely by the child's depth, so it auto-propagates
489        // down the tree without any extra config threading.
490        spec.capabilities.nested_spawn = session.spawn_depth < MAX_SPAWN_DEPTH;
491        spec.capabilities.max_spawn_depth = Some(MAX_SPAWN_DEPTH);
492        // #69: activate child-approval review. Sub-agents enforce permissions so
493        // their DANGEROUS actions (the worker uses a HIGH threshold) reach the
494        // parent for review — escalated to the human, or model-reviewed off-loop
495        // when the parent is in bypass. The worker installs no checker without
496        // this, so the whole review chain would otherwise stay dormant.
497        spec.capabilities.enforce_permissions = true;
498        // Propagate "bypass permissions" so a self-orchestrating worker knows it
499        // is a bypassed parent and installs the off-loop model-reviewer for its
500        // children's forced-ask actions (Phase 6, Part B). The child session
501        // already carries the inherited flag (create_child_action seeds it).
502        spec.capabilities.bypass = session
503            .agent_runtime_state
504            .as_ref()
505            .is_some_and(|s| s.bypass_permissions);
506        // #73: propagate "no interactive human approver" (headless / scheduled /
507        // deployed root, inherited by the child session). When set, the worker's
508        // per-run approval proxy model-reviews a gated action locally instead of
509        // escalating to a human who will never answer (which would 300s-deny).
510        spec.capabilities.no_human_approver = session
511            .agent_runtime_state
512            .as_ref()
513            .is_some_and(|s| s.no_human_approver);
514        // #71: mark a READ-ONLY Guardian reviewer so the worker installs the
515        // read-only Bash allowlist checker. The reviewer is spawned by
516        // `spawn_guardian_review` with `subagent_type == "guardian"` (the SAME
517        // marker the completion coordinator branches on to parse the verdict) AND
518        // the `guardian_read_only_disabled_tools` denylist. Keyed off that role
519        // marker (already read above to set `identity.role`), so it rides the same
520        // session-metadata path the denylist/subagent_type use — no new wire seam.
521        // Without this the worker keeps an UNRESTRICTED Bash, so the reviewer could
522        // still `rm -rf` / `git push` / `curl | sh`, defeating "read-only".
523        spec.capabilities.guardian_read_only =
524            session.metadata.get("subagent_type").map(String::as_str) == Some("guardian");
525        // #193: route this role to a REMOTE resident worker when one is pinned.
526        // `spec.identity.role` was just computed from `subagent_type` above; a
527        // match flips the placement to Remote and rides the worker's bearer on the
528        // scoped secrets envelope (TLS handshake / Authorization header only — the
529        // token is never logged). No match leaves the default `Placement::Local`,
530        // so the local path is byte-for-byte unchanged for every non-pinned role.
531        if let Some(placement) = self.remote_placements.get(spec.identity.role.as_str()) {
532            spec.placement = Placement::Remote {
533                endpoint: placement.endpoint.clone(),
534            };
535            spec.secrets.worker_auth_token = placement.token.clone();
536        } else if let Some(placement) = self.schedulable_placements.get(spec.identity.role.as_str())
537        {
538            // #181 (P2b): route this role to a SCHEDULED worker — ONLY when it is
539            // NOT already pinned to a fixed remote endpoint (the `else if` makes
540            // remote_placements take precedence for a role in both). The concrete
541            // worker is picked at run time in `execute_external_child` from the bus
542            // (a live connected worker of the pool role). No per-placement bearer
543            // now — the bus connection uses the bus token. No match in either map
544            // leaves the default `Placement::Local`.
545            spec.placement = Placement::Schedulable {
546                pool: placement.pool.clone(),
547            };
548        }
549        spec
550    }
551
552    /// The `metadata["placement"]` JSON to stamp on a child from its resolved
553    /// placement, preferring the matching cluster node's `host_label` (its
554    /// operator label/host) over the raw endpoint/pool. `None` for a Local child
555    /// (the DTO defaults it to the backend's own host). Split out of
556    /// `execute_external_child` so the role→placement→host resolution is unit-testable.
557    fn placement_stamp_for(&self, spec: &ProvisionSpec) -> Option<String> {
558        let host_label = match &spec.placement {
559            Placement::Remote { .. } => self
560                .remote_placements
561                .get(spec.identity.role.as_str())
562                .and_then(|p| p.host_label.as_deref()),
563            Placement::Schedulable { .. } => self
564                .schedulable_placements
565                .get(spec.identity.role.as_str())
566                .and_then(|p| p.host_label.as_deref()),
567            Placement::Local => None,
568        };
569        placement_metadata(&spec.placement, host_label)
570    }
571
572    /// Pick a live worker for a SCHEDULABLE role from the BUS (#181, Phase 3):
573    /// ask the broker which actors are connected serving the pool role (presence
574    /// is connection-truth — no HTTP registry, no leases, no connect-fail
575    /// failover), then round-robin one per resolve for spread. Returns the chosen
576    /// worker's mailbox id. An empty pool ⇒ a terminal `AgentError` — NEVER a
577    /// local-subprocess fallback (that would silently defeat the placement).
578    async fn resolve_schedulable_worker(
579        &self,
580        role: &str,
581    ) -> std::result::Result<String, AgentError> {
582        let pool = self
583            .schedulable_placements
584            .get(role)
585            .ok_or_else(|| {
586                AgentError::LLM(format!(
587                    "schedulable placement for role '{role}' vanished before scheduling"
588                ))
589            })?
590            .pool
591            .clone();
592        let bus = self.bus.as_ref().ok_or_else(|| {
593            AgentError::LLM(format!(
594                "schedulable role '{role}': no mailbox bus configured (subagents.broker)"
595            ))
596        })?;
597
598        // Ask the BUS who is connected serving the pool role — presence is
599        // connection-truth (no HTTP registry, no leases, no stale-record failover).
600        let mut q = bamboo_broker::BrokerClient::connect(
601            &bus.endpoint,
602            bamboo_subagent::AgentRef {
603                session_id: format!("sched-q-{role}"),
604                role: None,
605            },
606            &bus.token,
607        )
608        .await
609        .map_err(|e| AgentError::LLM(format!("schedulable role '{role}': bus connect failed: {e}")))?;
610        let candidates = q.list_connected(&pool).await.map_err(|e| {
611            AgentError::LLM(format!("schedulable role '{role}': bus presence query failed: {e}"))
612        })?;
613
614        if candidates.is_empty() {
615            return Err(AgentError::LLM(format!(
616                "schedulable role '{role}': no live worker in pool '{pool}' on the bus \
617                 (NOT spawning a local subprocess — a schedulable role has no local fallback)"
618            )));
619        }
620
621        // Round-robin: advance a per-pool cursor once per resolve so successive
622        // sibling spawns spread across the connected pool workers. No failover
623        // needed — a listed worker is connected NOW (the bus only lists live
624        // subscribers), so there is no stale-but-leased candidate to skip.
625        let idx = {
626            let mut cursors = self.schedule_cursor.lock().recover_poison();
627            let cursor = cursors.entry(pool.clone()).or_insert(0);
628            let i = *cursor % candidates.len();
629            *cursor = cursor.wrapping_add(1);
630            i
631        };
632        Ok(candidates[idx].clone())
633    }
634}
635
636#[async_trait]
637impl ExternalChildRunner for ActorChildRunner {
638    async fn should_handle(&self, session: &Session) -> bool {
639        session.metadata.get("runtime.kind") == Some(&"external".to_string())
640            && session.metadata.get("external.protocol") == Some(&"actor".to_string())
641            && session.metadata.get("external.agent_id") == Some(&self.agent_id)
642    }
643
644    fn set_escalation_bridge(&self, bridge: Option<bamboo_subagent::executor::HostBridge>) {
645        *self.escalation_bridge.lock().recover_poison() = bridge;
646    }
647
648    async fn execute_external_child(
649        &self,
650        session: &mut Session,
651        job: &SpawnJob,
652        event_tx: mpsc::Sender<AgentEvent>,
653        cancel_token: CancellationToken,
654    ) -> crate::runtime::runner::Result<()> {
655        // #68 CORRECTNESS CRUX: capture the per-run escalation bridge HERE, at the
656        // moment this grandchild is spawned — while the parent run's bridge is
657        // still in our slot — into an owned local handed to `drive()` for this
658        // grandchild's whole lifetime. A fire-and-forget grandchild that OUTLIVES
659        // the run that spawned it must NOT re-read `self.escalation_bridge` at
660        // approval time: by then `run()` may have cleared/overwritten it (a worker
661        // serves runs sequentially), and re-proxying through a closed bridge
662        // fail-closed denies. Capturing at spawn pins the right bridge per run.
663        let escalation = self.escalation_bridge.lock().recover_poison().clone();
664        let assignment = extract_assignment(session);
665        let mut spec = self.build_spec(session, job);
666        // Mark the worker reusable + give it an idle timeout so it self-reaps if
667        // orphaned. Warm bus workers are pooled per fingerprint and reused.
668        spec.reusable = true;
669        if spec.limits.idle_timeout_secs.is_none() {
670            spec.limits.idle_timeout_secs = Some(POOLED_IDLE_TIMEOUT_SECS);
671        }
672        let pool_key = Self::fingerprint(&spec);
673        // Rehydration: the child session in the parent's store is the actor's
674        // durable state. Ship the full conversation so a reactivation
675        // (send_message / update / rerun) carries its history. A reused worker is
676        // stateless between runs, so this is also what isolates each child's
677        // context on a shared process.
678        let messages: Vec<serde_json::Value> = session
679            .messages
680            .iter()
681            .filter_map(|m| serde_json::to_value(m).ok())
682            .collect();
683
684        // Backpressure: hold a concurrency slot for the lifetime of the *run*
685        // (cancellation still proceeds — the cancel branch in drive() runs while
686        // we hold the permit). Released when this fn returns, i.e. once the worker
687        // is parked back into the pool, so idle workers don't pin slots.
688        let _slot = self
689            .concurrency
690            .acquire()
691            .await
692            .map_err(|_| AgentError::LLM("actor concurrency limiter closed".to_string()))?;
693
694        // Split LOCAL (spawn + warm-pool) from the two process-less remote paths
695        // ONLY at the divergent spots — acquire/connect here and the park/retire at
696        // the end. Everything between (Run dispatch, live-actor registration,
697        // drive, the close) is identical for all three. `kind` is the single guard.
698        //   - Local       (#0):  byte-for-byte the pre-#193 reuse-or-spawn path.
699        //   - Remote       (#194): connect to a FIXED resident endpoint, no spawn.
700        //   - Schedulable  (#181): resolve a live worker from the registry, connect.
701        let kind = match spec.placement {
702            Placement::Remote { .. } => PlacementKind::Remote,
703            Placement::Schedulable { .. } => PlacementKind::Schedulable,
704            Placement::Local => PlacementKind::Local,
705        };
706        let remote = !matches!(kind, PlacementKind::Local);
707
708        // Stamp WHICH machine this child runs on onto its session metadata, so the
709        // UI can show it (mirrored into the session index → SessionSummary.placement).
710        // Only remote/scheduled placements need a stamp — a Local child falls through
711        // to the DTO default (this backend's own host). Persisted by the caller with
712        // the rest of the child session after we return.
713        if let Some(placement_meta) = self.placement_stamp_for(&spec) {
714            session
715                .metadata
716                .insert("placement".to_string(), placement_meta);
717        }
718
719        // Retry-once loop: a pooled local worker can die between its liveness
720        // check and handling the Run (a tiny TOCTOU window) — its Run then sits
721        // queued with no server. The first-frame watchdog in `drive` surfaces that
722        // as `WorkerUnresponsive`; we reap the dead worker and re-acquire ONCE
723        // (which spawns fresh / reuses the next live one). Remote/schedulable have
724        // no spawn fallback, so they never retry.
725        let mut attempt = 0u8;
726        let (result, actor) = loop {
727        let (actor, mut client) = match kind {
728            PlacementKind::Remote => {
729                // REMOTE branch: connect to a resident worker. No spawn, no pool
730                // touch, no drain. We do not own the worker, so a connect failure
731                // has NO respawn fallback — it is a clear, terminal error.
732                let placement = self
733                    .remote_placements
734                    .get(spec.identity.role.as_str())
735                    .ok_or_else(|| {
736                        AgentError::LLM(format!(
737                            "remote placement for role '{}' vanished before connect",
738                            spec.identity.role
739                        ))
740                    })?;
741                let endpoint = placement.endpoint.clone();
742                // Build the TLS trust: a pinned CA pins a self-signed worker cert;
743                // otherwise default webpki roots (or plaintext for `ws://`).
744                let trust_cfg = match placement.ca_cert_file.as_deref() {
745                    Some(path) => Some(client_config_trusting_cert(path).map_err(|e| {
746                        AgentError::LLM(format!("remote worker CA cert '{}': {e}", path.display()))
747                    })?),
748                    None => None,
749                };
750                let client = ChildClient::connect_with_auth_tls(
751                    &endpoint,
752                    placement.token.as_deref(),
753                    trust_cfg,
754                )
755                .await
756                .map_err(|e| {
757                    AgentError::LLM(format!("remote actor connect to '{endpoint}' failed: {e}"))
758                })?;
759                // Process-less handle so live-actor registration (in-band steering)
760                // works exactly as for a local worker; `kill()` is a no-op.
761                let record = AgentRecord {
762                    agent_id: job.child_session_id.clone(),
763                    role: spec.identity.role.clone(),
764                    labels: Vec::new(),
765                    endpoint: endpoint.clone(),
766                    pid: 0,
767                    version: String::new(),
768                    started_at: chrono::Utc::now(),
769                    lease_expires_at: chrono::Utc::now(),
770                };
771                let _ = endpoint;
772                let actor = PooledWorker {
773                    worker: SpawnedChild::remote(record),
774                    mailbox_id: job.child_session_id.clone(),
775                };
776                let client: Box<dyn bamboo_subagent::ChildLink> = Box::new(client);
777                (actor, client)
778            }
779            PlacementKind::Schedulable => {
780                // SCHEDULABLE branch (#181): pick a LIVE worker of the pool role
781                // from the BUS (presence = connection-truth; no HTTP registry, no
782                // leases, no failover) and drive it by mailbox id. The pool worker
783                // stays connected and is reused next time. No spawn, no kill, NO
784                // local fallback — an empty pool is a terminal error (raised in
785                // resolve_schedulable_worker).
786                let bus = self.bus.as_ref().ok_or_else(|| {
787                    AgentError::LLM(
788                        "schedulable sub-agents require a mailbox bus (subagents.broker)"
789                            .to_string(),
790                    )
791                })?;
792                let mailbox_id = self
793                    .resolve_schedulable_worker(spec.identity.role.as_str())
794                    .await?;
795                let parent = bamboo_subagent::AgentRef {
796                    session_id: format!("p-{}", job.child_session_id),
797                    role: None,
798                };
799                let link = bamboo_broker::BrokerChildLink::connect(
800                    &bus.endpoint,
801                    parent,
802                    &bus.token,
803                    mailbox_id.clone(),
804                )
805                .await
806                .map_err(|e| {
807                    AgentError::LLM(format!("schedulable link connect to '{mailbox_id}' failed: {e}"))
808                })?;
809                // Process-less handle — a bus-resident pool worker is never ours to
810                // kill (remote ⇒ dropped, not pooled, after the run).
811                let actor = PooledWorker {
812                    worker: SpawnedChild::remote(AgentRecord {
813                        agent_id: mailbox_id.clone(),
814                        role: spec.identity.role.clone(),
815                        labels: Vec::new(),
816                        endpoint: bus.endpoint.clone(),
817                        pid: 0,
818                        version: String::new(),
819                        started_at: chrono::Utc::now(),
820                        lease_expires_at: chrono::Utc::now(),
821                    }),
822                    mailbox_id,
823                };
824                let client: Box<dyn bamboo_subagent::ChildLink> = Box::new(link);
825                (actor, client)
826            }
827            PlacementKind::Local => {
828                // LOCAL = the mailbox bus (the unified transport): check out a warm
829                // pooled worker (reuse a live parked one, else spawn fresh) and
830                // drive it by mailbox id — no listen socket, no file discovery, no
831                // respawn-on-connect-miss (the broker queues the Run until the
832                // worker handles it). The legacy direct-WS path was retired; the bus
833                // is required.
834                let bus = self.bus.as_ref().ok_or_else(|| {
835                    AgentError::LLM(
836                        "local sub-agents require a mailbox bus (subagents.broker); none is \
837                         configured and the bus could not be embedded"
838                            .to_string(),
839                    )
840                })?;
841                let actor = self.acquire_bus_worker(&pool_key, &spec).await?;
842                let parent = bamboo_subagent::AgentRef {
843                    session_id: format!("p-{}", job.child_session_id),
844                    role: None,
845                };
846                let link = bamboo_broker::BrokerChildLink::connect(
847                    &bus.endpoint,
848                    parent,
849                    &bus.token,
850                    actor.mailbox_id.clone(),
851                )
852                .await
853                .map_err(|e| AgentError::LLM(format!("broker child link connect failed: {e}")))?;
854                let client: Box<dyn bamboo_subagent::ChildLink> = Box::new(link);
855                (actor, client)
856            }
857        };
858
859        if let Err(e) = client
860            .send(ParentFrame::Run(RunSpec {
861                // Cloned (not moved) so a retry can re-dispatch to a fresh worker.
862                assignment: assignment.clone(),
863                reasoning_effort: None,
864                messages: messages.clone(),
865            }))
866            .await
867        {
868            if !remote {
869                actor.worker.kill().await;
870            }
871            return Err(AgentError::LLM(format!("actor run dispatch failed: {e}")));
872        }
873
874        // Register as a live actor so send_message (running, no interrupt) can
875        // steer this child in-band over the existing WS connection. The guard
876        // unregisters on every exit path.
877        let (live_tx, mut live_rx) = mpsc::unbounded_channel::<ParentFrame>();
878        let live_guard = super::live::register(&job.child_session_id, live_tx);
879
880        let result = drive(
881            &mut *client,
882            &job.child_session_id,
883            self.approval_decider.as_ref(),
884            escalation.clone(),
885            &event_tx,
886            &cancel_token,
887            &mut live_rx,
888            // First-frame watchdog for EVERY placement: a wedged-but-connected
889            // worker (subscribed ≠ serving — e.g. stuck on a prior LLM call) emits
890            // no first frame; without a deadline drive() blocks forever. Bounding it
891            // turns the "running-but-unresponsive" hang into a recoverable
892            // WorkerUnresponsive (reap+respawn local / re-pick schedulable / error
893            // on a fixed remote endpoint).
894            Some(WORKER_FIRST_FRAME_TIMEOUT),
895        )
896        .await;
897        // Unregister IMMEDIATELY: after drive returns nobody consumes live_rx,
898        // so a send_message landing in the close/park window below must see
899        // "not live" and take the durable-queue fallback instead of vanishing.
900        // (Even if one slipped in earlier, send_message also appends it to the
901        // durable transcript, so the next activation still rehydrates it.)
902        drop(live_guard);
903        // Close the parent link (dropping it closes our broker connection; the
904        // worker stays dialed-in + subscribed, ready for its next Run).
905        drop(client);
906
907        // No first frame ⇒ the worker is wedged. Recover ONCE before giving up:
908        //   - Local: reap the dead pooled worker + respawn.
909        //   - Schedulable: not ours to kill — drop it and re-select a live pool
910        //     member (a wedged worker must not fail the run when the pool has others).
911        //   - Remote: a FIXED endpoint has no alternative — fall through to a bounded
912        //     WorkerUnresponsive error (far better than the previous infinite hang).
913        if attempt == 0 && matches!(result, Err(AgentError::WorkerUnresponsive(_))) {
914            match kind {
915                PlacementKind::Local => {
916                    tracing::warn!(
917                        "actor child {} got no first frame; reaping the worker and respawning once",
918                        job.child_session_id
919                    );
920                    actor.worker.kill().await;
921                    attempt += 1;
922                    continue;
923                }
924                PlacementKind::Schedulable => {
925                    tracing::warn!(
926                        "scheduled actor child {} got no first frame; re-selecting a pool worker",
927                        job.child_session_id
928                    );
929                    drop(actor);
930                    attempt += 1;
931                    continue;
932                }
933                PlacementKind::Remote => {}
934            }
935        }
936        break (result, actor);
937        };
938
939        // Park the warm worker for reuse on a clean run, or kill it on
940        // error/cancel (a wedged worker must not be reused). Remote / schedulable
941        // workers are registry-managed — never ours to pool/kill, just drop.
942        if remote {
943            drop(actor);
944        } else {
945            match &result {
946                Ok(_) => self.release_bus_worker(&pool_key, actor).await,
947                Err(_) => actor.worker.kill().await,
948            }
949        }
950
951        // Write-back: persist the actor's final reply onto the child session so
952        // the transcript survives and the NEXT activation sees it as history.
953        // (run_child_spawn saves the session right after we return.)
954        match result {
955            Ok(Some(text)) => {
956                if !text.is_empty() {
957                    session.add_message(bamboo_agent_core::Message::assistant(text, None));
958                }
959                Ok(())
960            }
961            Ok(None) => Ok(()),
962            Err(e) => Err(e),
963        }
964    }
965}
966
967/// The `{kind,host}` placement descriptor stamped onto a child session's metadata
968/// under `"placement"` — read back by the storage index → `SessionSummary.placement`
969/// → the UI's machine badge. `None` for `Local` (those fall through to the DTO's
970/// default of this backend's own host). The value is a JSON string matching
971/// `bamboo_storage::SessionPlacement { kind, host }`.
972fn placement_metadata(placement: &Placement, host_label: Option<&str>) -> Option<String> {
973    // Prefer the cluster node's own label/host (its metadata) when the placement
974    // maps to a node; else fall back to the raw endpoint host / pool name.
975    let value = match placement {
976        Placement::Local => return None,
977        Placement::Remote { endpoint } => serde_json::json!({
978            "kind": "remote",
979            "host": host_label.map(str::to_string).unwrap_or_else(|| host_of_endpoint(endpoint)),
980        }),
981        Placement::Schedulable { pool } => serde_json::json!({
982            "kind": "remote",
983            "host": host_label.unwrap_or(pool),
984        }),
985    };
986    serde_json::to_string(&value).ok()
987}
988
989/// Extract the host from a `ws[s]://host:port[/path]` bus endpoint, for display.
990fn host_of_endpoint(endpoint: &str) -> String {
991    endpoint
992        .trim()
993        .trim_start_matches("wss://")
994        .trim_start_matches("ws://")
995        .split(['/', ':'])
996        .next()
997        .unwrap_or(endpoint)
998        .to_string()
999}
1000
1001/// Pump child frames -> parent events until a terminal frame (or cancellation).
1002/// On success, yields the actor's final result text (for session write-back).
1003/// `live_rx` carries in-band frames (steering messages) from the live registry.
1004///
1005/// `escalation_bridge` (#68) is the per-run escalation host bridge CAPTURED BY
1006/// VALUE at spawn time in `execute_external_child` (NOT read live here): when a
1007/// non-bypass child re-proxies an approval request, this owned bridge routes it
1008/// UP to the parent run. Owning it for the call's lifetime is what lets a
1009/// fire-and-forget grandchild that outlives its spawning run still escalate to
1010/// the correct (then-current) parent bridge rather than a stale/overwritten one.
1011async fn drive(
1012    client: &mut dyn bamboo_subagent::ChildLink,
1013    child_session_id: &str,
1014    approval_decider: Option<&Arc<dyn ChildApprovalDecider>>,
1015    escalation_bridge: Option<bamboo_subagent::executor::HostBridge>,
1016    event_tx: &mpsc::Sender<AgentEvent>,
1017    cancel_token: &CancellationToken,
1018    live_rx: &mut mpsc::UnboundedReceiver<ParentFrame>,
1019    first_frame_timeout: Option<Duration>,
1020) -> crate::runtime::runner::Result<Option<String>> {
1021    // First-frame watchdog: a live worker emits its first frame (run-started /
1022    // first token) within seconds; total silence past the deadline means the
1023    // worker is dead (e.g. a pooled worker that exited right after checkout), so
1024    // its Run sits queued forever. We trip ONLY before the first frame — once any
1025    // frame arrives the worker is proven live and a legitimately long run (a slow
1026    // tool between tokens) never trips it.
1027    let mut got_first_frame = false;
1028    let mut first_frame_watch = first_frame_timeout.map(|d| Box::pin(tokio::time::sleep(d)));
1029    loop {
1030        tokio::select! {
1031            _ = cancel_token.cancelled() => {
1032                // fall through to the cancel handling below
1033                break;
1034            }
1035            _ = async {
1036                match first_frame_watch.as_mut() {
1037                    Some(s) => s.as_mut().await,
1038                    None => std::future::pending::<()>().await,
1039                }
1040            }, if !got_first_frame => {
1041                return Err(AgentError::WorkerUnresponsive(format!(
1042                    "child {child_session_id} produced no frame within {:?}",
1043                    first_frame_timeout.unwrap_or_default()
1044                )));
1045            }
1046            Some(frame) = live_rx.recv() => {
1047                // Forward in-band steering to the worker over the existing WS.
1048                if client.send(frame).await.is_err() {
1049                    tracing::warn!("live steering frame could not be sent; connection failing");
1050                }
1051            }
1052            frame = client.next_frame() => {
1053                // Any frame (event / approval / terminal / close / error) proves
1054                // the worker responded — disarm the first-frame watchdog.
1055                got_first_frame = true;
1056                first_frame_watch = None;
1057                match frame {
1058                    Ok(Some(ChildFrame::Event { event })) => {
1059                        // AgentEvent is serialized verbatim on the wire (zero mapping).
1060                        if let Ok(ev) = serde_json::from_value::<AgentEvent>(event) {
1061                            let _ = event_tx.send(ev).await;
1062                        }
1063                    }
1064                    Ok(Some(ChildFrame::ApprovalRequest { id, body })) => {
1065                        // Phase 2: a worker proxied a gated-tool approval back to
1066                        // the host. The WORKER side is live — its executor installs
1067                        // a per-run task-local `ApprovalProxy` (subagent_worker.rs)
1068                        // that calls `host.approval_call`, so this frame arrives
1069                        // when a child hits `ConfirmationRequired`.
1070                        if let Some(reviewer) = child_approval_reviewer() {
1071                            // Phase 6, Part B: a BYPASSED parent worker
1072                            // model-reviews its children's forced-ask (dangerous)
1073                            // actions. The review is an LLM call, so run it OFF
1074                            // the frame pump in a spawned task and deliver the
1075                            // verdict async via the live channel — the pump keeps
1076                            // forwarding events and the agent loop never blocks. A
1077                            // timeout denies a hung review so the child can't hang.
1078                            let child = child_session_id.to_string();
1079                            let req_id = id.clone();
1080                            let body = body.clone();
1081                            tokio::spawn(async move {
1082                                let approved = tokio::time::timeout(
1083                                    CHILD_APPROVAL_TIMEOUT,
1084                                    reviewer.review(&child, &body),
1085                                )
1086                                .await
1087                                .unwrap_or(false);
1088                                super::live::deliver_approval(&child, &req_id, approved);
1089                            });
1090                        } else if approval_decider.is_some() {
1091                            // A decider is wired (policy / auto): decide promptly
1092                            // and reply inline. (Must not block the pump — see the
1093                            // `ChildApprovalDecider` doc.)
1094                            let approved =
1095                                decide_child_approval(approval_decider, child_session_id, &body)
1096                                    .await;
1097                            if client
1098                                .send(ParentFrame::ApprovalReply { id, approved })
1099                                .await
1100                                .is_err()
1101                            {
1102                                tracing::warn!(
1103                                    "failed to answer approval_request; connection failing"
1104                                );
1105                            }
1106                        } else if let Some(host) = escalation_bridge.clone() {
1107                            // Non-bypass WORKER: ESCALATE up our own actor link
1108                            // (re-proxy) so the request chains to our parent — and
1109                            // up every level until a bypass level (model-review) or
1110                            // the top orchestrator (human) decides. Off-loop so the
1111                            // pump never blocks; relay the reply down to the child.
1112                            let child = child_session_id.to_string();
1113                            let req_id = id.clone();
1114                            let body = body.clone();
1115                            tokio::spawn(async move {
1116                                let approved = match tokio::time::timeout(
1117                                    CHILD_APPROVAL_TIMEOUT,
1118                                    host.approval_call(body),
1119                                )
1120                                .await
1121                                {
1122                                    Ok(Ok(reply)) => reply
1123                                        .get("approved")
1124                                        .and_then(|v| v.as_bool())
1125                                        .unwrap_or(false),
1126                                    // Transport error or timeout ⇒ fail closed.
1127                                    _ => false,
1128                                };
1129                                super::live::deliver_approval(&child, &req_id, approved);
1130                            });
1131                        } else {
1132                            // Top orchestrator (no escalation bridge): human-in-the-
1133                            // loop. Surface the request on the parent's event stream
1134                            // and DEFER — the decision arrives out-of-band via
1135                            // `live::deliver_approval(child, request_id, approved)`
1136                            // (→ this child's `live_rx` → forwarded to the worker
1137                            // above). A timeout denies a never-answered request so
1138                            // it can't hang the child forever.
1139                            let (tool_name, permission, resource) =
1140                                approval_request_fields(&body);
1141                            // Register the pending request BEFORE surfacing it so
1142                            // the external handler's `deliver_approval_checked` can
1143                            // correlate an out-of-band POST against a genuine
1144                            // human-loop request (and consume it one-shot).
1145                            super::live::register_pending_approval(child_session_id, &id);
1146                            let _ = event_tx
1147                                .send(AgentEvent::ChildApprovalRequested {
1148                                    child_session_id: child_session_id.to_string(),
1149                                    request_id: id.clone(),
1150                                    tool_name,
1151                                    permission,
1152                                    resource,
1153                                })
1154                                .await;
1155                            let child = child_session_id.to_string();
1156                            tokio::spawn(async move {
1157                                tokio::time::sleep(CHILD_APPROVAL_TIMEOUT).await;
1158                                // Deny only if still pending: a one-shot consume so
1159                                // we don't double-deliver if the human already
1160                                // answered (the POST took it), and so a late POST
1161                                // after this fires finds nothing pending.
1162                                if super::live::take_pending_approval(&child, &id) {
1163                                    super::live::deliver_approval(&child, &id, false);
1164                                }
1165                            });
1166                        }
1167                    }
1168                    Ok(Some(ChildFrame::Terminal { status, result, error, .. })) => {
1169                        return match status {
1170                            TerminalStatus::Completed => Ok(result),
1171                            TerminalStatus::Cancelled => Err(AgentError::Cancelled),
1172                            TerminalStatus::Error => Err(AgentError::LLM(
1173                                error.unwrap_or_else(|| "actor child errored".to_string()),
1174                            )),
1175                            // The suspend/resume round-trip (host re-dispatch of a
1176                            // nested parent) is not wired here yet; a worker in
1177                            // this build never emits Suspended, so this is
1178                            // unreachable in practice.
1179                            TerminalStatus::Suspended => Err(AgentError::LLM(
1180                                "nested sub-agent suspend received but resume transport is not wired"
1181                                    .to_string(),
1182                            )),
1183                        };
1184                    }
1185                    Ok(None) => {
1186                        return Err(AgentError::LLM(
1187                            "actor child closed before terminal".to_string(),
1188                        ));
1189                    }
1190                    Err(e) => {
1191                        return Err(AgentError::LLM(format!("actor transport error: {e}")));
1192                    }
1193                }
1194            }
1195        }
1196    }
1197
1198    // Only reached on cancellation: ask the child to stop (best-effort), then report cancelled.
1199    let _ = client.send(ParentFrame::Cancel).await;
1200    Err(AgentError::Cancelled)
1201}
1202
1203/// The assignment text = the child session's latest user message (falls back to its title).
1204fn extract_assignment(session: &Session) -> String {
1205    session
1206        .messages
1207        .iter()
1208        .rev()
1209        .find(|m| matches!(m.role, Role::User))
1210        .map(|m| m.content.clone())
1211        .unwrap_or_else(|| {
1212            session
1213                .metadata
1214                .get("title")
1215                .cloned()
1216                .unwrap_or_else(|| "Execute task".to_string())
1217        })
1218}
1219
1220#[cfg(test)]
1221mod tests {
1222    use super::*;
1223
1224    fn spec_with(
1225        role: &str,
1226        provider: &str,
1227        model: &str,
1228        workspace: Option<&str>,
1229        disabled: Option<Vec<&str>>,
1230    ) -> ProvisionSpec {
1231        let mut spec = ProvisionSpec::new(
1232            ChildIdentity {
1233                child_id: "c".into(),
1234                parent_id: None,
1235                project_key: None,
1236                role: role.into(),
1237                depth: 0,
1238            },
1239            ExecutorSpec::Echo,
1240            "/tmp/fab".into(),
1241        );
1242        spec.workspace = workspace.map(|w| w.to_string());
1243        spec.model = Some(ModelRefSpec {
1244            provider: provider.into(),
1245            model: model.into(),
1246        });
1247        spec.disabled_tools = disabled.map(|d| d.into_iter().map(String::from).collect());
1248        spec
1249    }
1250
1251    #[test]
1252    fn fingerprint_matches_interchangeable_children() {
1253        // Same role/provider/model/workspace and equal tool sets (order-insensitive)
1254        // are interchangeable on one warm worker — and differ only in child_id.
1255        let a = spec_with(
1256            "explorer",
1257            "p",
1258            "m",
1259            Some("/ws"),
1260            Some(vec!["Bash", "Edit"]),
1261        );
1262        let mut b = spec_with(
1263            "explorer",
1264            "p",
1265            "m",
1266            Some("/ws"),
1267            Some(vec!["Edit", "Bash"]),
1268        );
1269        b.identity.child_id = "other".into();
1270        assert_eq!(
1271            ActorChildRunner::fingerprint(&a),
1272            ActorChildRunner::fingerprint(&b)
1273        );
1274    }
1275
1276    #[test]
1277    fn fingerprint_separates_distinct_runtimes() {
1278        let base = spec_with("explorer", "p", "m", Some("/ws"), None);
1279        let base_fp = ActorChildRunner::fingerprint(&base);
1280        // Each axis that is baked into the worker must split the pool bucket.
1281        assert_ne!(
1282            base_fp,
1283            ActorChildRunner::fingerprint(&spec_with("writer", "p", "m", Some("/ws"), None))
1284        );
1285        assert_ne!(
1286            base_fp,
1287            ActorChildRunner::fingerprint(&spec_with("explorer", "p2", "m", Some("/ws"), None))
1288        );
1289        assert_ne!(
1290            base_fp,
1291            ActorChildRunner::fingerprint(&spec_with("explorer", "p", "m2", Some("/ws"), None))
1292        );
1293        assert_ne!(
1294            base_fp,
1295            ActorChildRunner::fingerprint(&spec_with("explorer", "p", "m", Some("/ws2"), None))
1296        );
1297        assert_ne!(
1298            base_fp,
1299            ActorChildRunner::fingerprint(&spec_with(
1300                "explorer",
1301                "p",
1302                "m",
1303                Some("/ws"),
1304                Some(vec!["Bash"])
1305            ))
1306        );
1307    }
1308
1309    #[test]
1310    fn fingerprint_splits_on_baked_capabilities() {
1311        // Every capability baked once at provision time must split the pool
1312        // bucket, else a worker baked for one posture gets reused for another
1313        // (e.g. a depth-1 worker re-stamping spawn_depth onto a depth-4 child,
1314        // breaking the depth cap; or a bypass worker reused for a non-bypass one).
1315        let base_fp =
1316            ActorChildRunner::fingerprint(&spec_with("explorer", "p", "m", Some("/ws"), None));
1317
1318        let mut depth = spec_with("explorer", "p", "m", Some("/ws"), None);
1319        depth.identity.depth = 2;
1320        assert_ne!(
1321            base_fp,
1322            ActorChildRunner::fingerprint(&depth),
1323            "depth must split"
1324        );
1325
1326        let mut nested = spec_with("explorer", "p", "m", Some("/ws"), None);
1327        nested.capabilities.nested_spawn = true;
1328        assert_ne!(
1329            base_fp,
1330            ActorChildRunner::fingerprint(&nested),
1331            "nested_spawn must split"
1332        );
1333
1334        let mut bypass = spec_with("explorer", "p", "m", Some("/ws"), None);
1335        bypass.capabilities.bypass = true;
1336        assert_ne!(
1337            base_fp,
1338            ActorChildRunner::fingerprint(&bypass),
1339            "bypass must split"
1340        );
1341
1342        let mut enforce = spec_with("explorer", "p", "m", Some("/ws"), None);
1343        enforce.capabilities.enforce_permissions = true;
1344        assert_ne!(
1345            base_fp,
1346            ActorChildRunner::fingerprint(&enforce),
1347            "enforce_permissions must split"
1348        );
1349
1350        let mut cap = spec_with("explorer", "p", "m", Some("/ws"), None);
1351        cap.capabilities.max_spawn_depth = Some(8);
1352        assert_ne!(
1353            base_fp,
1354            ActorChildRunner::fingerprint(&cap),
1355            "max_spawn_depth must split"
1356        );
1357
1358        // #73 (P1): the worker bakes `no_human_review` from this flag once at
1359        // build(), so it MUST split the pool or a worker baked for one approval
1360        // posture is reused for the opposite one.
1361        let mut nha = spec_with("explorer", "p", "m", Some("/ws"), None);
1362        nha.capabilities.no_human_approver = true;
1363        assert_ne!(
1364            base_fp,
1365            ActorChildRunner::fingerprint(&nha),
1366            "no_human_approver must split"
1367        );
1368
1369        // #71: the read-only Bash checker is baked once at build() from this flag,
1370        // so a guardian reviewer worker must not be reused for an ordinary child.
1371        let mut gro = spec_with("explorer", "p", "m", Some("/ws"), None);
1372        gro.capabilities.guardian_read_only = true;
1373        assert_ne!(
1374            base_fp,
1375            ActorChildRunner::fingerprint(&gro),
1376            "guardian_read_only must split"
1377        );
1378    }
1379
1380    struct StaticDecider(bool);
1381
1382    #[async_trait]
1383    impl ChildApprovalDecider for StaticDecider {
1384        async fn decide(&self, _child: &str, _req: &serde_json::Value) -> bool {
1385            self.0
1386        }
1387    }
1388
1389    // ---- first-frame watchdog (dead-pooled-worker recovery) -----------------
1390
1391    /// A link that never yields a frame — models a worker that died (or never
1392    /// subscribed) so its Run sits queued with no server.
1393    struct SilentLink;
1394    #[async_trait]
1395    impl bamboo_subagent::ChildLink for SilentLink {
1396        async fn send(&mut self, _: ParentFrame) -> bamboo_subagent::TransportResult<()> {
1397            Ok(())
1398        }
1399        async fn next_frame(
1400            &mut self,
1401        ) -> bamboo_subagent::TransportResult<Option<ChildFrame>> {
1402            std::future::pending().await
1403        }
1404    }
1405
1406    /// A link that immediately yields one terminal frame (a healthy fast worker).
1407    struct InstantTerminalLink {
1408        done: bool,
1409    }
1410    #[async_trait]
1411    impl bamboo_subagent::ChildLink for InstantTerminalLink {
1412        async fn send(&mut self, _: ParentFrame) -> bamboo_subagent::TransportResult<()> {
1413            Ok(())
1414        }
1415        async fn next_frame(
1416            &mut self,
1417        ) -> bamboo_subagent::TransportResult<Option<ChildFrame>> {
1418            if self.done {
1419                std::future::pending().await
1420            } else {
1421                self.done = true;
1422                Ok(Some(ChildFrame::Terminal {
1423                    status: TerminalStatus::Completed,
1424                    result: Some("done".into()),
1425                    error: None,
1426                    transcript: vec![],
1427                }))
1428            }
1429        }
1430    }
1431
1432    #[tokio::test]
1433    async fn drive_trips_first_frame_watchdog_on_a_silent_worker() {
1434        let (event_tx, _rx) = mpsc::channel::<AgentEvent>(8);
1435        let cancel = CancellationToken::new();
1436        let (_live_tx, mut live_rx) = mpsc::unbounded_channel::<ParentFrame>();
1437        let mut link = SilentLink;
1438        let r = drive(
1439            &mut link,
1440            "child-x",
1441            None,
1442            None,
1443            &event_tx,
1444            &cancel,
1445            &mut live_rx,
1446            Some(Duration::from_millis(100)),
1447        )
1448        .await;
1449        assert!(
1450            matches!(r, Err(AgentError::WorkerUnresponsive(_))),
1451            "a silent worker must trip the first-frame watchdog, got {r:?}"
1452        );
1453    }
1454
1455    #[tokio::test]
1456    async fn drive_does_not_trip_when_a_frame_arrives() {
1457        let (event_tx, _rx) = mpsc::channel::<AgentEvent>(8);
1458        let cancel = CancellationToken::new();
1459        let (_live_tx, mut live_rx) = mpsc::unbounded_channel::<ParentFrame>();
1460        let mut link = InstantTerminalLink { done: false };
1461        // Even a tiny timeout must NOT trip: the terminal frame arrives first and
1462        // disarms the watchdog.
1463        let r = drive(
1464            &mut link,
1465            "child-y",
1466            None,
1467            None,
1468            &event_tx,
1469            &cancel,
1470            &mut live_rx,
1471            Some(Duration::from_millis(50)),
1472        )
1473        .await;
1474        assert_eq!(r.ok().flatten().as_deref(), Some("done"));
1475    }
1476
1477    #[tokio::test]
1478    async fn child_approval_fails_closed_without_decider() {
1479        // No decider wired ⇒ the host denies (safe default), unchanged behavior.
1480        let body = serde_json::json!({"tool_name":"Bash","permission":"run","resource":"rm -rf /"});
1481        assert!(!decide_child_approval(None, "child-1", &body).await);
1482    }
1483
1484    #[tokio::test]
1485    async fn child_approval_honors_wired_decider() {
1486        let body =
1487            serde_json::json!({"tool_name":"Write","permission":"write","resource":"/tmp/x"});
1488        let approve: Arc<dyn ChildApprovalDecider> = Arc::new(StaticDecider(true));
1489        let deny: Arc<dyn ChildApprovalDecider> = Arc::new(StaticDecider(false));
1490        assert!(decide_child_approval(Some(&approve), "child-1", &body).await);
1491        assert!(!decide_child_approval(Some(&deny), "child-1", &body).await);
1492    }
1493
1494    #[test]
1495    fn approval_request_fields_extracts_and_defaults() {
1496        let full = serde_json::json!({"tool_name":"Bash","permission":"run","resource":"ls"});
1497        assert_eq!(
1498            approval_request_fields(&full),
1499            ("Bash".to_string(), "run".to_string(), "ls".to_string())
1500        );
1501        // Missing fields default to empty strings.
1502        let partial = serde_json::json!({"tool_name":"Write"});
1503        assert_eq!(
1504            approval_request_fields(&partial),
1505            ("Write".to_string(), String::new(), String::new())
1506        );
1507    }
1508
1509    // ---- #193: remote placement routing -------------------------------------
1510
1511    use crate::runtime::execution::SpawnJob;
1512    use bamboo_agent_core::Session;
1513
1514    /// A runner with a BOGUS worker_bin (`/bin/false`): a local spawn here would
1515    /// FAIL, so a passing remote test proves the remote path never spawns.
1516    fn bogus_runner(placements: HashMap<String, ResolvedRemotePlacement>) -> ActorChildRunner {
1517        ActorChildRunner::new(
1518            "test-actor".into(),
1519            PathBuf::from("/bin/false"),
1520            vec![],
1521            std::env::temp_dir().join("bamboo-test-fab-193"),
1522            ExecutorSpec::Echo,
1523            vec![],
1524            "anthropic".into(),
1525            4,
1526        )
1527        .with_remote_placements(placements)
1528    }
1529
1530    /// A child session of the given role (the role rides `subagent_type`, the
1531    /// path build_spec + the remote lookup both read).
1532    fn session_of_role(role: &str, assignment: &str) -> Session {
1533        let mut s = Session::new("child-1", "test-model");
1534        s.metadata
1535            .insert("subagent_type".to_string(), role.to_string());
1536        s.add_message(bamboo_agent_core::Message::user(assignment));
1537        s
1538    }
1539
1540    fn job_for(child: &str) -> SpawnJob {
1541        SpawnJob {
1542            parent_session_id: "parent-1".into(),
1543            child_session_id: child.into(),
1544            model: String::new(),
1545            disabled_tools: None,
1546        }
1547    }
1548
1549    #[test]
1550    fn build_spec_sets_remote_placement_for_matching_role() {
1551        let mut placements = HashMap::new();
1552        placements.insert(
1553            "explorer".to_string(),
1554            ResolvedRemotePlacement {
1555                endpoint: "wss://gpu-host:8443".into(),
1556                token: Some("T-secret".into()),
1557                ca_cert_file: None,
1558                host_label: None,
1559            },
1560        );
1561        let runner = bogus_runner(placements);
1562
1563        // Matching role -> Placement::Remote + the bearer on the secrets envelope.
1564        let s = session_of_role("explorer", "do the thing");
1565        let spec = runner.build_spec(&s, &job_for("child-1"));
1566        match &spec.placement {
1567            Placement::Remote { endpoint } => assert_eq!(endpoint, "wss://gpu-host:8443"),
1568            other => panic!("expected Remote, got {other:?}"),
1569        }
1570        assert_eq!(spec.secrets.worker_auth_token.as_deref(), Some("T-secret"));
1571    }
1572
1573    #[test]
1574    fn build_spec_leaves_local_for_unmatched_role() {
1575        let mut placements = HashMap::new();
1576        placements.insert(
1577            "explorer".to_string(),
1578            ResolvedRemotePlacement {
1579                endpoint: "wss://gpu-host:8443".into(),
1580                token: Some("T".into()),
1581                ca_cert_file: None,
1582                host_label: None,
1583            },
1584        );
1585        let runner = bogus_runner(placements);
1586
1587        // A DIFFERENT role keeps the default Local placement + no bearer.
1588        let s = session_of_role("writer", "do the thing");
1589        let spec = runner.build_spec(&s, &job_for("child-1"));
1590        assert_eq!(spec.placement, Placement::Local);
1591        assert!(spec.secrets.worker_auth_token.is_none());
1592    }
1593
1594    #[test]
1595    fn build_spec_local_when_no_placements() {
1596        let runner = bogus_runner(HashMap::new());
1597        let s = session_of_role("explorer", "do the thing");
1598        let spec = runner.build_spec(&s, &job_for("child-1"));
1599        assert_eq!(spec.placement, Placement::Local);
1600        assert!(spec.secrets.worker_auth_token.is_none());
1601    }
1602
1603    #[test]
1604    fn placement_metadata_stamps_remote_and_schedulable_not_local() {
1605        // Local children carry no stamp — the DTO defaults them to the backend host.
1606        assert_eq!(placement_metadata(&Placement::Local, None), None);
1607
1608        // Remote, no node label → host derived from the endpoint.
1609        let r = placement_metadata(
1610            &Placement::Remote {
1611                endpoint: "wss://10.0.0.5:8443/stream".into(),
1612            },
1613            None,
1614        )
1615        .unwrap();
1616        assert!(r.contains(r#""kind":"remote""#), "{r}");
1617        assert!(r.contains(r#""host":"10.0.0.5""#), "{r}");
1618
1619        // A cluster node's label (its metadata) OVERRIDES the raw endpoint host.
1620        let labeled = placement_metadata(
1621            &Placement::Remote {
1622                endpoint: "ws://169.254.230.101:8899".into(),
1623            },
1624            Some("mini"),
1625        )
1626        .unwrap();
1627        assert!(labeled.contains(r#""host":"mini""#), "{labeled}");
1628
1629        // Schedulable → {kind:"remote", host:<node label, else pool>}.
1630        let s =
1631            placement_metadata(&Placement::Schedulable { pool: "explorers".into() }, Some("mini"))
1632                .unwrap();
1633        assert!(s.contains(r#""kind":"remote""#), "{s}");
1634        assert!(s.contains(r#""host":"mini""#), "{s}");
1635
1636        // The stamp round-trips through the storage placement type.
1637        let p: bamboo_storage::SessionPlacement = serde_json::from_str(&labeled).unwrap();
1638        assert_eq!(p.kind, "remote");
1639        assert_eq!(p.host, "mini");
1640    }
1641
1642    /// End-to-end remote run through `execute_external_child`: a resident worker
1643    /// (Bearer-gated `WsServer` + `EchoExecutor`) serves the role; the runner is
1644    /// built with a `remote_placements` entry pointing at it AND a BOGUS
1645    /// worker_bin (`/bin/false`). A passing test proves the remote path CONNECTS
1646    /// to the resident worker and NEVER spawns (a spawn would fail on /bin/false),
1647    /// and that a terminal/echo result flows back.
1648    #[tokio::test]
1649    async fn execute_external_child_routes_role_to_remote_worker_without_spawning() {
1650        // 1. Stand up the resident worker on loopback with a required bearer.
1651        let token = "remote-test-token";
1652        let server = bamboo_subagent::transport::WsServer::bind_with_token(
1653            (std::net::Ipv4Addr::LOCALHOST, 0).into(),
1654            Some(token.to_string()),
1655        )
1656        .await
1657        .expect("bind resident worker");
1658        let endpoint = server.ws_endpoint(); // ws://127.0.0.1:<port>
1659        let srv = tokio::spawn(async move {
1660            // serve() loops connection-after-connection; the test exits, dropping it.
1661            let _ = server
1662                .serve(Arc::new(bamboo_subagent::executor::EchoExecutor))
1663                .await;
1664        });
1665
1666        // 2. Build the runner: role "explorer" pinned remote, bogus worker_bin.
1667        let mut placements = HashMap::new();
1668        placements.insert(
1669            "explorer".to_string(),
1670            ResolvedRemotePlacement {
1671                endpoint: endpoint.clone(),
1672                token: Some(token.to_string()),
1673                ca_cert_file: None,
1674                host_label: Some("mini-e2e".into()), // node label, surfaced on the badge
1675            },
1676        );
1677        let runner = bogus_runner(placements);
1678
1679        // 3. Drive a real run for that role.
1680        let mut session = session_of_role("explorer", "hello remote");
1681        let job = job_for("child-1");
1682        let (event_tx, mut event_rx) = mpsc::channel::<AgentEvent>(64);
1683        let cancel = CancellationToken::new();
1684
1685        let result = tokio::time::timeout(
1686            Duration::from_secs(10),
1687            runner.execute_external_child(&mut session, &job, event_tx, cancel),
1688        )
1689        .await
1690        .expect("run did not hang")
1691        .expect("remote run succeeded (connected to resident worker, did not spawn)");
1692
1693        let _ = result;
1694        // The EchoExecutor's reply is written back onto the child session as an
1695        // assistant message — proof a terminal result flowed back over the link.
1696        let last = session
1697            .messages
1698            .iter()
1699            .rev()
1700            .find(|m| matches!(m.role, Role::Assistant))
1701            .expect("an assistant reply was written back");
1702        assert!(
1703            last.content.contains("echo:"),
1704            "expected echo reply, got {:?}",
1705            last.content
1706        );
1707
1708        // A remote run must stamp WHICH machine it ran on onto the child session
1709        // (mirrored to the UI badge) using the placement's node label.
1710        let placement = session
1711            .metadata
1712            .get("placement")
1713            .expect("remote child session stamped with a placement");
1714        assert!(placement.contains(r#""kind":"remote""#), "{placement}");
1715        assert!(placement.contains(r#""host":"mini-e2e""#), "{placement}");
1716
1717        // Drain a couple of streamed events to confirm the event pipe carried the
1718        // worker's tokens too (best-effort; the reply assertion above is primary).
1719        let mut saw_event = false;
1720        while let Ok(Some(_ev)) =
1721            tokio::time::timeout(Duration::from_millis(50), event_rx.recv()).await
1722        {
1723            saw_event = true;
1724        }
1725        let _ = saw_event;
1726
1727        srv.abort();
1728    }
1729
1730    // ---- #181 (P2b): schedulable placement routing --------------------------
1731
1732
1733    /// A bogus-worker_bin runner carrying SCHEDULABLE placements (and optionally
1734    /// remote ones, to test precedence). A local spawn here would fail on
1735    /// `/bin/false`, so a passing schedulable test proves no subprocess spawned.
1736    fn bogus_sched_runner(
1737        remote: HashMap<String, ResolvedRemotePlacement>,
1738        sched: HashMap<String, ResolvedSchedulablePlacement>,
1739    ) -> ActorChildRunner {
1740        ActorChildRunner::new(
1741            "test-actor".into(),
1742            PathBuf::from("/bin/false"),
1743            vec![],
1744            std::env::temp_dir().join("bamboo-test-fab-181"),
1745            ExecutorSpec::Echo,
1746            vec![],
1747            "anthropic".into(),
1748            4,
1749        )
1750        .with_remote_placements(remote)
1751        .with_schedulable_placements(sched)
1752    }
1753
1754    fn sched_placement(pool: &str, _registry_url: impl Into<String>) -> ResolvedSchedulablePlacement {
1755        ResolvedSchedulablePlacement { pool: pool.into(), host_label: None }
1756    }
1757
1758    #[test]
1759    fn build_spec_sets_schedulable_placement_for_matching_role() {
1760        let mut sched = HashMap::new();
1761        sched.insert(
1762            "explorer".to_string(),
1763            sched_placement("gpu-pool", "unused"),
1764        );
1765        let runner = bogus_sched_runner(HashMap::new(), sched);
1766
1767        let s = session_of_role("explorer", "do the thing");
1768        let spec = runner.build_spec(&s, &job_for("child-1"));
1769        match &spec.placement {
1770            Placement::Schedulable { pool } => assert_eq!(pool, "gpu-pool"),
1771            other => panic!("expected Schedulable, got {other:?}"),
1772        }
1773        // No per-placement bearer now — the bus connection carries the bus token.
1774        assert!(spec.secrets.worker_auth_token.is_none());
1775    }
1776
1777    #[test]
1778    fn build_spec_remote_wins_when_role_in_both_maps() {
1779        // A role present in BOTH remote_placements and schedulable_placements must
1780        // resolve to the FIXED remote placement (documented precedence).
1781        let mut remote = HashMap::new();
1782        remote.insert(
1783            "explorer".to_string(),
1784            ResolvedRemotePlacement {
1785                endpoint: "wss://fixed-host:8443".into(),
1786                token: Some("T-remote".into()),
1787                ca_cert_file: None,
1788                host_label: None,
1789            },
1790        );
1791        let mut sched = HashMap::new();
1792        sched.insert(
1793            "explorer".to_string(),
1794            sched_placement("gpu-pool", "https://control-plane:9562"),
1795        );
1796        let runner = bogus_sched_runner(remote, sched);
1797
1798        let s = session_of_role("explorer", "do the thing");
1799        let spec = runner.build_spec(&s, &job_for("child-1"));
1800        match &spec.placement {
1801            Placement::Remote { endpoint } => assert_eq!(endpoint, "wss://fixed-host:8443"),
1802            other => panic!("expected Remote (precedence), got {other:?}"),
1803        }
1804        assert_eq!(spec.secrets.worker_auth_token.as_deref(), Some("T-remote"));
1805    }
1806
1807    #[test]
1808    fn build_spec_local_for_unmatched_schedulable_role() {
1809        let mut sched = HashMap::new();
1810        sched.insert(
1811            "explorer".to_string(),
1812            sched_placement("gpu-pool", "https://control-plane:9562"),
1813        );
1814        let runner = bogus_sched_runner(HashMap::new(), sched);
1815        let s = session_of_role("writer", "do the thing");
1816        let spec = runner.build_spec(&s, &job_for("child-1"));
1817        assert_eq!(spec.placement, Placement::Local);
1818        assert!(spec.secrets.worker_auth_token.is_none());
1819    }
1820
1821    /// The full role → resolved-placement → badge-host chain: a child routed to a
1822    /// remote/schedulable placement carrying a cluster node's `host_label` stamps
1823    /// that label; without a label it falls back to the endpoint host / pool; a
1824    /// Local child gets no stamp (the DTO defaults it to the backend host).
1825    #[test]
1826    fn placement_stamp_uses_node_label_for_remote_and_schedulable() {
1827        // Remote WITH a node label → {remote, <label>}, overriding the raw IP.
1828        let mut remote = HashMap::new();
1829        remote.insert(
1830            "explorer".to_string(),
1831            ResolvedRemotePlacement {
1832                endpoint: "ws://169.254.230.101:8899".into(),
1833                token: None,
1834                ca_cert_file: None,
1835                host_label: Some("mini".into()),
1836            },
1837        );
1838        let runner = bogus_runner(remote);
1839        let spec = runner.build_spec(&session_of_role("explorer", "go"), &job_for("c1"));
1840        let stamp = runner.placement_stamp_for(&spec).expect("remote child is stamped");
1841        assert!(stamp.contains(r#""kind":"remote""#), "{stamp}");
1842        assert!(stamp.contains(r#""host":"mini""#), "{stamp}");
1843
1844        // Remote WITHOUT a node label → falls back to the endpoint host.
1845        let mut remote_nolabel = HashMap::new();
1846        remote_nolabel.insert(
1847            "explorer".to_string(),
1848            ResolvedRemotePlacement {
1849                endpoint: "ws://169.254.230.101:8899".into(),
1850                token: None,
1851                ca_cert_file: None,
1852                host_label: None,
1853            },
1854        );
1855        let r2 = bogus_runner(remote_nolabel);
1856        let spec2 = r2.build_spec(&session_of_role("explorer", "go"), &job_for("c1"));
1857        assert!(
1858            r2.placement_stamp_for(&spec2)
1859                .unwrap()
1860                .contains(r#""host":"169.254.230.101""#)
1861        );
1862
1863        // Schedulable WITH a node label → {remote, <label>} (a node, not a pool name).
1864        let mut sched = HashMap::new();
1865        sched.insert(
1866            "mac-mini-monitor".to_string(),
1867            ResolvedSchedulablePlacement {
1868                pool: "mac-mini-monitor".into(),
1869                host_label: Some("mini".into()),
1870            },
1871        );
1872        let sr = bogus_sched_runner(HashMap::new(), sched);
1873        let spec3 = sr.build_spec(&session_of_role("mac-mini-monitor", "go"), &job_for("c1"));
1874        let stamp3 = sr.placement_stamp_for(&spec3).expect("scheduled child is stamped");
1875        assert!(stamp3.contains(r#""kind":"remote""#), "{stamp3}");
1876        assert!(stamp3.contains(r#""host":"mini""#), "{stamp3}");
1877
1878        // A Local (unmatched) child gets NO stamp.
1879        let local = bogus_runner(HashMap::new());
1880        let spec4 = local.build_spec(&session_of_role("writer", "go"), &job_for("c1"));
1881        assert_eq!(local.placement_stamp_for(&spec4), None);
1882    }
1883
1884    // ---- #181: schedulable selection over the BUS (Phase 3 cutover) ----------
1885
1886    async fn start_bus() -> (String, tempfile::TempDir) {
1887        let dir = tempfile::tempdir().unwrap();
1888        let core = std::sync::Arc::new(bamboo_broker::BrokerCore::new(dir.path()));
1889        let server = std::sync::Arc::new(bamboo_broker::BrokerServer::new(core, "t"));
1890        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1891        let addr = listener.local_addr().unwrap();
1892        tokio::spawn(async move {
1893            let _ = server.serve(listener).await;
1894        });
1895        (format!("ws://{addr}"), dir)
1896    }
1897
1898    async fn join_pool(endpoint: &str, id: &str, pool: &str) -> bamboo_broker::BrokerClient {
1899        let mut c = bamboo_broker::BrokerClient::connect(
1900            endpoint,
1901            bamboo_subagent::AgentRef {
1902                session_id: id.into(),
1903                role: Some(pool.into()),
1904            },
1905            "t",
1906        )
1907        .await
1908        .unwrap();
1909        c.subscribe().await.unwrap();
1910        c
1911    }
1912
1913    fn sched_runner_on_bus(endpoint: &str, child_role: &str, pool: &str) -> ActorChildRunner {
1914        let mut sched = HashMap::new();
1915        sched.insert(child_role.to_string(), sched_placement(pool, "unused"));
1916        bogus_sched_runner(HashMap::new(), sched).with_bus(Some(bamboo_subagent::BusEndpoint {
1917            endpoint: endpoint.into(),
1918            token: "t".into(),
1919        }))
1920    }
1921
1922    #[tokio::test]
1923    async fn resolve_schedulable_picks_a_live_bus_worker() {
1924        let (endpoint, _dir) = start_bus().await;
1925        let _w = join_pool(&endpoint, "w-gpu", "gpu-pool").await;
1926        let runner = sched_runner_on_bus(&endpoint, "explorer", "gpu-pool");
1927
1928        let mailbox = runner
1929            .resolve_schedulable_worker("explorer")
1930            .await
1931            .expect("a live pool worker is found on the bus");
1932        assert_eq!(mailbox, "w-gpu");
1933    }
1934
1935    #[tokio::test]
1936    async fn resolve_schedulable_round_robins_over_pool_workers() {
1937        let (endpoint, _dir) = start_bus().await;
1938        let _a = join_pool(&endpoint, "w-a", "gpu-pool").await;
1939        let _b = join_pool(&endpoint, "w-b", "gpu-pool").await;
1940        let runner = sched_runner_on_bus(&endpoint, "explorer", "gpu-pool");
1941
1942        // Successive resolves spread across both connected workers.
1943        let mut picked = std::collections::HashSet::new();
1944        for _ in 0..6 {
1945            picked.insert(runner.resolve_schedulable_worker("explorer").await.unwrap());
1946        }
1947        assert_eq!(
1948            picked,
1949            ["w-a".to_string(), "w-b".to_string()].into_iter().collect(),
1950            "round-robin must cover every connected pool worker"
1951        );
1952    }
1953
1954    #[tokio::test]
1955    async fn resolve_schedulable_errors_on_empty_pool() {
1956        let (endpoint, _dir) = start_bus().await;
1957        // No worker subscribes to "gpu-pool".
1958        let runner = sched_runner_on_bus(&endpoint, "explorer", "gpu-pool");
1959
1960        let err = runner
1961            .resolve_schedulable_worker("explorer")
1962            .await
1963            .expect_err("an empty pool is terminal — no local fallback")
1964            .to_string();
1965        assert!(err.contains("no live worker in pool"), "got: {err}");
1966        assert!(err.contains("NOT spawning"), "got: {err}");
1967    }
1968
1969    /// FULL schedulable run over the bus: a worker SERVING `EchoExecutor` joins the
1970    /// pool by role; `execute_external_child` with a Schedulable placement resolves
1971    /// it from the bus (no local subprocess — the worker_bin is `/bin/false`),
1972    /// drives the run, gets the echo back, AND stamps the child session with the
1973    /// pool's cluster-node label — `{kind:remote, host:"mini"}`. The end-to-end
1974    /// analogue of the live `mac-mini-monitor`→mini run.
1975    #[tokio::test]
1976    async fn execute_external_child_runs_schedulable_over_bus_and_stamps_node_label() {
1977        let (endpoint, _dir) = start_bus().await;
1978
1979        // A bus worker SERVING runs (not just presence), joined to the pool by role.
1980        let ep = endpoint.clone();
1981        let worker = tokio::spawn(async move {
1982            let _ = bamboo_broker::serve_executor(
1983                &ep,
1984                bamboo_subagent::AgentRef {
1985                    session_id: "mmm-worker".into(),
1986                    role: Some("mac-mini-monitor".into()),
1987                },
1988                "t",
1989                std::sync::Arc::new(bamboo_subagent::executor::EchoExecutor),
1990            )
1991            .await;
1992        });
1993
1994        // Wait until the worker is visible on the bus so the pool is non-empty
1995        // when execute_external_child resolves it (serve_executor connects async).
1996        let mut probe = bamboo_broker::BrokerClient::connect(
1997            &endpoint,
1998            bamboo_subagent::AgentRef { session_id: "probe".into(), role: None },
1999            "t",
2000        )
2001        .await
2002        .unwrap();
2003        let mut ready = false;
2004        for _ in 0..100 {
2005            if probe
2006                .list_connected("mac-mini-monitor")
2007                .await
2008                .unwrap()
2009                .iter()
2010                .any(|id| id == "mmm-worker")
2011            {
2012                ready = true;
2013                break;
2014            }
2015            tokio::time::sleep(Duration::from_millis(30)).await;
2016        }
2017        assert!(ready, "worker never joined the pool");
2018
2019        // Runner: child role → schedulable pool "mac-mini-monitor" carrying the
2020        // cluster node's label "mini"; bogus worker_bin so any local spawn fails.
2021        let mut sched = HashMap::new();
2022        sched.insert(
2023            "mac-mini-monitor".to_string(),
2024            ResolvedSchedulablePlacement {
2025                pool: "mac-mini-monitor".into(),
2026                host_label: Some("mini".into()),
2027            },
2028        );
2029        let runner = bogus_sched_runner(HashMap::new(), sched).with_bus(Some(
2030            bamboo_subagent::BusEndpoint { endpoint: endpoint.clone(), token: "t".into() },
2031        ));
2032
2033        let mut session = session_of_role("mac-mini-monitor", "hello scheduled");
2034        let job = job_for("child-1");
2035        let (event_tx, _rx) = mpsc::channel::<AgentEvent>(64);
2036        let cancel = CancellationToken::new();
2037
2038        tokio::time::timeout(
2039            Duration::from_secs(10),
2040            runner.execute_external_child(&mut session, &job, event_tx, cancel),
2041        )
2042        .await
2043        .expect("run did not hang")
2044        .expect("schedulable run succeeded over the bus (no local spawn)");
2045
2046        // Echo reply flowed back — proves it routed to the bus worker, not local.
2047        let last = session
2048            .messages
2049            .iter()
2050            .rev()
2051            .find(|m| matches!(m.role, Role::Assistant))
2052            .expect("an assistant reply was written back");
2053        assert!(last.content.contains("echo:"), "got {:?}", last.content);
2054
2055        // ...and the child is stamped with the pool's cluster-node label.
2056        let placement = session
2057            .metadata
2058            .get("placement")
2059            .expect("scheduled child session stamped with a placement");
2060        assert!(placement.contains(r#""kind":"remote""#), "{placement}");
2061        assert!(placement.contains(r#""host":"mini""#), "{placement}");
2062
2063        worker.abort();
2064    }
2065}