Skip to main content

agentmux_srv_core/backend/subagent_watcher/
jsonl.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The JSONL/journal file-change state machine: `process_jsonl_change` (the
5//! order of its steps, which live in `jsonl_change_steps.rs`) and
6//! its dispatch-membership/coalescing plumbing — `flush_pending_dispatch_
7//! activity`, `update_dispatch_membership`, `queue_dispatch_updated`,
8//! `process_journal_change`, `dispatch_entry`, `refresh_dispatch_info`,
9//! `refresh_dispatch_status`, `broadcast_dispatch_updated`.
10
11use std::collections::HashMap;
12use std::path::Path;
13
14use super::parse::*;
15use super::types::*;
16use super::SubagentWatcher;
17
18#[path = "jsonl_change_steps.rs"]
19pub mod steps;
20
21impl SubagentWatcher {
22    /// Process a changed/new JSONL subagent file. Reads new lines, updates state,
23    /// and broadcasts events via EventBus.
24    ///
25    /// `live`: `true` only when this call originates from the filesystem
26    /// watcher observing a real, in-the-moment change; `false` for a
27    /// cold-backfill replay (`scan_subagents_dir`, capped at
28    /// `BACKFILL_MAX_FILES`, run on pane reopen / srv restart). Eager
29    /// Haiku-naming (see `announce_spawn`) is gated on `live` —
30    /// without this, every restart of a long-lived session would re-fire a
31    /// naming call for every dispatch replayed from history, repeating the
32    /// broadcast-storm incident class in
33    /// docs/retro/retro-subagent-backfill-storm-oom-2026-07-17.md, just for
34    /// Haiku spend instead of WS events.
35    pub(super) fn process_jsonl_change(&self, parent_agent: &str, parent_block_id: &str, jsonl_path: &Path, live: bool) {
36        let Some(change) = steps::Change::of(parent_agent, parent_block_id, jsonl_path, live) else {
37            return;
38        };
39        let Some((new_events, new_offset, meta)) = self.read_new_lines(&change, jsonl_path) else {
40            return;
41        };
42        // Mutex released here — broadcast outside the lock
43        let (is_new, info_snapshot, completed) = match self.record_change(&change, jsonl_path, &new_events, new_offset, meta) {
44            steps::Recorded::Quiet { id_learned, name_learned } => {
45                self.announce_learned(&change, id_learned, name_learned);
46                return;
47            }
48            steps::Recorded::Changed { is_new, info_snapshot, completed, id_learned, name_learned } => {
49                self.announce_learned(&change, id_learned, name_learned);
50                (is_new, info_snapshot, completed)
51            }
52        };
53
54        if is_new {
55            self.announce_spawn(&change, &info_snapshot);
56        }
57        if !new_events.is_empty() {
58            self.announce_activity(&change, &new_events, &info_snapshot);
59        }
60        if completed {
61            self.announce_completion(&change, &info_snapshot);
62        }
63        self.announce_dispatch(&change, &info_snapshot, is_new, completed);
64    }
65
66    /// Flush every dispatch with buffered activity as one coalesced
67    /// `dispatch:activity` broadcast (SPEC §7). Called on
68    /// `DISPATCH_ACTIVITY_FLUSH_INTERVAL` by the background task
69    /// `spawn` starts. A quiet dispatch (nothing buffered) costs nothing —
70    /// the map only ever holds entries for dispatches with real pending
71    /// activity, drained on every flush.
72    pub(super) fn flush_pending_dispatch_activity(&self) {
73        let batch: HashMap<String, PendingDispatchActivity> = {
74            let mut pending = self.pending_activity.lock().unwrap();
75            std::mem::take(&mut *pending)
76        };
77        for (dispatch_id, pending) in batch {
78            for spawn in &pending.spawned {
79                self.broadcast_member_spawned(
80                    spawn,
81                    &pending.parent_agent,
82                    &pending.parent_block_id,
83                    &pending.session_id,
84                    &dispatch_id,
85                );
86            }
87
88            if !pending.members.is_empty() {
89                let new_events: usize = pending.members.iter().map(|(_, evs)| evs.len()).sum();
90                self.event_bus.broadcast_typed::<crate::backend::mps_events::DispatchActivity>(&super::events::DispatchActivityEvent {
91                    dispatch_id: dispatch_id.to_string(),
92                    parent_agent: pending.parent_agent.to_string(),
93                    parent_block_id: pending.parent_block_id.to_string(),
94                    session_id: pending.session_id.to_string(),
95                    new_events: new_events,
96                    members: pending.members.iter().map(|(agent_id, events)| super::events::DispatchMemberEvents { agent_id: agent_id.clone(), events: events.clone() }).collect(),
97                });
98            }
99
100            for done in &pending.completed {
101                self.broadcast_member_completed(
102                    done,
103                    &pending.parent_agent,
104                    &pending.parent_block_id,
105                    &pending.session_id,
106                    &dispatch_id,
107                );
108            }
109
110            if let Some(info) = &pending.latest_info {
111                self.broadcast_dispatch_updated(info);
112            }
113        }
114    }
115
116    /// Broadcast `subagent:spawned` for one member, immediately for a solo
117    /// dispatch or from the coalesced flush for a workflow member.
118    fn broadcast_member_spawned(
119        &self,
120        spawn: &PendingSpawn,
121        parent_agent: &str,
122        parent_block_id: &str,
123        session_id: &str,
124        dispatch_id: &str,
125    ) {
126        self.event_bus.broadcast_typed::<crate::backend::mps_events::SubagentSpawned>(&super::events::SubagentSpawnedEvent {
127            agent_id: spawn.agent_id.to_string(),
128            slug: spawn.slug.to_string(),
129            parent_agent: parent_agent.to_string(),
130            parent_block_id: parent_block_id.to_string(),
131            session_id: session_id.to_string(),
132            model: spawn.model.clone(),
133            dispatch_id: dispatch_id.to_string(),
134        });
135        tracing::info!(
136            agent_id = %spawn.agent_id,
137            slug = %spawn.slug,
138            parent = %parent_agent,
139            parent_block_id = %parent_block_id,
140            session_id = %session_id,
141            dispatch_id = %dispatch_id,
142            "subagent spawned"
143        );
144    }
145
146    /// Broadcast `subagent:completed` for one member, immediately for a solo
147    /// dispatch or from the coalesced flush for a workflow member.
148    fn broadcast_member_completed(
149        &self,
150        done: &PendingCompletion,
151        parent_agent: &str,
152        parent_block_id: &str,
153        session_id: &str,
154        dispatch_id: &str,
155    ) {
156        self.event_bus.broadcast_typed::<crate::backend::mps_events::SubagentCompleted>(&super::events::SubagentCompletedEvent {
157            agent_id: done.agent_id.to_string(),
158            parent_agent: Some(parent_agent.to_string()),
159            parent_block_id: parent_block_id.to_string(),
160            total_events: done.total_events,
161            dispatch_id: dispatch_id.to_string(),
162        });
163        tracing::info!(
164            agent_id = %done.agent_id,
165            total_events = done.total_events,
166            parent_block_id = %parent_block_id,
167            session_id = %session_id,
168            dispatch_id = %dispatch_id,
169            "subagent completed"
170        );
171    }
172
173    /// Fold a member subagent's lifecycle into its dispatch aggregate and
174    /// broadcast `dispatch:updated` — but only when membership actually
175    /// changed (a spawn or a completion). `process_jsonl_change` calls this
176    /// unconditionally for every workflow member, including plain
177    /// text/tool_use/tool_result activity ticks that carry neither flag; a
178    /// dispatch with several active members would otherwise broadcast a WS
179    /// event on every one of those ticks even though `memberCount`/
180    /// `membersDone` never moved. Mirrors the `has_new_records` gate in
181    /// `process_journal_change`.
182    fn update_dispatch_membership(
183        &self,
184        workflow_id: &str,
185        parent_agent: &str,
186        parent_block_id: &str,
187        session_id: &str,
188        member_spawned: bool,
189        member_completed: bool,
190    ) {
191        if !member_spawned && !member_completed {
192            return;
193        }
194
195        let info = {
196            let mut dispatches = self.dispatches.lock().unwrap();
197            let state = Self::dispatch_entry(
198                &mut dispatches,
199                workflow_id,
200                parent_agent,
201                parent_block_id,
202                session_id,
203            );
204            if member_spawned {
205                state.member_files += 1;
206            }
207            if member_completed {
208                state.members_completed += 1;
209            }
210            Self::refresh_dispatch_info(state);
211            state.info.clone()
212        };
213        self.queue_dispatch_updated(workflow_id, parent_agent, parent_block_id, session_id, info);
214    }
215
216    /// Queue an `AgentDispatch` snapshot for the next coalesced flush instead
217    /// of broadcasting `dispatch:updated` immediately — every caller here is
218    /// a Workflow-kind dispatch (Solo dispatches broadcast directly via
219    /// `broadcast_dispatch_updated`, see `process_jsonl_change`'s solo path).
220    fn queue_dispatch_updated(
221        &self,
222        dispatch_id: &str,
223        parent_agent: &str,
224        parent_block_id: &str,
225        session_id: &str,
226        info: AgentDispatch,
227    ) {
228        let mut pending = self.pending_activity.lock().unwrap();
229        let entry = pending
230            .entry(dispatch_id.to_string())
231            .or_insert_with(|| PendingDispatchActivity::new(parent_agent, parent_block_id, session_id));
232        entry.latest_info = Some(info);
233    }
234
235    /// Process a changed workflow journal (subagents/workflows/<wf>/journal.jsonl):
236    /// tally new `started`/`result` records and broadcast `dispatch:updated`.
237    pub(super) fn process_journal_change(
238        &self,
239        parent_agent: &str,
240        parent_block_id: &str,
241        journal_path: &Path,
242    ) {
243        let workflow_id = match parse_workflow_id(journal_path) {
244            Some(id) => id,
245            None => return,
246        };
247        let session_id = derive_session_id(journal_path);
248
249        // Read the current offset before locking (file I/O outside the lock).
250        let offset = {
251            let dispatches = self.dispatches.lock().unwrap();
252            dispatches
253                .get(&workflow_id)
254                .map(|w| w.journal_offset)
255                .unwrap_or(0)
256        };
257
258        let (started, results, new_offset) = match read_journal_counts(journal_path, offset) {
259            Ok(r) => r,
260            Err(e) => {
261                tracing::debug!(
262                    workflow_id = %workflow_id,
263                    error = %e,
264                    "failed to read workflow journal"
265                );
266                return;
267            }
268        };
269        // Nothing new landed (no complete lines since `offset`) — nothing to
270        // persist or broadcast.
271        if new_offset == offset {
272            return;
273        }
274
275        let has_new_records = started > 0 || results > 0;
276        let info = {
277            let mut dispatches = self.dispatches.lock().unwrap();
278            let state = Self::dispatch_entry(
279                &mut dispatches,
280                &workflow_id,
281                parent_agent,
282                parent_block_id,
283                &session_id,
284            );
285            // Always persist the advanced offset, even when the newly-read
286            // lines didn't contain a started/result record — otherwise those
287            // bytes get rescanned on every subsequent journal change until a
288            // matching record eventually appears elsewhere in the file.
289            state.journal_offset = new_offset;
290            if has_new_records {
291                state.journal_started += started;
292                state.journal_results += results;
293                Self::refresh_dispatch_info(state);
294            }
295            state.info.clone()
296        };
297        // Only queue when the counters actually moved — an offset-only
298        // advance (non-started/result lines) has no observable effect on
299        // AgentDispatch, so a broadcast would just be noise.
300        if has_new_records {
301            self.queue_dispatch_updated(&workflow_id, parent_agent, parent_block_id, &session_id, info);
302        }
303    }
304
305    fn dispatch_entry<'a>(
306        dispatches: &'a mut HashMap<String, DispatchState>,
307        workflow_id: &str,
308        parent_agent: &str,
309        parent_block_id: &str,
310        session_id: &str,
311    ) -> &'a mut DispatchState {
312        dispatches
313            .entry(workflow_id.to_string())
314            .or_insert_with(|| DispatchState {
315                info: AgentDispatch {
316                    dispatch_id: workflow_id.to_string(),
317                    kind: DispatchKind::Workflow,
318                    parent_agent: parent_agent.to_string(),
319                    parent_block_id: parent_block_id.to_string(),
320                    session_id: session_id.to_string(),
321                    member_count: 0,
322                    members_done: 0,
323                    status: DispatchStatus::Running,
324                    last_event_at: now_millis(),
325                    dispatch_name: None,
326                },
327                journal_offset: 0,
328                journal_started: 0,
329                journal_results: 0,
330                member_files: 0,
331                members_completed: 0,
332            })
333    }
334
335    /// Recompute public counters from raw journal/member counters. Either
336    /// source can lag the other (journal writes vs member file creation), so
337    /// take the max of each pair.
338    fn refresh_dispatch_info(state: &mut DispatchState) {
339        state.info.member_count = state.journal_started.max(state.member_files);
340        state.info.members_done = state.journal_results.max(state.members_completed);
341        state.info.last_event_at = now_millis();
342        // Called only in response to genuinely NEW member evidence (a spawn
343        // or a completion just landed) — always allowed to recompute, even
344        // overriding a prior Abandoned, mirroring the existing SubAgent-level
345        // precedent that a late-arriving Result always wins
346        // (`reconcile_stale_subagents_then_late_result_line_ends_completed_
347        // not_stuck_abandoned`). Codex P2 on PR #2677: an earlier version of
348        // this guard was unconditional (also applied here), permanently
349        // stranding a dispatch at Abandoned even once every member had
350        // actually finished. See `refresh_dispatch_status`'s own doc comment
351        // for why the READ-ONLY path (list_dispatches) still needs the guard.
352        Self::recompute_dispatch_status(state);
353    }
354
355    /// Counts-complete + 60s quiet ⇒ Completed. There is no timer: the flip
356    /// happens lazily at the next event or ListDispatches read. `started ==
357    /// results` alone is not terminal — it also holds between phases of a
358    /// still-running workflow, hence the quiet window.
359    pub(super) fn recompute_dispatch_status(state: &mut DispatchState) {
360        let counts_complete = state.info.member_count > 0
361            && state.info.members_done >= state.info.member_count;
362        let quiet = now_millis().saturating_sub(state.info.last_event_at) > 60_000;
363        state.info.status = if counts_complete && quiet {
364            DispatchStatus::Completed
365        } else {
366            DispatchStatus::Running
367        };
368    }
369
370    /// Read-only variant for `list_dispatches()` — `Abandoned` is terminal
371    /// and never recomputed here, since this call has no new evidence
372    /// (unlike `refresh_dispatch_info`'s call to `recompute_dispatch_status`
373    /// above, triggered by a genuinely new member event). `reconcile_stale_
374    /// subagents` is the ONLY writer of `Abandoned`
375    /// (SPEC_SWARM_DISPATCH_ATTRIBUTION_AND_LIFECYCLE_2026_08_19.md §3.2),
376    /// and `list_dispatches()` calls this on every single read (not just on
377    /// new events) — without this guard, the very next `ListDispatches` RPC
378    /// after a reconciliation pass would silently overwrite Abandoned back
379    /// to Running/Completed based on counts alone, discarding the
380    /// reconciliation before any client ever observed it.
381    pub(super) fn refresh_dispatch_status(state: &mut DispatchState) {
382        if state.info.status == DispatchStatus::Abandoned {
383            return;
384        }
385        Self::recompute_dispatch_status(state);
386    }
387
388    /// `subagent:named`: the subagent's display name is set (from the parent's
389    /// description, or by Haiku). The dock and the Swarm patch their row from it.
390    pub(super) fn broadcast_subagent_named(&self, agent_id: &str, display_name: &str) {
391        self.event_bus.broadcast_typed::<crate::backend::mps_events::SubagentNamed>(&super::events::SubagentNamedEvent {
392            agent_id: agent_id.to_string(),
393            display_name: display_name.to_string(),
394        });
395    }
396
397    /// A known subagent's fields changed without a new spawn — today, only its
398    /// `tool_use_id` arriving late from the sidecar. Swarm reloads the list on
399    /// it so the subagent's background tasks move under its row. Deliberately
400    /// NOT a re-sent `subagent:spawned`: the dock's sources add rows on that.
401    pub(super) fn broadcast_subagent_updated(&self, agent_id: &str, parent_block_id: &str) {
402        self.event_bus.broadcast_typed::<crate::backend::mps_events::SubagentUpdated>(&super::events::SubagentUpdatedEvent {
403            agent_id: agent_id.to_string(),
404            parent_block_id: parent_block_id.to_string(),
405        });
406    }
407
408    pub(super) fn broadcast_dispatch_updated(&self, info: &AgentDispatch) {
409        self.event_bus.broadcast_typed::<crate::backend::mps_events::DispatchUpdated>(&super::events::DispatchUpdatedEvent {
410            dispatch_id: info.dispatch_id.to_string(),
411            kind: info.kind.clone(),
412            parent_agent: info.parent_agent.to_string(),
413            parent_block_id: info.parent_block_id.to_string(),
414            session_id: info.session_id.to_string(),
415            member_count: info.member_count,
416            members_done: info.members_done,
417            status: info.status.clone(),
418            dispatch_name: info.dispatch_name.clone(),
419        });
420    }
421}
422
423#[cfg(test)]
424#[path = "jsonl_change_tests.rs"]
425mod change_tests;