Skip to main content

agentmux_srv_core/backend/subagent_watcher/
scan.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Session/directory backfill scanning and stale-subagent reconciliation:
5//! `scan_session_subagents` (pane-reopen backfill entry point),
6//! `reconcile_stale_subagents` (Active -> Abandoned correction once a
7//! parent's turn is confirmed idle), `broadcast_subagents_abandoned`, and
8//! `scan_subagents_dir` (the capped cold-backfill file walk).
9
10use std::collections::HashMap;
11use std::path::{Path, PathBuf};
12
13use super::completion;
14use super::parse::file_mtime;
15use super::types::*;
16use super::SubagentWatcher;
17
18/// How many times `reconcile_stale_subagents` retries when the parent
19/// block's controller isn't registered yet, before giving up and leaving
20/// the entries as-is. See that function's own doc comment (2026-09-02
21/// update) for why a single 2s attempt proved too short in practice —
22/// `MAX_RECONCILE_RETRIES * RECONCILE_RETRY_INTERVAL_MS` (~15s) is a
23/// realistic bound for a real controller to finish spawning under load,
24/// while still failing open rather than chasing a block forever.
25const MAX_RECONCILE_RETRIES: u32 = 5;
26const RECONCILE_RETRY_INTERVAL_MS: u64 = 3_000;
27
28/// Publish a `mps::EVENT_SUBAGENT_BACKFILL_STATUS` ping, scoped to this
29/// pane's own block id. No-op if `self.broker` was never wired (tests, or a
30/// `SubagentWatcher` built via bare `new()`) -- see the `broker` field's own
31/// doc comment in `mod.rs`. See
32/// docs/retro/retro-activity-dock-flicker-survives-debounce-fix-2026-08-24.md
33/// section 5.
34fn publish_backfill_status(watcher: &SubagentWatcher, parent_block_id: &str, status: &str) {
35    let Some(broker) = watcher.broker.lock().unwrap().clone() else { return };
36    broker.publish_event::<crate::backend::mps_events::SubagentBackfillStatus>(
37        &super::events::SubagentBackfillStatusEvent { status: status.to_string() },
38        vec![format!("block:{}", parent_block_id)],
39        2,
40    );
41}
42
43impl SubagentWatcher {
44    /// Backfill subagents that already existed before this pane (re)opened,
45    /// scoped to exactly the ONE session being resumed — not this agent
46    /// identity's entire history. Called from `handle_reactive_register`
47    /// when the block being registered already has a persisted
48    /// `agent:sessionid` (i.e. it's resuming a prior conversation, not
49    /// starting fresh); a brand-new session has nothing to backfill.
50    ///
51    /// Searches only the top level of `config_dir/projects/*` for a child
52    /// directory literally named `session_id` (the nested-per-session
53    /// layout observed in practice: `projects/<ws>/<session-uuid>/subagents/`)
54    /// — cheap, since an agent identity typically has few distinct project
55    /// dirs. Older/flat-layout installs where `subagents/` sits directly
56    /// under the project dir with no session-level folder have no way to
57    /// isolate one session's subagents from another's at the filesystem
58    /// level; in that case this intentionally finds nothing rather than
59    /// falling back to scanning everything.
60    pub fn scan_session_subagents(
61        &self,
62        parent_agent: &str,
63        parent_block_id: &str,
64        config_dir: &Path,
65        session_id: &str,
66    ) {
67        // "started"/"done" wrap the whole call, regardless of which of
68        // `scan_session_subagents_inner`'s several return paths is actually
69        // taken (nothing found at all, or found-and-processed) -- see
70        // `publish_backfill_status`'s own doc comment. A pane whose block
71        // has no persisted session id never calls this at all (see the
72        // caller in `server/reactive.rs`), so it never sees either status
73        // and its `ready()` gate is unaffected by this signal.
74        //
75        // reagentx P2 (PR #2781): generation-gated "done" -- see
76        // `backfill_generation`'s own doc comment in `mod.rs`. "started" is
77        // always published unconditionally; a stale/superseded call's own
78        // "started" is harmless (the gate just stays closed either way).
79        let my_generation = {
80            let mut gens = self.backfill_generation.lock().unwrap();
81            let next = gens.get(parent_block_id).copied().unwrap_or(0) + 1;
82            gens.insert(parent_block_id.to_string(), next);
83            next
84        };
85        publish_backfill_status(self, parent_block_id, "started");
86        self.scan_session_subagents_inner(parent_agent, parent_block_id, config_dir, session_id);
87        if self.is_backfill_generation_current(parent_block_id, my_generation) {
88            publish_backfill_status(self, parent_block_id, "done");
89        }
90    }
91
92    /// Whether `generation` (captured at the start of one
93    /// `scan_session_subagents` call) is still the most recent generation
94    /// recorded for `parent_block_id` — i.e. no NEWER overlapping call has
95    /// started since. See `backfill_generation`'s own doc comment in
96    /// `mod.rs`.
97    pub(super) fn is_backfill_generation_current(&self, parent_block_id: &str, generation: u64) -> bool {
98        self.backfill_generation.lock().unwrap().get(parent_block_id).copied() == Some(generation)
99    }
100
101    fn scan_session_subagents_inner(
102        &self,
103        parent_agent: &str,
104        parent_block_id: &str,
105        config_dir: &Path,
106        session_id: &str,
107    ) {
108        let projects_dir = config_dir.join("projects");
109        let Ok(walker) = std::fs::read_dir(&projects_dir) else { return };
110
111        for entry in walker.flatten() {
112            let session_dir = entry.path().join(session_id);
113            let subagents_dir = session_dir.join("subagents");
114            if subagents_dir.is_dir() {
115                // Correlates a pane (re)open with the session it's backfilling —
116                // needed to tell "this session was backfilled once" apart from
117                // "this session was backfilled repeatedly under different
118                // parent_block_ids" (a subagent's parent_block_id is fixed at
119                // first discovery, see process_jsonl_change; a mismatch here is
120                // the mechanism a NAME/grouping-dedup bug would leave a trail in).
121                //
122                // reagent (PR #2143 round 1): info!, not debug! — the default
123                // production EnvFilter (crates/srv/src/main.rs, "agentmuxsrv=
124                // info,info") drops debug-level lines unless RUST_LOG=debug is
125                // already set, which would make this diagnostic invisible in a
126                // normally-running srv, defeating the point of adding it.
127                tracing::info!(
128                    agent = %parent_agent,
129                    parent_block_id = %parent_block_id,
130                    session_id = %session_id,
131                    dir = %subagents_dir.display(),
132                    "backfilling session subagents on pane (re)open"
133                );
134                self.scan_subagents_dir(parent_agent, parent_block_id, &subagents_dir);
135                self.reconcile_stale_subagents(parent_block_id, session_id);
136                return; // session ids are unique — no need to keep scanning
137            }
138        }
139    }
140
141    /// After a full session backfill scan, downgrade any subagent that's
142    /// still `Active` to `Abandoned` if its parent block's turn is not
143    /// currently active. A subagent runs inside its parent's own CLI
144    /// process — a Task-tool call is synchronous within the parent's turn —
145    /// so once the parent's turn has ended, any subagent file lacking a
146    /// terminal `Result` line was interrupted (crashed, killed, or the
147    /// app/srv restarted mid-task), not still running. This call site is
148    /// reached from `scan_session_subagents`, itself only invoked when a
149    /// block re-registers with a pre-existing session id (`reactive.rs`) —
150    /// i.e. a freshly-spawned controller whose turn genuinely hasn't
151    /// started yet, so every subagent found on disk predates this process
152    /// and is unambiguously history, not in-flight.
153    ///
154    /// Only reconciles on a *confirmed-idle* read (`Some(false)`).
155    /// `Some(true)` (confirmed active) skips with no follow-up — correct,
156    /// nothing to reconcile. `None` ("no controller registered yet") used
157    /// to be folded into the same "assume active, don't touch it" bucket as
158    /// confirmed-active, permanently — a previously-flagged, unconfirmed
159    /// race (`SPEC_SUBAGENT_LIVE_RECONCILIATION_AND_RETIRE_2026_07_20.md`
160    /// §5 Open Question 2) where this call site, reached from
161    /// `scan_session_subagents` at pane-reopen backfill time, can run
162    /// before the freshly-spawned controller has registered in
163    /// `CONTROLLER_REGISTRY`. Left unresolved, an entry hitting that race
164    /// stayed `Active`-looking forever, since nothing else ever revisits it
165    /// (see `SPEC_SWARM_DISPATCH_ATTRIBUTION_AND_LIFECYCLE_2026_08_19.md`
166    /// §2, mechanism 4). Fixed by treating `None` as "retry, don't give up
167    /// silently" (`retry_reconcile_once`) instead of a terminal no-op —
168    /// still conservative (a genuine `Some(true)` never retries; only the
169    /// ambiguous case does, and only up to `MAX_RECONCILE_RETRIES` times).
170    ///
171    /// 2026-09-02 (docs/retro/retro-activitydock-appears-on-agent-pane-load-2026-09-02.md):
172    /// the original version of this fix allowed exactly ONE 2s retry before
173    /// giving up permanently. Confirmed live on a real agent whose CLI
174    /// controller never registered at all (an expired provider login — the
175    /// process either never spawns or spawns and exits before reaching
176    /// `register_controller`): the single 2s retry window is frequently too
177    /// short to distinguish "controller is still starting up, wait" from
178    /// "controller is never coming" — for the FORMER case this left the
179    /// pane's Activity Dock showing genuinely-dead subagents as `Active`
180    /// indefinitely (no live turn-end ever fires to retry later either),
181    /// and for the LATTER case a couple of seconds is too optimistic a
182    /// bound for how long a real controller can legitimately take to spawn
183    /// and register under load. Extended to a bounded retry loop
184    /// (`MAX_RECONCILE_RETRIES` attempts, `RECONCILE_RETRY_INTERVAL_MS`
185    /// apart) — still fails open in bounded time (~`MAX_RECONCILE_RETRIES *
186    /// RECONCILE_RETRY_INTERVAL_MS`), just with a realistic window instead
187    /// of a single throw-away check.
188    ///
189    /// Called from two places as of SPEC_SUBAGENT_LIVE_RECONCILIATION_AND_
190    /// RETIRE_2026_07_20 Phase A: `scan_session_subagents` (reopen/backfill,
191    /// unchanged) and `blockcontroller::persistent`'s turn-end hook (live —
192    /// closes docs/specs/SPEC_SUBAGENT_LIFECYCLE_RECONCILIATION_2026_07_12.md
193    /// Open Question 1, which deliberately deferred real-time wiring).
194    /// `pub(crate)` so the live call site (a different module) can reach it.
195    /// Thin entry point — always starts the retry budget at
196    /// `MAX_RECONCILE_RETRIES`.
197    pub(crate) fn reconcile_stale_subagents(&self, parent_block_id: &str, session_id: &str) {
198        self.reconcile_stale_subagents_impl(parent_block_id, session_id, MAX_RECONCILE_RETRIES);
199    }
200
201    // pub(super), not private — `tests.rs` (a sibling module, not a
202    // descendant of `scan`) needs to call this directly with
203    // `retries_remaining: 0` to test the exhausted-retry path without
204    // depending on a real spawned watcher's tokio::spawn actually firing.
205    pub(super) fn reconcile_stale_subagents_impl(&self, parent_block_id: &str, session_id: &str, retries_remaining: u32) {
206        if !self.parent_turn_is_confirmed_idle(parent_block_id, session_id, retries_remaining) {
207            return;
208        }
209        let resolved = self.resolve_active_members(parent_block_id, session_id);
210        let Some(reconciled) = self.apply_resolved_statuses(parent_block_id, session_id, &resolved) else { return };
211        self.announce_reconciled(parent_block_id, session_id, &reconciled);
212        self.abandon_finished_dispatches(parent_block_id, session_id, &reconciled.statuses_by_dispatch);
213    }
214
215    /// Bounded retry for `reconcile_stale_subagents`'s `None`
216    /// (controller-not-yet-registered) case — see that function's doc
217    /// comment for why a single 2s attempt was too short in practice.
218    /// `retries_remaining` counts DOWN — the loop terminates because each
219    /// hop passes a strictly smaller budget, never because of a separate
220    /// flag; a block whose controller genuinely never registers (e.g. it
221    /// was deleted, or its provider login never resolves) still gets a
222    /// bounded, not unbounded, chase.
223    ///
224    /// Mirrors `trigger_eager_naming`'s `self_ref` upgrade-to-`Arc` pattern
225    /// for spawning a task that outlives this sync call; silently no-ops
226    /// for a bare `new()` watcher (most unit tests), same "untracked ->
227    /// safe no-op" convention as that method.
228    /// The parent block is mid-close, or no longer exists — either way no
229    /// controller for it will ever register again. A failed store read is
230    /// "unknown", not "closed", so it keeps the bounded retry.
231    /// SPEC_AGENT_PANE_CLOSE_GRACEFUL_SHUTDOWN_2026_09_18.md (graceful close
232    /// removes the controller before the block record).
233    pub(super) fn parent_block_closed(&self, parent_block_id: &str) -> bool {
234        crate::backend::blockcontroller::is_closing(parent_block_id)
235            || matches!(self.mstore.get::<crate::backend::obj::Block>(parent_block_id), Ok(None))
236    }
237
238    pub(super) fn retry_reconcile_once(&self, parent_block_id: &str, session_id: &str, retries_remaining: u32) {
239        let Some(watcher) = self.self_ref.lock().unwrap().as_ref().and_then(|w| w.upgrade()) else {
240            return;
241        };
242        let parent_block_id = parent_block_id.to_string();
243        let session_id = session_id.to_string();
244        tokio::spawn(async move {
245            tokio::time::sleep(std::time::Duration::from_millis(RECONCILE_RETRY_INTERVAL_MS)).await;
246            watcher.reconcile_stale_subagents_impl(&parent_block_id, &session_id, retries_remaining);
247        });
248    }
249
250    /// One batched broadcast per reconciliation pass (not one per
251    /// subagent) — a pass can reconcile many subagents at once (e.g. a
252    /// workflow with dozens of members whose parent turn just ended), and
253    /// the frontend only needs "something changed, reload" (`swarm-model.ts`'s
254    /// `scheduleLoadSubagents`), not per-agent granularity. Mirrors the
255    /// batch-not-spam precedent `dispatch:activity` already established in
256    /// this file for the same reason.
257    ///
258    /// The frontend `muxEventSubscribe({ eventType: "subagent:abandoned",
259    /// ... })` listener lands in the immediately-following PR (Phase B,
260    /// #2235 — SPEC_SUBAGENT_LIVE_RECONCILIATION_AND_RETIRE_2026_07_20),
261    /// not this one. Broadcasting with no subscriber yet is inert, not
262    /// harmful: this PR's actual goal (subagents resolving to `Completed`/
263    /// `Abandoned` correctly in the backend, live, not just at reopen) is
264    /// already fully achieved without it — the missing piece until #2235
265    /// merges is only "push the correction to an already-open Swarm pane
266    /// immediately" (an already-open pane still picks up the correction on
267    /// its next unrelated reload in the meantime).
268    pub(super) fn broadcast_subagents_abandoned(&self, parent_block_id: &str, agent_ids: &[String]) {
269        self.event_bus.broadcast_typed::<crate::backend::mps_events::SubagentAbandoned>(&super::events::SubagentAbandonedEvent {
270            parent_block_id: parent_block_id.to_string(),
271            agent_ids: agent_ids.to_vec(),
272        });
273    }
274
275    /// The `Completed` counterpart to `broadcast_subagents_abandoned` above,
276    /// for members reconciliation resolved as having actually returned (see
277    /// `completion.rs`). Emits the same `subagent:completed` event `jsonl.rs`
278    /// already sends when it observes a completion live, so a client needs no
279    /// new handling for the reconcile path — it just stops being told
280    /// "abandoned" for dispatches that returned.
281    ///
282    /// Per-agent rather than batched, unlike its `Abandoned` sibling: the
283    /// payload carries per-member fields (`totalEvents`, `dispatchId`) that a
284    /// batched shape has nowhere to put, and matching `jsonl.rs`'s existing
285    /// event exactly is worth more here than saving a broadcast — a reconcile
286    /// pass typically resolves a handful of completions, not the dozens the
287    /// batching rationale above was written for.
288    ///
289    /// `parentAgent` is omitted (the live emitter includes it): reconcile is
290    /// keyed on the block, and no consumer reads that field.
291    pub(super) fn broadcast_subagent_completed(
292        &self,
293        parent_block_id: &str,
294        agent_id: &str,
295        dispatch_id: &str,
296        total_events: usize,
297    ) {
298        self.event_bus.broadcast_typed::<crate::backend::mps_events::SubagentCompleted>(&super::events::SubagentCompletedEvent {
299            agent_id: agent_id.to_string(),
300            parent_agent: None,
301            parent_block_id: parent_block_id.to_string(),
302            total_events: total_events,
303            dispatch_id: dispatch_id.to_string(),
304        });
305    }
306
307    /// Process agent-*.jsonl directly in `dir`, plus workflow runs under
308    /// `dir/workflows/<wf>/` (member agent files + journal).
309    ///
310    /// A pane's `subagents/` directory accumulates forever — every Task-tool
311    /// and Workflow-tool run this session has ever made leaves its
312    /// `agent-*.jsonl` files behind. Because `is_new` (`process_jsonl_change`)
313    /// is keyed off the in-memory `sessions` map, which starts empty on every
314    /// srv process (restart or fresh start), an unbounded scan here replays
315    /// the session's ENTIRE history — full-file read + parse + WS broadcast
316    /// per file — on every pane reopen or srv restart. On a heavily-used pane
317    /// this is a genuine crash trigger, not just wasted work: a live incident
318    /// (see docs/retro/retro-subagent-backfill-storm-oom-2026-07-17.md) hit
319    /// 1,000+ replayed files across three back-to-back srv restarts in under
320    /// 10 seconds, on a machine already near its commit ceiling — the
321    /// resulting allocation/broadcast storm is a plausible contributor to
322    /// each restart re-crashing before the launcher's 3-strikes budget gave
323    /// up and killed the whole app.
324    ///
325    /// Bound the replay to the `BACKFILL_MAX_FILES` most-recently-modified
326    /// agent files (by mtime) — recent activity is what the Swarm pane's
327    /// reopen backfill exists to show; a months-old workflow run replaying on
328    /// every restart serves no one. Skipped files are still on disk and
329    /// still show up via `list_active`'s normal file-count telemetry if
330    /// something later reads them directly — this only bounds the *push*
331    /// (broadcast) side of a cold backfill.
332    fn scan_subagents_dir(&self, parent_agent: &str, parent_block_id: &str, dir: &Path) {
333        let mut candidates: Vec<(std::time::SystemTime, PathBuf)> = Vec::new();
334
335        if let Ok(files) = std::fs::read_dir(dir) {
336            for file in files.flatten() {
337                let path = file.path();
338                if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
339                    if name.starts_with("agent-") && name.ends_with(".jsonl") {
340                        candidates.push((file_mtime(&path), path));
341                    }
342                }
343            }
344        }
345
346        let workflows_dir = dir.join("workflows");
347        let mut journals: Vec<PathBuf> = Vec::new();
348        if let Ok(runs) = std::fs::read_dir(&workflows_dir) {
349            for run in runs.flatten() {
350                if let Ok(files) = std::fs::read_dir(run.path()) {
351                    for file in files.flatten() {
352                        let path = file.path();
353                        match path.file_name().and_then(|n| n.to_str()) {
354                            Some(name)
355                                if name.starts_with("agent-") && name.ends_with(".jsonl") =>
356                            {
357                                candidates.push((file_mtime(&path), path));
358                            }
359                            // Journals are one small file per run (not one per
360                            // member agent) — always process them so
361                            // `workflow:updated`/run status stay accurate
362                            // regardless of the member-file cap below.
363                            Some("journal.jsonl") => journals.push(path),
364                            _ => {}
365                        }
366                    }
367                }
368            }
369        }
370
371        let total = candidates.len();
372        candidates.sort_by(|a, b| b.0.cmp(&a.0)); // newest mtime first
373        let skipped = total.saturating_sub(BACKFILL_MAX_FILES);
374        if skipped > 0 {
375            tracing::info!(
376                agent = %parent_agent,
377                parent_block_id = %parent_block_id,
378                dir = %dir.display(),
379                total,
380                skipped,
381                cap = BACKFILL_MAX_FILES,
382                "scan_subagents_dir: capping cold-backfill replay to the most recent files"
383            );
384        }
385        for (_, path) in candidates.into_iter().take(BACKFILL_MAX_FILES) {
386            // live=false: this is a cold-backfill replay (pane reopen / srv
387            // restart), not a genuinely-live spawn — must never trigger eager
388            // Haiku naming (see process_jsonl_change's `live` param doc).
389            self.process_jsonl_change(parent_agent, parent_block_id, &path, false);
390        }
391        for path in journals {
392            self.process_journal_change(parent_agent, parent_block_id, &path);
393        }
394    }
395}