agentmux_srv_core/backend/subagent_watcher/mod.rs
1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Subagent watcher: monitors Claude Code session directories for subagent
5//! JSONL files and broadcasts activity events to WebSocket clients.
6//!
7//! Claude Code spawns "subagents" via the Task tool. Each subagent writes its
8//! conversation to a JSONL file under:
9//! `<claude-config>/projects/<encoded-workspace>/subagents/agent-<id>.jsonl`
10//!
11//! A Workflow tool run nests its member agents one level deeper, under a
12//! per-run directory, and adds a run-level journal:
13//! `<claude-config>/projects/<encoded-workspace>/subagents/workflows/<run-id>/agent-<id>.jsonl`
14//! `<claude-config>/projects/<encoded-workspace>/subagents/workflows/<run-id>/journal.jsonl`
15//!
16//! This module watches those directories and emits:
17//! - `subagent:spawned` — new subagent JSONL file detected
18//! - `subagent:activity` — new events for a Solo dispatch's one member,
19//! broadcast immediately (existing per-member consumers, e.g. the
20//! agent-pane activity dock, still rely on this)
21//! - `subagent:completed` — subagent finished (result event seen)
22//! - `subagent:named` — a `SubAgent.display_name` resolved (on-demand
23//! click-triggered, or eager at dispatch time — see `trigger_eager_naming`)
24//! - `dispatch:updated` — an `AgentDispatch`'s member count, status, or
25//! `dispatch_name` changed (both Solo and Workflow kinds)
26//! - `dispatch:activity` — coalesced new events across a dispatch's
27//! members, flushed every `DISPATCH_ACTIVITY_FLUSH_INTERVAL`. Workflow
28//! dispatches are ONLY ever represented here (no per-member broadcast).
29//! Solo dispatches are ALSO queued here in addition to the immediate
30//! `subagent:activity` above (dual emission, not a replacement) — see
31//! docs/specs/SPEC_SWARM_DISPATCH_NAMING_AND_ROW_MODEL_2026_07_19.md
32//! Phase A, added so a solo dispatch's row can use the same
33//! concatenated-feed expand mechanism a Workflow row already had.
34//! - `subagent:block_pruned` — a deleted block's subagents/dispatches were
35//! just pruned from this watcher's state (`prune_block`/`unwatch_agent`,
36//! driven by `spawn_block_prune_subscriber` reacting to
37//! `Event::BlockDeleted`/`TabDeleted`/`WorkspaceDeleted`). Without this,
38//! `ListActive`/`ListDispatches` kept returning a closed block's
39//! subagents forever, so the Swarm pane kept rendering a ghost row for
40//! it until the whole app/srv restarted. `prune_block` also tears down
41//! the block's own filesystem watcher (`unwatch_block`) — without that,
42//! a closed block's watcher leaked indefinitely and kept re-creating
43//! fresh (mis-)attributions the next time another agent sharing its
44//! watched directory wrote to its own subagent transcript; see
45//! `session_belongs_to_block` and
46//! docs/retro/retro-subagent-watcher-shared-dir-fanout-and-leak-2026-07-23.md.
47//!
48//! Split into submodules (pure relocation, no behavior change): `types` (the
49//! state/event types), `query` (the read/naming API), `scan` (session/dir
50//! backfill scanning + stale-subagent reconciliation), `jsonl` (the JSONL/
51//! journal file-change state machine and dispatch-activity coalescing), and
52//! `parse` (free-standing path/JSONL parsing utilities). This file keeps the
53//! `SubagentWatcher` struct definition and its lifecycle methods (`new`/
54//! `spawn`/`watch_agent`/`unwatch_agent`/`prune_block*`).
55
56pub mod completion;
57pub mod events;
58pub mod jsonl;
59pub mod parse;
60pub mod query;
61pub mod reconcile_steps;
62pub mod scan;
63pub mod types;
64
65#[cfg(test)]
66mod tests;
67
68#[allow(unused_imports)]
69pub use parse::{
70 derive_claude_config_dir, resolve_claude_config_dir,
71 spawn_block_prune_subscriber,
72};
73pub(crate) use parse::read_task_prompt;
74#[allow(unused_imports)]
75pub use types::{
76 AgentDispatch, DispatchKind, DispatchStatus, SubAgent, SubAgentStatus, SubagentEvent,
77 SubagentEventType,
78};
79
80use std::collections::HashMap;
81use std::path::{Path, PathBuf};
82use std::sync::{Arc, Mutex, OnceLock};
83use std::time::Duration;
84
85use notify::{EventKind, RecommendedWatcher, RecursiveMode, Watcher};
86use tokio::sync::mpsc;
87
88use super::eventbus::EventBus;
89use parse::{derive_session_id, nearest_existing_ancestor};
90use types::{DispatchState, PendingDispatchActivity, SessionWatch, WatchedAgent};
91
92/// Flush cadence for buffered dispatch activity (SPEC §9.5 — 250ms-1s was
93/// floated as a plausible range, not measured; 500ms is the midpoint,
94/// picked as a reasonable default pending real usage data).
95const DISPATCH_ACTIVITY_FLUSH_INTERVAL: Duration = Duration::from_millis(500);
96
97// Host-wide instance, set once at startup (`set_global`, called from
98// bootstrap/background.rs right after `SubagentWatcher::spawn`). Exposed as a global —
99// mirroring `process_tracker::registry`'s own doc comment for the exact
100// same problem — so callers that only occasionally need it (like
101// `blockcontroller/persistent/stdout_reader.rs`'s turn-end reconciliation hook,
102// SPEC_SUBAGENT_LIVE_RECONCILIATION_AND_RETIRE_2026_07_20 Phase A) can reach it
103// without threading an `Arc` through `PersistentSubprocessController::new`
104// and every one of ITS callers up to `resync_controller`. Tests that don't
105// call `set_global` see `None` from `global()` and skip reconciliation —
106// a safe no-op, not a panic.
107static GLOBAL: OnceLock<Arc<SubagentWatcher>> = OnceLock::new();
108
109pub fn set_global(watcher: Arc<SubagentWatcher>) {
110 let _ = GLOBAL.set(watcher);
111}
112
113pub fn global() -> Option<Arc<SubagentWatcher>> {
114 GLOBAL.get().cloned()
115}
116
117pub struct SubagentWatcher {
118 event_bus: Arc<EventBus>,
119 mstore: Arc<crate::backend::storage::store::Store>,
120 /// Held so `recheck_config_dir`/`recheck_all_watched_agents` (called
121 /// from the identity-bind RPC handlers, `server/app_api/identity.rs`
122 /// and `server/agent_handlers/identity.rs`) can re-resolve a fresh
123 /// identity binding without every caller needing to thread these
124 /// stores through. NOT used to self-verify inside `watch_agent`/
125 /// `start_watch` itself — an earlier version of this fix tried that
126 /// and broke callers whose `config_dir` isn't backed by a resolvable
127 /// instance/binding row at all (the legacy `parent_block_id: ""` manual
128 /// RPC entry point, and several tests); see `watch_agent`'s own doc
129 /// comment for why that self-check lives in `handle_reactive_register`
130 /// instead, scoped to the one call site that actually derives
131 /// `config_dir` from identity/binding resolution in the first place.
132 id_store: Arc<crate::backend::storage::store::Store>,
133 identity_store: Arc<crate::backend::storage::store::Store>,
134 sessions: Mutex<HashMap<String, SessionWatch>>,
135 watched_agents: Mutex<Vec<WatchedAgent>>,
136 dispatches: Mutex<HashMap<String, DispatchState>>,
137 pending_activity: Mutex<HashMap<String, PendingDispatchActivity>>,
138 /// Dispatch IDs that have already had their one eager Haiku-naming call
139 /// triggered (issue: SPEC_SWARM_DISPATCH_NAMING_AND_ROW_MODEL_2026_07_19)
140 /// — checked-and-inserted atomically at the same point `is_new` is
141 /// computed in `process_jsonl_change`, so a Workflow dispatch (whose
142 /// `dispatch_id` is shared by every member) only ever triggers once,
143 /// on its first-observed-live member, not once per member. Never
144 /// cleared — naming is "at most once ever per dispatch," not a
145 /// retryable in-flight guard (unlike `activity_watcher.rs`'s
146 /// `in_flight` set, which this deliberately does NOT mirror: there's no
147 /// "try again later" concept for a dispatch's name).
148 naming_triggered: Mutex<std::collections::HashSet<String>>,
149 /// Weak self-reference, populated once by `spawn()` right after the
150 /// `Arc::new` that wraps this watcher — lets any `&self` method upgrade
151 /// to `Arc<Self>` to move into a `tokio::spawn`ed background task (the
152 /// eager-naming trigger) without threading `Arc<Self>` through every
153 /// caller of `process_jsonl_change` (`scan_subagents_dir`/
154 /// `scan_session_subagents`, both `&self` today). `None` for a
155 /// `SubagentWatcher` built via bare `new()` (as most tests do, to skip
156 /// the background flush loop) — eager naming silently no-ops in that
157 /// case rather than panicking, matching this module's existing
158 /// "unknown/untracked -> safe no-op" convention (see `set_display_name`).
159 self_ref: Mutex<Option<std::sync::Weak<SubagentWatcher>>>,
160 /// The scoped, persisted MPS broker -- used only for
161 /// `subagent:backfill_status` (`scan.rs`'s `publish_backfill_status`),
162 /// so a pane can query "is my own backfill still in progress" via
163 /// `EventReadHistoryCommand` rather than relying solely on live-event
164 /// timing (mirrors the identical `agent-resume-retry` design,
165 /// `docs/status/STATUS_STALE_RESUME_LIVE_REPRO_AND_FIX_PLAN_2026_08_23.md`
166 /// section 6.2). Deliberately separate from `event_bus` above (the raw,
167 /// unscoped, unpersisted WS fan-out every OTHER event in this module
168 /// uses) -- this one event specifically needs the scope+persist
169 /// semantics only `mps::Broker` provides. `None` until `set_broker` is
170 /// called (bootstrap only, after both this watcher and the broker
171 /// exist) -- every test call site built via bare `new()` skips this
172 /// event entirely rather than panicking, same posture as `self_ref`.
173 broker: Mutex<Option<Arc<crate::backend::mps::Broker>>>,
174 /// reagentx P2 (PR #2781): `scan_session_subagents` can be called twice
175 /// for the SAME `parent_block_id` in overlapping fashion (the same
176 /// block re-registered under a new `agent_id` -- see
177 /// `server/reactive.rs`'s caller comment -- while an earlier call for
178 /// that same block id is still mid-scan). Without this, an OLDER call's
179 /// "done" can publish after a NEWER call's "started" already fired,
180 /// prematurely clearing the `subagent:backfill_status` gate while the
181 /// newer scan is still running. Keyed by `parent_block_id`, incremented
182 /// at the start of every call; a call only publishes "done" if its own
183 /// captured generation is STILL the latest recorded one for that block
184 /// id when it finishes -- a stale call silently skips "done" entirely,
185 /// leaving the (correctly still-in-progress) gate to whichever call is
186 /// actually current. See `scan.rs`'s `scan_session_subagents`.
187 backfill_generation: Mutex<HashMap<String, u64>>,
188}
189
190impl SubagentWatcher {
191 pub fn new(
192 event_bus: Arc<EventBus>,
193 mstore: Arc<crate::backend::storage::store::Store>,
194 id_store: Arc<crate::backend::storage::store::Store>,
195 identity_store: Arc<crate::backend::storage::store::Store>,
196 ) -> Self {
197 Self {
198 event_bus,
199 mstore,
200 id_store,
201 identity_store,
202 sessions: Mutex::new(HashMap::new()),
203 watched_agents: Mutex::new(Vec::new()),
204 dispatches: Mutex::new(HashMap::new()),
205 pending_activity: Mutex::new(HashMap::new()),
206 naming_triggered: Mutex::new(std::collections::HashSet::new()),
207 self_ref: Mutex::new(None),
208 broker: Mutex::new(None),
209 backfill_generation: Mutex::new(HashMap::new()),
210 }
211 }
212
213 /// Wire in the shared MPS broker post-construction (bootstrap only) --
214 /// see the `broker` field's own doc comment for why this is optional
215 /// and set separately rather than a constructor parameter.
216 pub fn set_broker(&self, broker: Arc<crate::backend::mps::Broker>) {
217 *self.broker.lock().unwrap() = Some(broker);
218 }
219
220 /// Create a new SubagentWatcher and return it wrapped in Arc. Also
221 /// starts the background flush loop for coalesced dispatch activity
222 /// (SPEC §7) — runs for the lifetime of the process, mirroring
223 /// `watch_agent`'s existing `tokio::spawn` pattern.
224 pub fn spawn(
225 event_bus: Arc<EventBus>,
226 mstore: Arc<crate::backend::storage::store::Store>,
227 id_store: Arc<crate::backend::storage::store::Store>,
228 identity_store: Arc<crate::backend::storage::store::Store>,
229 ) -> Arc<Self> {
230 let watcher = Arc::new(Self::new(event_bus, mstore, id_store, identity_store));
231 *watcher.self_ref.lock().unwrap() = Some(Arc::downgrade(&watcher));
232 tracing::info!("subagent watcher initialized");
233 let flusher = Arc::clone(&watcher);
234 tokio::spawn(async move {
235 let mut interval = tokio::time::interval(DISPATCH_ACTIVITY_FLUSH_INTERVAL);
236 loop {
237 interval.tick().await;
238 flusher.flush_pending_dispatch_activity();
239 }
240 });
241 watcher
242 }
243
244 /// Start watching a Claude Code agent's session directory for subagent files.
245 /// Spawns a background tokio task for debounced file event processing.
246 ///
247 /// `parent_block_id` is the pane/block that owns this Claude instance (from
248 /// the reactive register request). It is stamped onto every emitted subagent
249 /// event so the frontend can route the ⚡ panel to the originating pane only,
250 /// instead of every agent pane rendering every subagent globally.
251 ///
252 /// Note: the watcher dedupes by `agent_id`, so if the same agent_id is
253 /// registered from two blocks, events carry the first registrant's block id.
254 /// That edge case (same instance name in two panes) is rare; the common
255 /// leak — a terminal Claude's subagents showing up in unrelated agent panes —
256 /// is fully fixed because the terminal block id never matches an agent pane.
257 pub fn watch_agent(self: &Arc<Self>, agent_id: &str, parent_block_id: &str, config_dir: PathBuf) {
258 // Check if already watching this agent. A second block registering
259 // the same agent_id adds itself as a dependent of the existing
260 // shared watcher (see WatchedAgent::parent_block_ids) instead of
261 // being silently dropped — otherwise `unwatch_block` (below) had no
262 // way to tell that a still-open second block also depended on this
263 // watcher when the first one closed.
264 {
265 let mut watched = self.watched_agents.lock().unwrap();
266 if let Some(existing) = watched.iter_mut().find(|w| w.agent_id == agent_id) {
267 existing.parent_block_ids.insert(parent_block_id.to_string());
268 tracing::debug!(agent = %agent_id, parent_block_id = %parent_block_id, "already watching this agent");
269 return;
270 }
271 }
272 // NOTE: does NOT self-verify its own resolution against a fresh
273 // identity lookup after inserting — an earlier version of this fix
274 // did exactly that (Codex P1 on PR #2980: closing the narrow race
275 // between `handle_reactive_register` resolving `config_dir` and
276 // this call actually installing the watch), but `watch_agent` is a
277 // generic primitive with OTHER callers whose `config_dir` isn't
278 // necessarily backed by a resolvable instance/binding row at all —
279 // the legacy manual `subagent.WatchAgent` RPC entry point
280 // (`server/service/misc.rs`) passes `parent_block_id: ""`
281 // specifically for callers with no pane to scope to, and a blind
282 // re-resolve there (or for any test/manual caller whose block has
283 // no real `AgentInstance`) fell through `resolve_claude_config_dir`'s
284 // last-resort `derive_claude_config_dir` fallback and silently
285 // repointed the watch away from the caller's own explicit choice
286 // (confirmed live: broke `live_fs_event_with_empty_block_id_
287 // bypasses_the_ownership_check` and `live_fs_event_is_not_
288 // misattributed_to_a_block_that_does_not_own_the_session`). The
289 // self-check that DOES close this race lives in
290 // `handle_reactive_register` itself instead, immediately after ITS
291 // `watch_agent` call — the one call site that actually derived
292 // `config_dir` from identity/binding resolution in the first place,
293 // so a fresh re-resolve there can only ever mean "the DB state
294 // changed since I last read it," never "this caller never intended
295 // identity resolution to apply here at all."
296 self.start_watch(agent_id, parent_block_id, config_dir);
297 }
298
299 /// Re-resolve and, if the answer changed, re-point an already-watched
300 /// agent's filesystem watch at a corrected directory. `watch_agent`'s
301 /// own config-dir resolution only ever runs ONCE per agent, at the
302 /// reactive-register handshake — before this agent's identity binding
303 /// is necessarily committed to the DB yet (a genuinely observed race:
304 /// a fresh agent launch's reactive-register can fire before the launch
305 /// flow's own account-bind write lands, landing on a stale/ambient
306 /// `cmd:env` snapshot instead of the real identity-bound directory).
307 /// If that race is lost, the watcher previously had no correction
308 /// mechanism at all — nothing else ever calls `watch_agent` again for
309 /// an already-registered pane, so it silently watched the wrong
310 /// directory, forever, for the rest of that pane's life. Called from
311 /// `watch_agent` itself (a post-insert self-check) and from the
312 /// identity-bind RPC handlers (`server/app_api/identity.rs`,
313 /// `server/agent_handlers/identity.rs`) via `recheck_all_watched_agents`
314 /// below, right after a successful `agent_identity_link` write.
315 ///
316 /// No-op if `agent_id` isn't currently watched (nothing to correct —
317 /// its next real registration resolves fresh, by-then-committed
318 /// bindings correctly on its own) or if the newly-resolved directory
319 /// is unchanged. See
320 /// docs/reports/REPORT_SWARM_SUBAGENT_WATCHER_ONE_SHOT_RESOLUTION_RACE_2026_09_04.md.
321 pub fn recheck_config_dir(self: &Arc<Self>, agent_id: &str, new_config_dir: PathBuf) {
322 let (primary_block_id, all_block_ids, old_dir) = {
323 let watched = self.watched_agents.lock().unwrap();
324 let Some(existing) = watched.iter().find(|w| w.agent_id == agent_id) else {
325 return;
326 };
327 if existing.config_dir == new_config_dir {
328 return;
329 }
330 (existing.primary_block_id.clone(), existing.parent_block_ids.clone(), existing.config_dir.clone())
331 };
332 // Codex P2 on PR #2980: build the replacement BEFORE touching the
333 // existing (stale-but-working) entry. If the new directory's
334 // watcher fails to construct or `.watch()` fails (a transient
335 // resource/permission/filesystem error), keep the old watch in
336 // place rather than losing tracking for this agent entirely —
337 // `build_watch` itself already logs the specific failure reason.
338 let Some((watcher, rx)) = self.build_watch(agent_id, &new_config_dir) else {
339 tracing::warn!(
340 agent = %agent_id,
341 old_dir = %old_dir.display(),
342 new_dir = %new_config_dir.display(),
343 "identity rebind resolved a new subagent config dir, but the replacement watch failed to start — keeping the existing watch"
344 );
345 return;
346 };
347 tracing::info!(
348 agent = %agent_id,
349 old_dir = %old_dir.display(),
350 new_dir = %new_config_dir.display(),
351 "identity rebind changed this agent's Claude config dir — re-pointing subagent watch"
352 );
353 // Atomic swap: remove the old entry (dropping its `_watcher`,
354 // which stops the stale `notify` subscription — the same RAII
355 // teardown `unwatch_agent`/`unwatch_block` rely on) and insert the
356 // replacement in one critical section, preserving the ORIGINAL
357 // `primary_block_id` and the full `parent_block_ids` set — Codex
358 // P3 on PR #2980: never re-derive the primary from the (unordered)
359 // set, which could silently attribute subsequent events to a
360 // different pane than before.
361 {
362 let mut watched = self.watched_agents.lock().unwrap();
363 watched.retain(|w| w.agent_id != agent_id);
364 watched.push(WatchedAgent {
365 agent_id: agent_id.to_string(),
366 primary_block_id: primary_block_id.clone(),
367 parent_block_ids: all_block_ids.clone(),
368 config_dir: new_config_dir.clone(),
369 _watcher: watcher,
370 });
371 }
372 self.spawn_consumer_loop(agent_id, &primary_block_id, rx);
373 // Backfill anything genuinely missed while the watch was pointed at
374 // the wrong directory — same session-scoped mechanism, and the same
375 // reason for scoping it, as `handle_reactive_register`'s own
376 // backfill call: a blind scan-everything would flood Swarm with
377 // every session this identity has ever run, not just this pane's.
378 for block_id in &all_block_ids {
379 let Ok(Some(block)) = self.mstore.get::<crate::backend::obj::Block>(block_id) else {
380 continue;
381 };
382 let session_id = crate::backend::obj::meta_get_string(
383 &block.meta,
384 crate::backend::blockcontroller::core::META_SESSION_ID,
385 "",
386 );
387 if !session_id.is_empty() {
388 self.scan_session_subagents(agent_id, block_id, &new_config_dir, &session_id);
389 }
390 }
391 }
392
393 /// Re-check every currently-watched agent's Claude config dir against a
394 /// fresh identity resolution, re-pointing (`recheck_config_dir`) any
395 /// whose resolution changed. Cheap and safe to call from anywhere an
396 /// identity/account binding just changed — the number of currently-
397 /// watched agents on a single instance is small, and this only runs on
398 /// the rare bind/rebind path, never per-turn.
399 pub fn recheck_all_watched_agents(self: &Arc<Self>) {
400 let candidates: Vec<(String, String)> = {
401 let watched = self.watched_agents.lock().unwrap();
402 watched.iter().map(|w| (w.agent_id.clone(), w.primary_block_id.clone())).collect()
403 };
404 for (agent_id, block_id) in candidates {
405 // ReAgent P1 on PR #2980, round 2: this is called on EVERY
406 // `agent_identity_link` write anywhere in the app, with no
407 // scoping to the agent whose identity actually changed, and it
408 // used to iterate every `WatchedAgent` regardless of whether
409 // that entry's `config_dir` was ever derived from identity
410 // resolution in the first place. An agent registered via the
411 // still-live legacy `subagent.WatchAgent` RPC
412 // (`server/service/misc.rs`) passes `parent_block_id: ""` and
413 // an arbitrary caller-supplied `config_dir` that has nothing to
414 // do with identity binding — exactly the shape `watch_agent`'s
415 // own doc comment already documents as needing to stay outside
416 // identity resolution's reach. Without this guard, a resolve
417 // against a nonexistent block falls through
418 // `resolve_claude_config_dir`'s last-resort
419 // `derive_claude_config_dir` guess and silently repoints that
420 // agent away from its caller's explicit choice — the SAME
421 // failure class the P1 fix's first (reverted) attempt already
422 // hit once inside `watch_agent` itself, reappearing here one
423 // layer up. Skip any candidate with no real, resolvable block:
424 // an empty id can never correspond to one, and a nonexistent
425 // block means there is nothing for identity resolution to
426 // legitimately apply to.
427 if block_id.is_empty() {
428 continue;
429 }
430 let Some(block) = self.mstore.get::<crate::backend::obj::Block>(&block_id).ok().flatten() else {
431 continue;
432 };
433 let bound_dir = crate::identity::resolver::resolve_bound_oauth_config_dir(
434 &self.mstore,
435 &self.id_store,
436 &self.identity_store,
437 &block_id,
438 );
439 crate::identity::foreign_dir::heal_block_config_dir_env(&self.mstore, Some(&block), bound_dir.as_deref());
440 let new_dir = resolve_claude_config_dir(&block.meta, &agent_id, bound_dir);
441 if let Some(new_dir) = new_dir {
442 self.recheck_config_dir(&agent_id, new_dir);
443 }
444 }
445 }
446
447 /// Build (but do not install) a `notify` watcher for `config_dir`,
448 /// falling back to the nearest existing ancestor directory if it
449 /// doesn't exist on disk yet. Returns `None` on any failure — every
450 /// branch already logs its own specific reason. Deliberately has NO
451 /// side effect on `watched_agents`: callers (`start_watch` for a
452 /// first-time registration, `recheck_config_dir` for a repoint) decide
453 /// separately whether/how to install the result, which is what lets
454 /// `recheck_config_dir` build the replacement before touching the
455 /// existing entry (Codex P2 on PR #2980).
456 fn build_watch(
457 self: &Arc<Self>,
458 agent_id: &str,
459 config_dir: &Path,
460 ) -> Option<(RecommendedWatcher, mpsc::UnboundedReceiver<PathBuf>)> {
461 // Derive the projects directory where Claude stores session data
462 let projects_dir = config_dir.join("projects");
463 if !projects_dir.exists() {
464 tracing::debug!(
465 agent = %agent_id,
466 dir = %projects_dir.display(),
467 "projects dir does not exist yet, will watch when created"
468 );
469 }
470
471 let (tx, rx) = mpsc::unbounded_channel::<PathBuf>();
472
473 // Set up filesystem watcher. `watch_agent` is called from the
474 // reactive-register handshake, which fires as soon as the CLI's hook
475 // reaches AgentMux — well before the CLI itself has necessarily
476 // created its `CLAUDE_CONFIG_DIR` on disk (a live trace showed a 47s
477 // gap between register and the persistent process actually
478 // spawning). Watching a path that doesn't exist yet fails outright
479 // with no retry, permanently disabling subagent tracking for that
480 // agent's whole session — the observed cause of subagents silently
481 // never appearing in Swarm. Fall back to the nearest EXISTING
482 // ancestor (typically `~/.config`, effectively always present) so
483 // the watch succeeds immediately and the recursive mode picks up
484 // `config_dir`/`projects_dir` once the CLI creates them.
485 let watched_dir = if projects_dir.exists() {
486 projects_dir.clone()
487 } else if config_dir.exists() {
488 config_dir.to_path_buf()
489 } else {
490 match nearest_existing_ancestor(config_dir) {
491 Some(dir) => {
492 tracing::info!(
493 agent = %agent_id,
494 config_dir = %config_dir.display(),
495 watching = %dir.display(),
496 "config dir does not exist yet — watching nearest existing ancestor instead"
497 );
498 dir
499 }
500 None => {
501 tracing::warn!(
502 agent = %agent_id,
503 config_dir = %config_dir.display(),
504 "no existing ancestor found for config dir — cannot watch for subagents"
505 );
506 return None;
507 }
508 }
509 };
510
511 // Filters events to this agent's config dir regardless of which
512 // directory ended up watched — a no-op when watching config_dir or
513 // projects_dir directly (both are already under config_dir), but
514 // essential when watching a shared ancestor above: without it,
515 // every other agent's subagent files under that same ancestor would
516 // be misattributed to this agent_id.
517 let config_dir_filter = config_dir.to_path_buf();
518 let tx_clone = tx.clone();
519
520 let mut watcher = match notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
521 match res {
522 Ok(event) => {
523 let dominated = matches!(
524 event.kind,
525 EventKind::Modify(_) | EventKind::Create(_)
526 );
527 if dominated {
528 for path in event.paths {
529 if !path.starts_with(&config_dir_filter) {
530 continue;
531 }
532 if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
533 let is_subagent =
534 name.starts_with("agent-") && name.ends_with(".jsonl");
535 // Workflow run journals live at
536 // subagents/workflows/<wf>/journal.jsonl and drive
537 // workflow-level progress counters.
538 let is_journal = name == "journal.jsonl";
539 if is_subagent || is_journal {
540 let _ = tx_clone.send(path);
541 } else if let Some(transcript) =
542 completion::transcript_for_sidecar(&path)
543 {
544 // The sidecar can land after the transcript's
545 // last line; re-process the transcript so its
546 // `tool_use_id` retry runs (jsonl.rs).
547 let _ = tx_clone.send(transcript);
548 }
549 }
550 }
551 }
552 }
553 Err(e) => {
554 tracing::warn!(error = %e, "subagent filesystem watcher error");
555 }
556 }
557 }) {
558 Ok(w) => w,
559 Err(e) => {
560 tracing::warn!(
561 agent = %agent_id,
562 error = %e,
563 "failed to create subagent file watcher"
564 );
565 return None;
566 }
567 };
568
569 if let Err(e) = watcher.watch(&watched_dir, RecursiveMode::Recursive) {
570 tracing::warn!(
571 agent = %agent_id,
572 dir = %watched_dir.display(),
573 error = %e,
574 "failed to watch directory for subagents"
575 );
576 return None;
577 }
578
579 tracing::info!(
580 agent = %agent_id,
581 dir = %watched_dir.display(),
582 "watching for subagent JSONL files"
583 );
584
585 Some((watcher, rx))
586 }
587
588 /// First-time registration for an agent_id: build the watch and, if it
589 /// succeeds, install it (`WatchedAgent`, with `parent_block_id` as both
590 /// the initial `primary_block_id` and sole member of `parent_block_ids`)
591 /// and spawn its consumer loop. A no-op (nothing installed, nothing
592 /// spawned) if `build_watch` fails — already logs its own reason,
593 /// nothing further to report here.
594 fn start_watch(self: &Arc<Self>, agent_id: &str, parent_block_id: &str, config_dir: PathBuf) {
595 let Some((watcher, rx)) = self.build_watch(agent_id, &config_dir) else {
596 return;
597 };
598 {
599 let mut watched = self.watched_agents.lock().unwrap();
600 watched.push(WatchedAgent {
601 agent_id: agent_id.to_string(),
602 primary_block_id: parent_block_id.to_string(),
603 parent_block_ids: std::iter::once(parent_block_id.to_string()).collect(),
604 config_dir,
605 _watcher: watcher,
606 });
607 }
608
609 // Deliberately NOT scanning history here. `watch_agent` runs at
610 // reactive-register time — before this agent identity's session for
611 // *this pane* is known — and `projects_dir` covers every project
612 // this agent identity has EVER worked in, across every past
613 // session. A blind scan here used to flood the Swarm view with
614 // every subagent this identity had ever spawned, in every project,
615 // the moment any pane for it was reopened (observed: 20 old
616 // sessions, 4-18 subagent files each, all appearing at once). A
617 // brand-new session has nothing to backfill — subagents will be
618 // picked up live, correctly, as the Task tool spawns them. A
619 // RESUMED session's own prior subagents (still legitimately
620 // relevant) are scoped in via `scan_session_subagents`, called from
621 // `handle_reactive_register` when the block's persisted
622 // `agent:sessionid` meta says which exact session this pane is
623 // resuming. See
624 // docs/specs/archive/REPORT_SWARM_SUBAGENT_HISTORY_FLOOD_2026_07_07.md.
625 self.spawn_consumer_loop(agent_id, parent_block_id, rx);
626 }
627
628 /// Spawn the debounced background task that consumes raw filesystem
629 /// events for one agent's watch and dispatches them to
630 /// `process_jsonl_change`/`process_journal_change`. Shared by
631 /// `start_watch` (first registration) and `recheck_config_dir`
632 /// (repointing an existing watch at a corrected directory) — same
633 /// consumer mechanics either way, just fed by a different `rx`.
634 fn spawn_consumer_loop(
635 self: &Arc<Self>,
636 agent_id: &str,
637 parent_block_id: &str,
638 mut rx: mpsc::UnboundedReceiver<PathBuf>,
639 ) {
640 let self_clone = Arc::clone(self);
641 let parent_agent = agent_id.to_string();
642 let parent_block_id = parent_block_id.to_string();
643 tokio::spawn(async move {
644 loop {
645 let path = match rx.recv().await {
646 Some(p) => p,
647 None => {
648 tracing::info!(
649 agent = %parent_agent,
650 "subagent watcher channel closed"
651 );
652 break;
653 }
654 };
655
656 // Debounce: drain additional events within 200ms
657 tokio::time::sleep(Duration::from_millis(200)).await;
658 let mut paths = vec![path];
659 while let Ok(p) = rx.try_recv() {
660 if !paths.contains(&p) {
661 paths.push(p);
662 }
663 }
664
665 for changed_path in paths {
666 // Agents without a per-account auth dir all
667 // resolve to the same shared default Claude config dir
668 // (see resolve_claude_config_dir's doc comment), so this
669 // watcher's notify subscription can legitimately be on a
670 // directory tree several OTHER agents' watchers are also
671 // subscribed to. Without this check, one agent's real
672 // subagent write fans out to every other agent sharing
673 // that path, each misattributing it to their own
674 // parent_block_id. See
675 // docs/retro/retro-subagent-watcher-shared-dir-fanout-and-leak-2026-07-23.md.
676 //
677 // Skipped entirely when parent_block_id is empty — the
678 // legacy/manual `subagent.WatchAgent` RPC entry point
679 // (server/service/misc.rs) deliberately passes "" for
680 // callers with no pane to scope to; there's no block to
681 // own the session against, so the check would otherwise
682 // reject every event from that path unconditionally.
683 let session_id = derive_session_id(&changed_path);
684 if !parent_block_id.is_empty()
685 && !self_clone.session_belongs_to_block(&parent_block_id, &session_id)
686 {
687 tracing::debug!(
688 agent = %parent_agent,
689 parent_block_id = %parent_block_id,
690 session_id = %session_id,
691 path = %changed_path.display(),
692 "dropping subagent fs event: session does not belong to this block"
693 );
694 continue;
695 }
696
697 let is_journal = changed_path.file_name().and_then(|n| n.to_str())
698 == Some("journal.jsonl");
699 if is_journal {
700 self_clone.process_journal_change(
701 &parent_agent,
702 &parent_block_id,
703 &changed_path,
704 );
705 } else {
706 // live=true: this came from the filesystem watcher
707 // observing a real, in-the-moment change — eligible
708 // to trigger eager Haiku naming.
709 self_clone.process_jsonl_change(
710 &parent_agent,
711 &parent_block_id,
712 &changed_path,
713 true,
714 );
715 }
716 }
717 }
718 });
719 }
720
721 /// True if `session_id` is the session currently persisted on
722 /// `block_id`'s own `agent:sessionid` meta. Used by the live
723 /// filesystem-watch dispatch loop (`watch_agent`) to reject an event for
724 /// a session this block doesn't actually own before it can be
725 /// misattributed — necessary because agents without a per-identity
726 /// bundle override all share one `notify` subscription on the same
727 /// default Claude config dir (see `resolve_claude_config_dir`), so any
728 /// one of their watchers can receive any other's raw file-change events.
729 /// `false` for a block that no longer exists (closed pane) or has since
730 /// moved to a different session — both cases mean this event isn't this
731 /// block's to process. See
732 /// docs/retro/retro-subagent-watcher-shared-dir-fanout-and-leak-2026-07-23.md.
733 fn session_belongs_to_block(&self, block_id: &str, session_id: &str) -> bool {
734 let Ok(Some(block)) = self.mstore.get::<crate::backend::obj::Block>(block_id) else {
735 return false;
736 };
737 crate::backend::obj::meta_get_string(
738 &block.meta,
739 crate::backend::blockcontroller::core::META_SESSION_ID,
740 "",
741 ) == session_id
742 }
743
744 /// Stop watching an agent from the graceful `/agentmux/reactive/unregister`
745 /// path: remove `block_id` as a dependent of its watcher (same
746 /// mechanism as `unwatch_block`, keyed by `agent_id` first since that's
747 /// what the caller has), tearing down the underlying filesystem watcher
748 /// — which closes the debounce channel, so the processing task
749 /// self-terminates on its next `rx.recv()` returning `None` — only once
750 /// no block depends on it anymore. Idempotent: a no-op if the agent
751 /// isn't currently watched.
752 ///
753 /// `block_id` is `None` when the reactive registry has no record of
754 /// this agent_id (already unregistered, or never registered) — nothing
755 /// to disassociate in that case, so the watcher-teardown step is
756 /// skipped entirely rather than guessing.
757 ///
758 /// `watch_agent` dedupes by `agent_id`: two blocks registering the same
759 /// agent_id share one `WatchedAgent` entry. Removing that whole entry
760 /// unconditionally here (as this method used to) killed the shared
761 /// watcher — and with it, live tracking — for every OTHER still-open
762 /// block sharing that agent identity the moment any ONE of them
763 /// gracefully closed, since this is the primary, far-more-common
764 /// teardown path (`unwatch_block` only covers the crash/API-delete
765 /// backstop). See `WatchedAgent::parent_block_ids`'s doc comment and
766 /// docs/retro/retro-subagent-watcher-shared-dir-fanout-and-leak-2026-07-23.md.
767 ///
768 /// Without this, `watched_agents` was push-only: every distinct agent that
769 /// ever ran leaked one OS watch handle + channel + idle task for the rest of
770 /// the process lifetime, even after its pane/agent was deleted.
771 ///
772 /// Also prunes `sessions`, `dispatches`, and `pending_activity`: every
773 /// entry whose owner is this agent (`SubAgent`/`AgentDispatch`'s
774 /// `parent_agent`, `PendingDispatchActivity.parent_agent`), and any
775 /// session left with no subagents afterward. The parent agent is gone,
776 /// so nothing can query this data again — it was previously left as
777 /// plain data forever, growing these maps by one entry set per distinct
778 /// agent that ever ran a subagent. (`dispatches`/`pending_activity`
779 /// pruning added alongside `prune_block`'s block-scoped equivalent,
780 /// below — this method previously only pruned `sessions`, silently
781 /// leaking a Workflow-kind `DispatchState` for the agent's lifetime.)
782 pub fn unwatch_agent(&self, agent_id: &str, block_id: Option<&str>) {
783 if let Some(block_id) = block_id {
784 let mut watched = self.watched_agents.lock().unwrap();
785 for w in watched.iter_mut() {
786 if w.agent_id == agent_id {
787 w.parent_block_ids.remove(block_id);
788 }
789 }
790 let before = watched.len();
791 watched.retain(|w| !(w.agent_id == agent_id && w.parent_block_ids.is_empty()));
792 if watched.len() != before {
793 tracing::info!(agent = %agent_id, block_id = %block_id, "stopped watching subagent dir");
794 }
795 }
796
797 let mut sessions = self.sessions.lock().unwrap();
798 let mut pruned_subagents = 0usize;
799 sessions.retain(|_session_id, session| {
800 let before = session.subagents.len();
801 session
802 .subagents
803 .retain(|_agent_id, state| state.info.parent_agent != agent_id);
804 pruned_subagents += before - session.subagents.len();
805 !session.subagents.is_empty()
806 });
807 if pruned_subagents > 0 {
808 tracing::debug!(
809 agent = %agent_id,
810 pruned_subagents,
811 "pruned subagent session state for unwatched agent"
812 );
813 }
814 drop(sessions);
815
816 let mut dispatches = self.dispatches.lock().unwrap();
817 let before = dispatches.len();
818 dispatches.retain(|_, state| state.info.parent_agent != agent_id);
819 let pruned_dispatches = before - dispatches.len();
820 drop(dispatches);
821
822 let mut pending = self.pending_activity.lock().unwrap();
823 let before = pending.len();
824 pending.retain(|_, activity| activity.parent_agent != agent_id);
825 let pruned_pending = before - pending.len();
826 drop(pending);
827
828 if pruned_dispatches > 0 || pruned_pending > 0 {
829 tracing::debug!(
830 agent = %agent_id,
831 pruned_dispatches,
832 pruned_pending,
833 "pruned dispatch/pending-activity state for unwatched agent"
834 );
835 }
836 }
837
838 /// Prune every subagent, dispatch, and buffered activity entry owned by
839 /// `block_id` — the block-scoped counterpart of `unwatch_agent`'s
840 /// agent-scoped pruning, above. This is the robust backstop: it runs
841 /// from a `srv_events_tx` subscriber reacting to `Event::BlockDeleted`/
842 /// `TabDeleted`/`WorkspaceDeleted` (see `spawn_block_prune_subscriber`
843 /// below), independent of whether the frontend's normal
844 /// `/agentmux/reactive/unregister` teardown path (which drives
845 /// `unwatch_agent`) actually fires for this close — that path depends
846 /// on a live renderer's `TermWrap.dispose()` completing an async fetch,
847 /// which an API-driven delete, a tab/workspace cascade delete, or a
848 /// crash can all skip. Without this, closing an agent pane left its
849 /// Swarm-pane row (and any subagents/dispatches under it) visible
850 /// until the whole app/srv restarted — `ListActive`/`ListDispatches`
851 /// kept returning them forever, and the frontend's `buildTree()` has a
852 /// `parentIds` fallback (`swarm-model.ts`) that renders a row for any
853 /// block_id it still sees in the subagent list, with no complementary
854 /// removal path of its own.
855 ///
856 /// Block-scoped (not agent-name-scoped like `unwatch_agent`) so this
857 /// also correctly handles an agent identity reused across multiple
858 /// blocks over time — pruning by `parent_block_id` can never touch a
859 /// different, still-live block that happens to share an agent name.
860 ///
861 /// Also tears down this block's own filesystem watcher (`unwatch_block`,
862 /// below) — without this, `prune_block` only cleared the DERIVED
863 /// subagent/dispatch state at the moment it ran, while the underlying
864 /// `notify` watcher (and its dedicated tokio task, keyed by
865 /// `parent_block_id`) kept running indefinitely, silently re-creating
866 /// fresh entries for this closed block the next time any OTHER agent
867 /// sharing its watched directory wrote to its own subagent transcript
868 /// — see `session_belongs_to_block`'s doc comment and
869 /// docs/retro/retro-subagent-watcher-shared-dir-fanout-and-leak-2026-07-23.md.
870 ///
871 /// Returns whether any DERIVED state was actually pruned, so the caller
872 /// only broadcasts a refresh when there's something for clients to
873 /// refresh — independent of whether a watcher also got torn down.
874 pub fn prune_block(&self, block_id: &str) -> bool {
875 let mut pruned = false;
876
877 let mut sessions = self.sessions.lock().unwrap();
878 sessions.retain(|_session_id, session| {
879 let before = session.subagents.len();
880 session
881 .subagents
882 .retain(|_agent_id, state| state.info.parent_block_id != block_id);
883 if session.subagents.len() != before {
884 pruned = true;
885 }
886 !session.subagents.is_empty()
887 });
888 drop(sessions);
889
890 let mut dispatches = self.dispatches.lock().unwrap();
891 let before = dispatches.len();
892 dispatches.retain(|_, state| state.info.parent_block_id != block_id);
893 if dispatches.len() != before {
894 pruned = true;
895 }
896 drop(dispatches);
897
898 let mut pending = self.pending_activity.lock().unwrap();
899 let before = pending.len();
900 pending.retain(|_, activity| activity.parent_block_id != block_id);
901 if pending.len() != before {
902 pruned = true;
903 }
904 drop(pending);
905
906 // reagentx P2 (PR #2781, round 3): `backfill_generation` is keyed
907 // by `parent_block_id` (see its own doc comment) but was never
908 // pruned here like every other per-block map above — every
909 // distinct block_id that ever called `scan_session_subagents` left
910 // a permanent entry for the life of the srv process, even after
911 // the block was deleted. Not counted toward `pruned` below —
912 // that return value is specifically about DERIVED subagent/
913 // dispatch data clients might need to refresh over, not internal
914 // bookkeeping with no client-visible effect.
915 self.backfill_generation.lock().unwrap().remove(block_id);
916
917 self.unwatch_block(block_id);
918
919 if pruned {
920 tracing::debug!(block_id = %block_id, "pruned subagent/dispatch state for deleted block");
921 }
922 pruned
923 }
924
925 /// Remove `block_id` as a dependent of its watcher, tearing down the
926 /// underlying `notify` subscription (closing the debounce channel so the
927 /// associated processing task self-terminates on its next `rx.recv()`)
928 /// only once NO block depends on it anymore. Block-scoped, not
929 /// agent-name-scoped — mirrors `unwatch_agent`'s teardown mechanism, but
930 /// keyed by `parent_block_id`.
931 ///
932 /// `watch_agent` dedupes by `agent_id`: a second block registering an
933 /// already-watched agent_id adds itself to that entry's
934 /// `parent_block_ids` instead of getting its own watcher. Tearing down
935 /// the whole entry the moment ANY one dependent block closes would kill
936 /// live tracking for every other still-open block sharing that agent
937 /// identity — removing just this block_id from the set (and only
938 /// dropping the entry once the set is empty) keeps the watcher alive for
939 /// as long as any block still needs it. Idempotent — a no-op if
940 /// `block_id` isn't a dependent of any watcher.
941 fn unwatch_block(&self, block_id: &str) {
942 let mut watched = self.watched_agents.lock().unwrap();
943 for w in watched.iter_mut() {
944 w.parent_block_ids.remove(block_id);
945 }
946 let before = watched.len();
947 watched.retain(|w| !w.parent_block_ids.is_empty());
948 if watched.len() != before {
949 tracing::info!(block_id = %block_id, "stopped watching subagent dir: last dependent block closed");
950 }
951 }
952
953 fn broadcast_block_pruned(&self, block_id: &str) {
954 self.event_bus.broadcast_typed::<crate::backend::mps_events::SubagentBlockPruned>(&events::SubagentBlockPrunedEvent {
955 block_id: block_id.to_string(),
956 });
957 }
958
959 /// Prune `block_id` and broadcast `subagent:block_pruned` if anything
960 /// was actually removed — the combined operation `spawn_block_prune_
961 /// subscriber` calls per cascaded block_id.
962 pub fn prune_block_and_notify(&self, block_id: &str) {
963 if self.prune_block(block_id) {
964 self.broadcast_block_pruned(block_id);
965 }
966 }
967}