zeph_subagent/manager/mod.rs
1// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Sub-agent lifecycle management: spawn, cancel, collect, and resume.
5
6mod collect;
7mod secrets;
8mod spawn;
9mod worktree;
10
11use std::collections::{HashMap, HashSet};
12use std::path::PathBuf;
13use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
14use std::time::Instant;
15
16use tokio::sync::{mpsc, watch};
17use tokio::task::JoinSet;
18use tokio_util::sync::CancellationToken;
19use zeph_common::task_supervisor::BlockingHandle;
20use zeph_common::{SkillTrustLevel, TaskSupervisor};
21use zeph_config::{ContentIsolationConfig, McpServerConfig};
22use zeph_llm::provider::Message;
23
24use crate::def::{PermissionMode, SubAgentDef};
25use crate::durable::DurableResolverSeat;
26use crate::error::SubAgentError;
27use crate::fleet::SharedFleetRegistry;
28use crate::forward::ForwardSurfaces;
29use crate::grants::{GrantedSecret, PermissionGrants, SecretRequest};
30use crate::state::SubAgentState;
31
32/// Classifies what triggered a given spawn attempt, for [`DelegationMode`] enforcement
33/// (spec `042-subagent-delegation-mode-parity`, issue #5857).
34///
35/// # Fail-closed default
36///
37/// [`SpawnOrigin::default`] is [`SpawnOrigin::Autonomous`] — the *restrictive* value, not the
38/// permissive one. An untagged or forgotten [`SpawnContext`] therefore reads as `Autonomous`
39/// and is denied under [`DelegationMode::ExplicitRequestOnly`]/[`DelegationMode::Disabled`],
40/// never silently allowed. Only a caller that explicitly sets `origin = SpawnOrigin::Explicit`
41/// (after auditing that the trigger really is a direct, attributable user action) can bypass
42/// the `explicit_request_only` restriction. A mistagged legitimate spawn fails visibly (a
43/// `tracing::warn!` plus a denied spawn); a mistagged illegitimate one can never be silently
44/// let through.
45///
46/// [`DelegationMode`]: zeph_config::DelegationMode
47/// [`DelegationMode::ExplicitRequestOnly`]: zeph_config::DelegationMode::ExplicitRequestOnly
48/// [`DelegationMode::Disabled`]: zeph_config::DelegationMode::Disabled
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum SpawnOrigin {
51 /// A direct, attributable user action in the current turn (e.g. `/agent spawn`,
52 /// `/agent resume`) — always permitted except under `delegation_mode = "disabled"`.
53 Explicit,
54 /// Autonomous planner/scheduler decision-making with no corresponding explicit user
55 /// request in the current turn (e.g. the orchestration scheduler's DAG dispatch). Denied
56 /// under `delegation_mode = "explicit_request_only"` and `"disabled"`.
57 Autonomous,
58}
59
60impl Default for SpawnOrigin {
61 /// Fail-closed: see the type-level doc comment.
62 fn default() -> Self {
63 Self::Autonomous
64 }
65}
66
67/// Parent-derived state propagated to a spawned sub-agent at spawn time.
68///
69/// All fields default to empty/`None`, preserving existing behavior when callers
70/// pass `SpawnContext::default()`.
71///
72/// # Constraint propagation
73///
74/// [`max_trust_level`][Self::max_trust_level] and
75/// [`inherited_tool_allowlist`][Self::inherited_tool_allowlist] implement transitive
76/// constraint propagation: safety constraints set at orchestration time are enforced on
77/// every sub-agent in the spawn chain, regardless of nesting depth.
78///
79/// When a sub-agent spawns its own sub-agents it must forward these fields downward so
80/// that grandchild agents cannot silently receive more privileges than the original
81/// orchestration policy allowed.
82///
83/// # Examples
84///
85/// ```rust
86/// use zeph_subagent::manager::{SpawnContext, SpawnOrigin};
87///
88/// // Minimal context — all fields use their defaults.
89/// let ctx = SpawnContext::default();
90/// assert!(ctx.parent_messages.is_empty());
91/// assert_eq!(ctx.spawn_depth, 0);
92/// assert!(ctx.max_trust_level.is_none());
93/// assert!(ctx.inherited_tool_allowlist.is_none());
94/// // Fail-closed: an untagged context reads as Autonomous, not Explicit.
95/// assert_eq!(ctx.origin, SpawnOrigin::Autonomous);
96/// ```
97#[derive(Default)]
98pub struct SpawnContext {
99 /// Recent parent conversation messages (last N turns).
100 pub parent_messages: Vec<Message>,
101 /// Parent's cancellation token for linked cancellation (foreground spawns).
102 pub parent_cancel: Option<CancellationToken>,
103 /// Parent's active provider name (for context propagation).
104 pub parent_provider_name: Option<String>,
105 /// Current spawn depth (0 = top-level agent).
106 pub spawn_depth: u32,
107 /// MCP tool names available in the parent's tool executor (for diagnostics).
108 pub mcp_tool_names: Vec<String>,
109 /// Seeded trajectory risk score from the parent sentinel (spec 050 §4).
110 ///
111 /// When `Some`, the subagent's `TrajectorySentinel` starts with this pre-seeded score
112 /// rather than `0.0`, preventing a subagent spawn from acting as a free risk reset.
113 /// The subagent loop applies this via `TrajectorySentinel::seed_score` after build.
114 pub seed_trajectory_score: Option<f32>,
115 /// Parent's content isolation config, propagated so the subagent loop can run the
116 /// same sanitizer settings on hook-replaced tool output.
117 pub content_isolation: ContentIsolationConfig,
118 /// Name of the orchestrator that spawned this subagent.
119 ///
120 /// When set, the subagent's system prompt includes an identity header naming the
121 /// orchestrator, so the subagent can validate that instructions are consistent with
122 /// the expected authority.
123 pub orchestrator_name: Option<String>,
124 /// Role or task label of the orchestrating agent (e.g., `"planner"`, `"tool-router"`).
125 ///
126 /// Injected alongside [`orchestrator_name`][Self::orchestrator_name] when both are set.
127 /// Omitted from the identity header when only `orchestrator_name` is provided.
128 pub orchestrator_role: Option<String>,
129 /// Per-session MCP servers to inject into this subagent's tool name annotations.
130 ///
131 /// The parent is responsible for connecting these servers and including them in the
132 /// `tool_executor` passed to [`SubAgentManager::spawn`]. This field only carries the
133 /// server metadata so the subagent's system prompt lists the additional tool names.
134 pub session_mcp_servers: Vec<McpServerConfig>,
135 /// Maximum trust level cap inherited from the parent agent or orchestration policy.
136 ///
137 /// When `Some(cap)`, the spawned sub-agent's effective trust level is clamped to
138 /// `min(own_trust, cap)` so that sub-agents can never receive higher privileges than
139 /// the orchestration policy originally allowed.
140 ///
141 /// # Caller responsibility for nested spawns
142 ///
143 /// This field does **not** propagate automatically. When a sub-agent itself spawns a
144 /// grandchild, it must copy this field from its own received `SpawnContext` into the
145 /// grandchild's `SpawnContext`. Passing `None` (the default) at that point means the
146 /// grandchild receives **no cap**, which is a privilege escalation if the parent was
147 /// constrained. Only the top-level session (spawned by `build_spawn_context`) correctly
148 /// leaves this `None` — that represents an unconstrained top-level entry point.
149 ///
150 /// `None` means no cap is imposed by the parent (the sub-agent's own definition
151 /// determines its trust level).
152 pub max_trust_level: Option<SkillTrustLevel>,
153 /// Tool names that this sub-agent is allowed to invoke, inherited from the parent.
154 ///
155 /// When `Some(set)`, the effective tool allowlist for the spawned agent is the
156 /// intersection of `set` and the agent's own definition policy. This prevents a
157 /// sub-agent from accessing tools that the parent is itself not allowed to use.
158 ///
159 /// # Caller responsibility for nested spawns
160 ///
161 /// Like [`max_trust_level`][Self::max_trust_level], this field does **not** propagate
162 /// automatically. When a constrained sub-agent spawns its own children, it must copy
163 /// this field from its received `SpawnContext` into the child's `SpawnContext`.
164 /// Passing `None` at that point would grant the grandchild unrestricted tool access,
165 /// defeating the original orchestration policy.
166 ///
167 /// `None` means no additional allowlist restriction is imposed by the parent
168 /// (the agent's definition policy applies without narrowing).
169 pub inherited_tool_allowlist: Option<HashSet<String>>,
170
171 /// Durable resolver seat for promise-based subagent spawn/await (spec-064 §P4, INV-9).
172 ///
173 /// When `Some`, the spawned background task resolves the parent's durable promise after the
174 /// agent loop terminates. The seat carries the resolver token and MUST NOT be forwarded to
175 /// the child's tool executor or LLM surface — only the background task wrapper consumes it.
176 ///
177 /// `None` when `durable.enabled && durable.subagent` is false (plain spawn/collect path).
178 pub durable_resolver: Option<DurableResolverSeat>,
179
180 /// Deny network egress for this sub-agent's `bash` tool calls.
181 ///
182 /// Set by the orchestration layer when the spawning `TaskNode` carries
183 /// `network_scope: NetworkScope::Deny` (spec `069-threat-model` OQ-1). When `true`,
184 /// `build_filtered_executor` wraps the tool executor with
185 /// [`NetworkDenyToolExecutor`](crate::NetworkDenyToolExecutor), which blocks `bash`
186 /// invocations of `curl`, `wget`, `nc`, `ncat`, and `netcat` for this spawn only —
187 /// sibling tasks and the parent agent's own executor are unaffected.
188 ///
189 /// # Caller responsibility for nested spawns
190 ///
191 /// Like [`max_trust_level`][Self::max_trust_level], this field does **not** propagate
192 /// automatically. A sub-agent that itself spawns a grandchild must copy this field
193 /// from its own received `SpawnContext` into the grandchild's `SpawnContext`, or the
194 /// grandchild spawns with network access regardless of the original task's scope.
195 ///
196 /// `false` (the default) imposes no restriction beyond the executor/global
197 /// `allow_network` default.
198 pub network_denied: bool,
199
200 /// Shared progress heartbeat for idle-timeout detection (issue #6245).
201 ///
202 /// Set by the orchestration driver (`handle_scheduler_spawn_action` in `zeph-core`'s
203 /// `scheduler_loop.rs`) alongside [`network_denied`][Self::network_denied] — same
204 /// post-construction assignment pattern, not part of `build_spawn_context`'s base
205 /// literal. The driver creates the `Arc`, clones it in here, and keeps the original for
206 /// `zeph_orchestration::DagScheduler::record_spawn`'s `last_progress_at` parameter so
207 /// both the running loop and the scheduler observe the same counter.
208 ///
209 /// `None` (the default) for spawns not tracked by a `DagScheduler` — e.g. the standalone
210 /// `/agent run` command — which are never idle-tracked.
211 pub progress_at: Option<Arc<std::sync::atomic::AtomicU64>>,
212
213 /// Cross-crate debug-dump sink, threaded down so sub-agent LLM calls are captured
214 /// through the same pipeline as the top-level agent loop's `--debug-dump` output (#6391).
215 ///
216 /// Set by `zeph-core`'s `build_spawn_context` from `DebugState::debug_dumper`. `None`
217 /// when debug dumps are disabled — no sub-agent dump is written in that case, mirroring
218 /// the top-level `debug_dumper: None` behavior.
219 ///
220 /// # Caller responsibility for nested spawns
221 ///
222 /// Like [`max_trust_level`][Self::max_trust_level], this does **not** propagate
223 /// automatically — a sub-agent that spawns its own children must copy this field from
224 /// its received `SpawnContext` into the child's, or grandchild LLM calls go undumped.
225 pub debug_dump_sink: Option<Arc<dyn zeph_llm::debug_dump::DebugDumpSink>>,
226
227 /// What triggered this spawn attempt — enforced against `delegation_mode` at the top of
228 /// [`SubAgentManager::spawn`] (spec `042-subagent-delegation-mode-parity`, issue #5857).
229 ///
230 /// Defaults to [`SpawnOrigin::Autonomous`] (fail-closed — see [`SpawnOrigin`]'s doc
231 /// comment). `zeph-core`'s `build_spawn_context` (the base used by the explicit
232 /// `/agent spawn`/`/agent resume` commands) sets this to [`SpawnOrigin::Explicit`]; the
233 /// orchestration scheduler overrides it back to `Autonomous` on its own call, mirroring
234 /// the existing post-construction override pattern used for
235 /// [`network_denied`][Self::network_denied] and [`progress_at`][Self::progress_at].
236 pub origin: SpawnOrigin,
237}
238
239/// Intersect two optional tool allowlists, preserving the "narrow only" invariant shared by
240/// [`SpawnContext::inherited_tool_allowlist`] and `TaskNode::tool_allowlist` (#6526/#6527):
241/// `(None, None)` → `None` (no restriction from either source), one side `Some` → that side
242/// (the only source of narrowing), both `Some` → their set intersection. Never produces a
243/// wider set than either input, so composing a parent-derived floor with a per-task
244/// allowlist can only narrow further.
245///
246/// # Examples
247///
248/// ```rust
249/// use std::collections::HashSet;
250/// use zeph_subagent::manager::intersect_allowlists;
251///
252/// assert_eq!(intersect_allowlists(None, None), None);
253///
254/// let a: HashSet<String> = ["read".to_owned(), "grep".to_owned()].into();
255/// assert_eq!(intersect_allowlists(Some(a.clone()), None), Some(a));
256///
257/// let b: HashSet<String> = ["grep".to_owned(), "bash".to_owned()].into();
258/// let want: HashSet<String> = ["grep".to_owned()].into();
259/// let a: HashSet<String> = ["read".to_owned(), "grep".to_owned()].into();
260/// assert_eq!(intersect_allowlists(Some(a), Some(b)), Some(want));
261/// ```
262// Every caller uses the std `RandomState` default hasher (constraint propagation on
263// SpawnContext/TaskNode allowlists, never a caller-supplied HashSet<_, S>), and
264// `HashSet::intersection` requires both sides to share the same hasher type anyway —
265// generalizing over `S` here would add a type parameter with no real call site benefit.
266#[allow(clippy::implicit_hasher)]
267#[must_use]
268pub fn intersect_allowlists(
269 a: Option<HashSet<String>>,
270 b: Option<HashSet<String>>,
271) -> Option<HashSet<String>> {
272 match (a, b) {
273 (None, None) => None,
274 (Some(set), None) | (None, Some(set)) => Some(set),
275 (Some(a), Some(b)) => Some(a.intersection(&b).cloned().collect()),
276 }
277}
278
279/// Live status snapshot of a running sub-agent.
280///
281/// Values are updated by the background agent loop via a [`tokio::sync::watch`] channel.
282/// Callers receive snapshots via [`SubAgentManager::statuses`].
283#[derive(Debug, Clone)]
284pub struct SubAgentStatus {
285 /// Current lifecycle state of the agent task.
286 pub state: SubAgentState,
287 /// Last message content from the agent (trimmed for display).
288 pub last_message: Option<String>,
289 /// Number of LLM turns consumed so far.
290 pub turns_used: u32,
291 /// Monotonic timestamp recorded at spawn time.
292 pub started_at: Instant,
293}
294
295/// Handle to a spawned sub-agent task, owned by [`SubAgentManager`].
296///
297/// Fields are public to allow test harnesses in downstream crates to construct handles
298/// without going through the full spawn lifecycle. Production code must not mutate
299/// grants or the cancellation state directly — use the [`SubAgentManager`] API instead.
300///
301/// The `Drop` implementation cancels the task and revokes all grants as a safety net.
302pub struct SubAgentHandle {
303 /// Short display ID (same as `task_id` for non-resumed sessions).
304 pub id: String,
305 /// The definition that was used to spawn this agent.
306 pub def: SubAgentDef,
307 /// UUID assigned at spawn time (currently identical to `id`; separated for future use).
308 pub task_id: String,
309 /// Cached state — may lag the background task by one watch broadcast.
310 pub state: SubAgentState,
311 /// Supervised handle for the background agent loop task.
312 pub join_handle: Option<BlockingHandle<Result<String, SubAgentError>>>,
313 /// Cancellation token; cancelled on [`SubAgentManager::cancel`] or drop.
314 pub cancel: CancellationToken,
315 /// Watch receiver for live status updates from the agent loop.
316 pub status_rx: watch::Receiver<SubAgentStatus>,
317 /// Zero-trust TTL-bounded grants for this agent session.
318 ///
319 /// Shared with the spawned agent-loop task via `Arc<Mutex<..>>` (issue #6567) so that
320 /// `GrantKind::Tool` enforcement inside `handle_tool_step` observes the same live state
321 /// this handle mutates — in particular so `revoke_all()` called here (task collection,
322 /// cancellation, or drop) is immediately visible to the running loop task without a
323 /// delivery channel. `GrantKind::Secret` values are still delivered separately over
324 /// `secret_tx`/`secret_rx` as a point-in-time snapshot, since secrets are explicitly
325 /// requested per-key rather than checked implicitly on every dispatch.
326 pub grants: Arc<Mutex<PermissionGrants>>,
327 /// Receives secret requests from the sub-agent loop.
328 pub pending_secret_rx: mpsc::Receiver<SecretRequest>,
329 /// Delivers the approval outcome to the sub-agent loop: `None` = denied,
330 /// `Some(value)` = approved, carrying the resolved vault secret value and its
331 /// grant expiry so the loop can re-validate the TTL locally on every tool call.
332 pub secret_tx: mpsc::Sender<Option<GrantedSecret>>,
333 /// ISO 8601 UTC timestamp recorded when the agent was spawned or resumed.
334 pub started_at_str: String,
335 /// Resolved transcript directory at spawn time; `None` if transcripts were disabled.
336 pub transcript_dir: Option<PathBuf>,
337 /// MCP tool names available at spawn time, persisted for transcript meta on collect.
338 pub mcp_tool_names: Vec<String>,
339}
340
341impl SubAgentHandle {
342 /// Construct a minimal [`SubAgentHandle`] for use in unit tests.
343 ///
344 /// The returned handle has a no-op cancel token, closed channels, and no grants.
345 /// It must not be spawned or collected — it is only valid for inspection logic
346 /// that operates on the handle's metadata fields (id, def, state, etc.).
347 #[cfg(test)]
348 pub fn for_test(id: impl Into<String>, def: SubAgentDef) -> Self {
349 let initial_status = SubAgentStatus {
350 state: SubAgentState::Working,
351 last_message: None,
352 turns_used: 0,
353 started_at: Instant::now(),
354 };
355 let (status_tx, status_rx) = watch::channel(initial_status);
356 drop(status_tx);
357 let (pending_secret_rx_tx, pending_secret_rx) = mpsc::channel(1);
358 drop(pending_secret_rx_tx);
359 let (secret_tx, _) = mpsc::channel(1);
360 let id_str = id.into();
361 Self {
362 task_id: id_str.clone(),
363 id: id_str,
364 def,
365 state: SubAgentState::Working,
366 join_handle: None,
367 cancel: CancellationToken::new(),
368 status_rx,
369 grants: Arc::new(Mutex::new(PermissionGrants::default())),
370 pending_secret_rx,
371 secret_tx,
372 started_at_str: String::new(),
373 transcript_dir: None,
374 mcp_tool_names: Vec::new(),
375 }
376 }
377
378 /// Lock the shared, TTL-bounded permission grants for this agent.
379 ///
380 /// Recovers from a poisoned lock (a panic elsewhere while holding it) rather than
381 /// propagating the panic. This is plainly **fail-open**, not fail-closed: a poisoned
382 /// mutex is ignored and the guard is handed back regardless, so this method makes no
383 /// guarantee about the freshness or consistency of the `PermissionGrants` it returns.
384 /// That is safe today because every operation performed under this lock
385 /// (`PermissionGrants::add`/`sweep_expired`/`is_active`/`check_tool_grant`/`revoke_all`)
386 /// is a plain, infallible in-memory `Vec` operation — none of them can panic in normal
387 /// operation, so poisoning can only originate from an unrelated bug elsewhere, and simply
388 /// proceeding with the (still internally consistent) data is the pragmatic choice over
389 /// permanently wedging every subsequent tool dispatch for this sub-agent. The actual
390 /// fail-closed behavior for `GrantKind::Tool` enforcement lives one layer up, in
391 /// `PermissionGrants::check_tool_grant` (issue #6567), which rejects the tool call on an
392 /// expired/revoked grant independent of whether this lock happened to be poisoned.
393 pub(crate) fn grants_lock(&self) -> MutexGuard<'_, PermissionGrants> {
394 self.grants.lock().unwrap_or_else(PoisonError::into_inner)
395 }
396}
397
398impl std::fmt::Debug for SubAgentHandle {
399 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
400 f.debug_struct("SubAgentHandle")
401 .field("id", &self.id)
402 .field("task_id", &self.task_id)
403 .field("state", &self.state)
404 .field("def_name", &self.def.name)
405 .finish_non_exhaustive()
406 }
407}
408
409impl Drop for SubAgentHandle {
410 fn drop(&mut self) {
411 // Defense-in-depth: cancel the task and revoke grants on drop even if
412 // cancel() or collect() was not called (e.g., on panic or early return).
413 self.cancel.cancel();
414 let mut grants = self.grants_lock();
415 if !grants.is_empty_grants() {
416 tracing::warn!(
417 id = %self.id,
418 "SubAgentHandle dropped without explicit cleanup — revoking grants"
419 );
420 }
421 grants.revoke_all();
422 }
423}
424
425/// Manages sub-agent lifecycle: definitions, spawning, cancellation, and result collection.
426///
427/// `SubAgentManager` is the central coordinator for all sub-agent tasks. It tracks active
428/// [`SubAgentHandle`]s, enforces the global concurrency limit, and stores loaded
429/// [`SubAgentDef`]s.
430///
431/// # Concurrency model
432///
433/// The concurrency limit counts agents whose [`SubAgentState`] is `Submitted` or `Working`.
434/// Reserved slots (via [`reserve_slots`][Self::reserve_slots]) also count against this limit
435/// to allow orchestration schedulers to guarantee capacity before spawning.
436///
437/// # Examples
438///
439/// ```rust
440/// use zeph_subagent::SubAgentManager;
441///
442/// let manager = SubAgentManager::new(4);
443/// assert_eq!(manager.definitions().len(), 0);
444/// ```
445pub struct SubAgentManager {
446 definitions: Vec<SubAgentDef>,
447 agents: HashMap<String, SubAgentHandle>,
448 max_concurrent: usize,
449 /// Number of slots soft-reserved by the orchestration scheduler.
450 ///
451 /// Reserved slots count against the concurrency limit so that the scheduler can
452 /// guarantee capacity for tasks it is about to spawn, preventing a planning-phase
453 /// sub-agent from exhausting the pool and causing a deadlock.
454 reserved_slots: usize,
455 /// Config-level `SubagentStop` hooks, cached so `cancel()` and `collect()` can fire them.
456 stop_hooks: Vec<super::hooks::HookDef>,
457 /// Directory for JSONL transcripts and meta sidecars.
458 transcript_dir: Option<PathBuf>,
459 /// Maximum number of transcript files to keep (0 = unlimited).
460 transcript_max_files: usize,
461 /// Optional fleet registry for registering sub-agents in the fleet dashboard.
462 ///
463 /// When `None`, fleet registration is skipped silently. Inject via
464 /// [`set_fleet_registry`][Self::set_fleet_registry].
465 fleet_registry: Option<SharedFleetRegistry>,
466 /// Tracks fire-and-forget hook and fleet-registry tasks to prevent silent panic swallowing.
467 ///
468 /// Completed and panicked tasks are drained before each new spawn. On graceful shutdown,
469 /// [`shutdown_all`][Self::shutdown_all] aborts all outstanding tasks via
470 /// [`JoinSet::shutdown`].
471 hook_tasks: JoinSet<()>,
472 /// Maximum number of concurrent hook tasks allowed in [`hook_tasks`][Self::hook_tasks].
473 ///
474 /// When the limit is reached, new fire-and-forget tasks are dropped with a warning instead
475 /// of growing the set unboundedly under high-throughput spawning.
476 max_hook_tasks: usize,
477 /// Optional worktree manager; `Some` iff `worktree.enabled = true` in config.
478 ///
479 /// When set, every [`spawn`][Self::spawn] acquires [`cwd_lock`][Self::cwd_lock] for
480 /// its full run so that plain agents cannot observe a stale cwd mutated by a worktree
481 /// agent (INV-1). Only agents with `permissions.worktree = true` and a non-`None`
482 /// `bg_isolation` actually get a dedicated worktree.
483 ///
484 /// This is the single live instance shared by the running agent's `/worktree`
485 /// slash command (see [`worktree_manager`][Self::worktree_manager]) — distinct from
486 /// the CLI's `zeph worktree list`/`clean`, which constructs its own fresh manager
487 /// per invocation (`src/commands/worktree.rs`).
488 worktree_manager: Option<Arc<zeph_worktree::DefaultWorktreeManager>>,
489 /// Process-level serialisation mutex for working-directory mutations (INV-1).
490 ///
491 /// Acquired by every spawned task when `worktree_manager.is_some()`. The
492 /// `OwnedMutexGuard` is held for the full duration of `run_agent_loop` via the
493 /// `CwdRestoreGuard` RAII wrapper.
494 cwd_lock: Arc<tokio::sync::Mutex<()>>,
495 /// Optional supervisor for subagent lifecycle tasks.
496 ///
497 /// When set, each spawned agent loop task is registered under its task ID so it is
498 /// visible to TUI status panels and shutdown is coordinated through the supervisor.
499 task_supervisor: Option<TaskSupervisor>,
500 /// Which forwarding consumer surfaces are active for this session (issue #6359).
501 ///
502 /// Fixed at session start via [`set_forward_surfaces`][Self::set_forward_surfaces].
503 /// `ForwardSurfaces::default()` (all `false`) until then, matching "forwarding
504 /// disabled" byte-for-byte (FR-001/NFR-003).
505 forward_surfaces: ForwardSurfaces,
506 /// Ring buffer of recent sanitized display lines per task ID, owned by each task's
507 /// forwarding drain (issue #6359). Read by [`forwarded_tail`][Self::forwarded_tail]
508 /// for the TUI runtime detail view; entries are evicted by the drain itself shortly
509 /// after that task's terminal chunk.
510 forward_buffer: Arc<crate::forward::ForwardBuffer>,
511 /// Optional secret-mask registry applied to forwarded chunks (issue #6359, security
512 /// Finding 1 / NFR-005) — closes the consistency gap with the analogous outbound-LLM
513 /// egress path (`apply_secret_masking`), which the forwarding pipeline would otherwise
514 /// bypass. `None` (the default) means forwarded content is not masked for known vault
515 /// secrets — set via [`set_secret_registry`][Self::set_secret_registry].
516 secret_registry: Option<Arc<zeph_sanitizer::secret_mask::SecretMaskRegistry>>,
517 /// Optional PII filter applied to forwarded chunks (issue #6359, security Finding 1 /
518 /// NFR-005) — mirrors the optional `PiiFilter` layer sub-agent debug dumps get via
519 /// `PiiScrubbingDumpSink` (#6407). `None` (the default) means no PII scrubbing beyond the
520 /// baseline `ContentSanitizer` pass — set via [`set_pii_filter`][Self::set_pii_filter].
521 pii_filter: Option<zeph_sanitizer::pii::PiiFilter>,
522 /// Effective delegation mode gating every spawn (spec `042-subagent-delegation-mode-parity`,
523 /// issue #5857). Already folds in the `enabled` outer kill switch — the bootstrap caller
524 /// computes `if !config.agents.enabled { Disabled } else { config.agents.delegation_mode }`
525 /// before calling [`set_delegation_mode`][Self::set_delegation_mode], so this field alone
526 /// is authoritative at spawn time; `SubAgentManager` does not re-read `enabled` itself.
527 /// Defaults to [`zeph_config::DelegationMode::default()`] (`Proactive`) until set.
528 delegation_mode: zeph_config::DelegationMode,
529}
530
531impl std::fmt::Debug for SubAgentManager {
532 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
533 f.debug_struct("SubAgentManager")
534 .field("definitions_count", &self.definitions.len())
535 .field("active_agents", &self.agents.len())
536 .field("max_concurrent", &self.max_concurrent)
537 .field("reserved_slots", &self.reserved_slots)
538 .field("stop_hooks_count", &self.stop_hooks.len())
539 .field("transcript_dir", &self.transcript_dir)
540 .field("transcript_max_files", &self.transcript_max_files)
541 .field("fleet_registry", &self.fleet_registry.is_some())
542 .field("hook_tasks_len", &self.hook_tasks.len())
543 .field("max_hook_tasks", &self.max_hook_tasks)
544 .field("worktree_manager", &self.worktree_manager.is_some())
545 .field("cwd_lock", &"<Mutex>")
546 .field("task_supervisor", &self.task_supervisor.is_some())
547 .field("forward_surfaces", &self.forward_surfaces)
548 .field("forward_buffer", &"<Mutex>")
549 .field("secret_registry", &self.secret_registry.is_some())
550 .field("pii_filter", &self.pii_filter.is_some())
551 .field("delegation_mode", &self.delegation_mode)
552 .finish()
553 }
554}
555
556impl SubAgentManager {
557 /// Create a new manager with the given concurrency limit.
558 #[must_use]
559 pub fn new(max_concurrent: usize) -> Self {
560 Self {
561 definitions: Vec::new(),
562 agents: HashMap::new(),
563 max_concurrent,
564 reserved_slots: 0,
565 stop_hooks: Vec::new(),
566 transcript_dir: None,
567 transcript_max_files: 50,
568 fleet_registry: None,
569 hook_tasks: JoinSet::new(),
570 max_hook_tasks: 64,
571 worktree_manager: None,
572 cwd_lock: Arc::new(tokio::sync::Mutex::new(())),
573 task_supervisor: None,
574 forward_surfaces: ForwardSurfaces::default(),
575 forward_buffer: crate::forward::new_buffer(),
576 secret_registry: None,
577 pii_filter: None,
578 delegation_mode: zeph_config::DelegationMode::default(),
579 }
580 }
581
582 /// Inject a [`TaskSupervisor`] so subagent lifecycle tasks are registered and visible.
583 ///
584 /// Must be called before the first [`spawn`][Self::spawn]. When set, each spawned agent
585 /// loop task is registered under its task ID and is observable in TUI status panels and
586 /// [`TaskSupervisor::snapshot`].
587 pub fn set_task_supervisor(&mut self, supervisor: TaskSupervisor) {
588 self.task_supervisor = Some(supervisor);
589 }
590
591 /// Declare which forwarding consumer surfaces are active for this session (issue #6359).
592 ///
593 /// Fixed at session start — call once during bootstrap, before the first
594 /// [`spawn`][Self::spawn]. When `surfaces.any()` is `false` (the default) or
595 /// `SubAgentConfig::forward_transcript` is `false`, no forwarding sender or drain is ever
596 /// constructed for any subagent (FR-007). A [`TaskSupervisor`] must also be wired via
597 /// [`set_task_supervisor`][Self::set_task_supervisor] — unlike other subagent lifecycle
598 /// tasks, the forward drain never falls back to an untracked spawn (NFR-002).
599 pub fn set_forward_surfaces(&mut self, surfaces: ForwardSurfaces) {
600 self.forward_surfaces = surfaces;
601 }
602
603 /// Set the effective delegation mode gating every future [`spawn`][Self::spawn] call
604 /// (spec `042-subagent-delegation-mode-parity`, issue #5857).
605 ///
606 /// Call during bootstrap, before the first [`spawn`][Self::spawn]. The caller MUST fold
607 /// in the `enabled` outer kill switch before calling this: pass
608 /// `zeph_config::DelegationMode::Disabled` when `config.agents.enabled == false`,
609 /// regardless of `config.agents.delegation_mode`'s configured value (FR-002). The manager
610 /// itself performs no `enabled` check — it only sees the already-resolved effective mode.
611 pub fn set_delegation_mode(&mut self, mode: zeph_config::DelegationMode) {
612 self.delegation_mode = mode;
613 }
614
615 /// The effective delegation mode currently in force, as set by
616 /// [`set_delegation_mode`][Self::set_delegation_mode]. Exposed for status/observability
617 /// surfaces (e.g. `/agent list`) so operators can confirm the active mode without
618 /// inspecting `config.toml` directly (spec 042 NFR-004).
619 #[must_use]
620 pub fn delegation_mode(&self) -> zeph_config::DelegationMode {
621 self.delegation_mode
622 }
623
624 /// Wire the bootstrap-level secret-mask registry into the forwarding pipeline (issue
625 /// #6359, security Finding 1 / NFR-005).
626 ///
627 /// When set, every forwarded `Text`/`Thinking` chunk has known vault secrets replaced
628 /// with opaque placeholders before reaching any sink (TUI ring, `--bare` stdout) — the
629 /// same registry already applied to the outbound-LLM path via `apply_secret_masking`.
630 /// Call during bootstrap, before the first [`spawn`][Self::spawn]; has no effect on
631 /// already-spawned drains.
632 pub fn set_secret_registry(
633 &mut self,
634 registry: Arc<zeph_sanitizer::secret_mask::SecretMaskRegistry>,
635 ) {
636 self.secret_registry = Some(registry);
637 }
638
639 /// Wire a PII filter into the forwarding pipeline (issue #6359, security Finding 1 /
640 /// NFR-005).
641 ///
642 /// When set, every forwarded `Text`/`Thinking` chunk is scrubbed for emails, phone
643 /// numbers, SSNs, etc. before reaching any sink — mirroring the optional `PiiFilter`
644 /// layer sub-agent debug dumps already get via `PiiScrubbingDumpSink` (#6407). The filter
645 /// itself is unconditionally constructible and self-gates on its own `enabled` config
646 /// field, matching the top-level agent's own `PiiFilter` construction convention. Call
647 /// during bootstrap, before the first [`spawn`][Self::spawn].
648 pub fn set_pii_filter(&mut self, filter: zeph_sanitizer::pii::PiiFilter) {
649 self.pii_filter = Some(filter);
650 }
651
652 /// Read the current forwarded-transcript tail for `task_id` (up to the last `n` lines).
653 ///
654 /// Returns an empty vector when forwarding is disabled, no surface is active, or the
655 /// task has not forwarded any lines yet. Backing store for
656 /// [`crate::manager::SubAgentManager`]'s TUI runtime detail view integration
657 /// (FR-005) — see `zeph-core`'s `refresh_subagent_metrics`.
658 #[must_use]
659 pub fn forwarded_tail(&self, task_id: &str, n: usize) -> Vec<String> {
660 crate::forward::forwarded_tail(&self.forward_buffer, task_id, n)
661 }
662
663 /// Build a forwarding sender + spawn its per-task drain for `task_id`, if forwarding is
664 /// active for this session.
665 ///
666 /// Returns `None` (no-op) unless `config.forward_transcript` is set, at least one
667 /// consumer surface is active, and a [`TaskSupervisor`] is wired — the forward drain must
668 /// never fall back to an untracked `tokio::spawn` (NFR-002, P-new-2). The returned
669 /// [`crate::forward::ForwardSender`] must be threaded into `AgentLoopArgs::forward` and
670 /// owned exclusively by that subagent's own turn loop for the run's lifetime (P-new-3).
671 pub(crate) fn maybe_spawn_forward(
672 &self,
673 task_id: &str,
674 def_name: &str,
675 forward_transcript: bool,
676 content_isolation: &ContentIsolationConfig,
677 ) -> Option<crate::forward::ForwardSender> {
678 if !forward_transcript || !self.forward_surfaces.any() {
679 return None;
680 }
681 let Some(ref supervisor) = self.task_supervisor else {
682 tracing::warn!(
683 task_id,
684 "subagent transcript forwarding is enabled but no TaskSupervisor is wired — \
685 skipping forwarding for this run rather than spawning an untracked drain \
686 (NFR-002)"
687 );
688 return None;
689 };
690
691 let task_id_arc: Arc<str> = Arc::from(task_id);
692 let def_name_arc: Arc<str> = Arc::from(def_name);
693 let (sender, rx) =
694 crate::forward::new_channel(Arc::clone(&task_id_arc), Arc::clone(&def_name_arc));
695
696 let surfaces = self.forward_surfaces;
697 let buffer = Arc::clone(&self.forward_buffer);
698 let layers = crate::forward::SanitizeLayers {
699 sanitizer: zeph_sanitizer::ContentSanitizer::new(content_isolation),
700 secret_registry: self.secret_registry.clone(),
701 pii_filter: self.pii_filter.clone(),
702 };
703 let span = tracing::info_span!(
704 "subagent.forward.drain",
705 task_id = %task_id_arc,
706 tui = surfaces.tui,
707 bare = surfaces.bare,
708 );
709 let drain_task_id = Arc::clone(&task_id_arc);
710 let drain_def_name = Arc::clone(&def_name_arc);
711 let drain_name: Arc<str> = Arc::from(format!("subagent-forward-drain-{task_id}").as_str());
712 let _handle = supervisor.spawn_oneshot(drain_name, move || {
713 use tracing::Instrument as _;
714 crate::forward::run_forward_drain(
715 drain_task_id,
716 drain_def_name,
717 rx,
718 layers,
719 surfaces,
720 buffer,
721 )
722 .instrument(span)
723 });
724
725 Some(sender)
726 }
727
728 /// Inject a [`DefaultWorktreeManager`][zeph_worktree::DefaultWorktreeManager] into the
729 /// manager.
730 ///
731 /// Must be called at most once, before the first [`spawn`][Self::spawn]. When set,
732 /// every spawned task acquires the process-level cwd mutex (INV-1) and agents with
733 /// `permissions.worktree = true` receive a dedicated git worktree.
734 pub fn set_worktree_manager(&mut self, wm: Arc<zeph_worktree::DefaultWorktreeManager>) {
735 self.worktree_manager = Some(wm);
736 }
737
738 /// Returns the live worktree manager, if the worktree subsystem is enabled for this
739 /// session.
740 ///
741 /// This is the same instance [`spawn`][Self::spawn] uses to create per-subagent
742 /// worktrees, so callers (e.g. the `/worktree` slash command) observe this session's
743 /// actual live state rather than a fresh disk scan. Its own
744 /// `prune_branch_on_remove()` reflects `WorktreeConfig::prune_branch_on_remove` — no
745 /// need to retain a separate copy on `SubAgentManager`.
746 #[must_use]
747 pub fn worktree_manager(&self) -> Option<&Arc<zeph_worktree::DefaultWorktreeManager>> {
748 self.worktree_manager.as_ref()
749 }
750
751 /// Drain completed hook tasks and spawn a new one if below the limit.
752 ///
753 /// Polls [`hook_tasks`][Self::hook_tasks] for finished entries so the set does not
754 /// accumulate stale handles. When the set is at capacity, logs a warning and skips
755 /// the spawn rather than growing unboundedly.
756 fn spawn_hook_task<F>(&mut self, future: F)
757 where
758 F: std::future::Future<Output = ()> + Send + 'static,
759 {
760 // Drain completed/panicked tasks before checking capacity.
761 while self.hook_tasks.try_join_next().is_some() {}
762 if self.hook_tasks.len() >= self.max_hook_tasks {
763 tracing::warn!(
764 limit = self.max_hook_tasks,
765 "hook task limit reached — dropping fire-and-forget task"
766 );
767 return;
768 }
769 self.hook_tasks.spawn(future);
770 }
771
772 /// Spawns a named subagent task under the session [`TaskSupervisor`] if one is configured,
773 /// making the task visible in TUI status and abortable on shutdown via
774 /// [`TaskSupervisor::shutdown_all`].
775 ///
776 /// Falls back to a transient local supervisor when no session supervisor has been wired via
777 /// [`SubAgentManager::set_task_supervisor`] — the task runs but is not tracked globally.
778 /// The returned [`BlockingHandle`] type is identical in both cases so call sites are uniform.
779 ///
780 /// Every agent loop task's future resolves to a `Result<T, E>` (in practice always
781 /// `Result<String, SubAgentError>`), so this classifies via
782 /// [`TaskSupervisor::spawn_oneshot_classified`] rather than plain `spawn_oneshot` — an
783 /// `Err` produced by a genuinely completed task (e.g. a worktree-quota or cwd-guard setup
784 /// failure returned before the agent loop ever starts) is thus classified and logged as a
785 /// supervisor-level failure instead of a normal completion (#6257).
786 pub(crate) fn spawn_agent_task<F, Fut, T, E>(
787 &self,
788 name: Arc<str>,
789 factory: F,
790 ) -> BlockingHandle<Result<T, E>>
791 where
792 F: FnOnce() -> Fut + Send + 'static,
793 Fut: std::future::Future<Output = Result<T, E>> + Send + 'static,
794 T: Send + 'static,
795 E: Send + 'static,
796 {
797 if let Some(ref sup) = self.task_supervisor {
798 sup.spawn_oneshot_classified(name, factory, Result::is_ok)
799 } else {
800 let local = TaskSupervisor::new(CancellationToken::new());
801 local.spawn_oneshot_classified(name, factory, Result::is_ok)
802 }
803 }
804
805 /// Reserve `n` concurrency slots for the orchestration scheduler.
806 ///
807 /// Reserved slots count against the concurrency limit in [`spawn`](Self::spawn) so that
808 /// the scheduler can guarantee capacity for tasks it is about to launch. Call
809 /// [`release_reservation`](Self::release_reservation) when the scheduler finishes.
810 pub fn reserve_slots(&mut self, n: usize) {
811 self.reserved_slots = self.reserved_slots.saturating_add(n);
812 }
813
814 /// Release `n` previously reserved concurrency slots.
815 pub fn release_reservation(&mut self, n: usize) {
816 self.reserved_slots = self.reserved_slots.saturating_sub(n);
817 }
818
819 /// Configure transcript storage settings.
820 pub fn set_transcript_config(&mut self, dir: Option<PathBuf>, max_files: usize) {
821 self.transcript_dir = dir;
822 self.transcript_max_files = max_files;
823 }
824
825 /// Set config-level lifecycle stop hooks (fired when any agent finishes or is cancelled).
826 pub fn set_stop_hooks(&mut self, hooks: Vec<super::hooks::HookDef>) {
827 self.stop_hooks = hooks;
828 }
829
830 /// Inject a fleet registry so spawned sub-agents appear in the fleet dashboard.
831 ///
832 /// When set, [`spawn`][Self::spawn] registers the session as `Active` and
833 /// [`collect`][Self::collect] / [`cancel`][Self::cancel] mark it terminal.
834 /// Errors from the registry are logged at `warn` level and never propagate to callers.
835 pub fn set_fleet_registry(&mut self, registry: SharedFleetRegistry) {
836 self.fleet_registry = Some(registry);
837 }
838
839 /// Load sub-agent definitions from the given directories.
840 ///
841 /// Higher-priority directories should appear first. Name conflicts are resolved
842 /// by keeping the first occurrence. Non-existent directories are silently skipped.
843 ///
844 /// # Errors
845 ///
846 /// Returns [`SubAgentError`] if any definition file fails to parse.
847 pub fn load_definitions(&mut self, dirs: &[PathBuf]) -> Result<(), SubAgentError> {
848 let defs = SubAgentDef::load_all(dirs)?;
849
850 // Security gate: non-Default permission_mode is forbidden when the user-level
851 // agents directory (~/.zeph/agents/) is one of the load sources. This prevents
852 // a crafted agent file from escalating its own privileges.
853 // Validation happens here (in the manager) because this is the only place
854 // that has full context about which directories were searched.
855 //
856 // FIX-5: fail-closed — if user_agents_dir is in dirs and a definition has
857 // non-Default permission_mode, we cannot verify it did not originate from the
858 // user-level dir (SubAgentDef no longer stores source_path), so we reject it.
859 let user_agents_dir = dirs::home_dir().map(|h| h.join(".zeph").join("agents"));
860 let loads_user_dir = user_agents_dir.as_ref().is_some_and(|user_dir| {
861 // FIX-8: log and treat as non-user-level if canonicalize fails.
862 match std::fs::canonicalize(user_dir) {
863 Ok(canonical_user) => dirs
864 .iter()
865 .filter_map(|d| std::fs::canonicalize(d).ok())
866 .any(|d| d == canonical_user),
867 Err(e) => {
868 tracing::warn!(
869 dir = %user_dir.display(),
870 error = %e,
871 "could not canonicalize user agents dir, treating as non-user-level"
872 );
873 false
874 }
875 }
876 });
877
878 if loads_user_dir {
879 for def in &defs {
880 if def.permissions.permission_mode != PermissionMode::Default {
881 return Err(SubAgentError::Invalid(format!(
882 "sub-agent '{}': non-default permission_mode is not allowed for \
883 user-level definitions (~/.zeph/agents/)",
884 def.name
885 )));
886 }
887 }
888 }
889
890 self.definitions = defs;
891 tracing::info!(
892 count = self.definitions.len(),
893 "sub-agent definitions loaded"
894 );
895 Ok(())
896 }
897
898 /// Load definitions with full scope context for source tracking and security checks.
899 ///
900 /// The blocking filesystem scan runs on a dedicated thread via
901 /// `tokio::task::spawn_blocking` so the tokio worker thread is not stalled (#5108).
902 ///
903 /// # Errors
904 ///
905 /// Returns [`SubAgentError`] if a CLI-sourced definition file fails to parse.
906 #[tracing::instrument(name = "subagent.manager.load_definitions_with_sources", skip_all)]
907 pub async fn load_definitions_with_sources(
908 &mut self,
909 ordered_paths: &[PathBuf],
910 cli_agents: &[PathBuf],
911 config_user_dir: Option<&PathBuf>,
912 extra_dirs: &[PathBuf],
913 ) -> Result<(), SubAgentError> {
914 // Clone inputs so they can be moved into spawn_blocking ('static bound).
915 let ordered = ordered_paths.to_vec();
916 let cli = cli_agents.to_vec();
917 let user_dir = config_user_dir.cloned();
918 let extra = extra_dirs.to_vec();
919
920 let defs = tokio::task::spawn_blocking(move || {
921 SubAgentDef::load_all_with_sources(&ordered, &cli, user_dir.as_ref(), &extra)
922 })
923 .await
924 .map_err(|e| SubAgentError::TaskPanic(format!("load_definitions_with_sources: {e}")))?;
925
926 self.definitions = defs?;
927 tracing::info!(
928 count = self.definitions.len(),
929 "sub-agent definitions loaded"
930 );
931 Ok(())
932 }
933
934 /// Return all loaded definitions.
935 #[must_use]
936 pub fn definitions(&self) -> &[SubAgentDef] {
937 &self.definitions
938 }
939
940 /// Return mutable access to the loaded definitions list.
941 ///
942 /// Intended for test harnesses and dynamic definition registration. Production code
943 /// should prefer [`load_definitions`][Self::load_definitions].
944 pub fn definitions_mut(&mut self) -> &mut Vec<SubAgentDef> {
945 &mut self.definitions
946 }
947
948 /// Insert a pre-built handle directly into the active agents map.
949 ///
950 /// Used in tests to simulate an agent that has already run and left a pending secret
951 /// request in its channel without going through the full spawn lifecycle.
952 pub fn insert_handle_for_test(&mut self, id: String, handle: SubAgentHandle) {
953 self.agents.insert(id, handle);
954 }
955}
956
957#[cfg(test)]
958mod tests;