Skip to main content

agentmux_srv_core/backend/subagent_watcher/
reconcile_steps.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The steps of `reconcile_stale_subagents_impl` (scan.rs), one function each:
5//! the idle gate, resolving what each `Active` member became, applying that under
6//! the `sessions` lock, announcing it, and propagating it to Workflow dispatches.
7//!
8//! Lock order: `sessions` and `dispatches` are never held at the same time, and
9//! neither is held across file IO or a broadcast.
10
11use std::collections::HashMap;
12use std::path::PathBuf;
13
14use super::completion;
15use super::types::*;
16use super::SubagentWatcher;
17
18/// What one reconcile pass changed, for the announce and dispatch steps.
19pub(super) struct Reconciled {
20    /// Members that went `Active` -> `Abandoned`.
21    pub(super) abandoned_ids: Vec<String>,
22    /// Members that went `Active` -> `Completed`: (agent_id, dispatch_id, event_count).
23    pub(super) completed: Vec<(String, String, usize)>,
24    /// Every member of this block, by dispatch, after the pass (not just the changed ones).
25    pub(super) statuses_by_dispatch: HashMap<String, Vec<SubAgentStatus>>,
26}
27
28impl SubagentWatcher {
29    /// True when the parent's turn is confirmed idle and the pass should go on. Otherwise
30    /// it has said why not (and queued the retry, when one is due) and the pass is over.
31    pub(super) fn parent_turn_is_confirmed_idle(
32        &self,
33        parent_block_id: &str,
34        session_id: &str,
35        retries_remaining: u32,
36    ) -> bool {
37        let turn_active = crate::backend::blockcontroller::get_block_controller_status(parent_block_id)
38            .map(|s| s.turn_active);
39        match turn_active {
40            Some(true) => {
41                tracing::info!(
42                    parent_block_id = %parent_block_id,
43                    session_id = %session_id,
44                    "reconcile_stale_subagents: parent turn active — nothing to reconcile"
45                );
46                false
47            }
48            // The pane was closed: its controller left the registry on
49            // purpose and will never register again. Retrying (~15s of
50            // "not yet registered" lines after every mid-turn close) would
51            // only chase a block that's gone.
52            None if self.parent_block_closed(parent_block_id) => {
53                tracing::debug!(
54                    parent_block_id = %parent_block_id,
55                    session_id = %session_id,
56                    "reconcile_stale_subagents: parent block closed — nothing to reconcile"
57                );
58                false
59            }
60            None if retries_remaining > 0 => {
61                tracing::info!(
62                    parent_block_id = %parent_block_id,
63                    session_id = %session_id,
64                    retries_remaining,
65                    "reconcile_stale_subagents: controller not yet registered — retrying, not giving up silently"
66                );
67                self.retry_reconcile_once(parent_block_id, session_id, retries_remaining - 1);
68                false
69            }
70            None => {
71                tracing::info!(
72                    parent_block_id = %parent_block_id,
73                    session_id = %session_id,
74                    "reconcile_stale_subagents: controller still not registered after all retries — giving up (bounded)"
75                );
76                false
77            }
78            Some(false) => true, // confirmed idle — proceed
79        }
80    }
81
82    /// What each of this block's still-`Active` members became: `Completed` when the
83    /// PARENT recorded a `tool_result` for its `tool_use_id`, else `Abandoned`.
84    ///
85    /// AgentMux transcripts carry no `"type":"result"` line, so a missing one proves
86    /// nothing (`completion.rs`, docs/reports/REPORT_SUBAGENT_COMPLETION_NEVER_DETECTED_2026_09_05.md).
87    /// Resolved before taking the `sessions` lock and in two phases, because a parent
88    /// transcript is routinely tens of MB: read the candidates under a short lock, do the
89    /// file IO unlocked, apply afterwards (which re-checks `Active`).
90    pub(super) fn resolve_active_members(
91        &self,
92        parent_block_id: &str,
93        session_id: &str,
94    ) -> HashMap<String, SubAgentStatus> {
95        let candidates: Vec<(String, PathBuf)> = {
96            let sessions = self.sessions.lock().unwrap();
97            sessions
98                .get(session_id)
99                .map(|session| {
100                    session
101                        .subagents
102                        .values()
103                        .filter(|s| {
104                            s.info.parent_block_id == parent_block_id
105                                && s.info.status == SubAgentStatus::Active
106                        })
107                        .map(|s| {
108                            (s.info.agent_id.clone(), PathBuf::from(&s.info.jsonl_path))
109                        })
110                        .collect()
111                })
112                .unwrap_or_default()
113        };
114        // Each candidate resolves its OWN parent transcript, with reads cached per
115        // distinct path: Workflow-tool members sit one level deeper
116        // (`subagents/workflows/<run-id>/`), and `candidates` comes from a HashMap in no
117        // fixed order, so sharing one member's resolution would abandon Solo members
118        // non-deterministically (#3007).
119        let mut results_by_parent: HashMap<PathBuf, HashMap<String, bool>> = HashMap::new();
120        candidates
121            .into_iter()
122            .map(|(agent_id, path)| {
123                let status = match completion::parent_transcript_for(&path) {
124                    Some(parent) => {
125                        let results = results_by_parent
126                            .entry(parent.clone())
127                            .or_insert_with(|| completion::parent_tool_results_at(&parent));
128                        let tool_use_id = completion::tool_use_id_for(&path);
129                        completion::terminal_status(tool_use_id.as_deref(), results)
130                    }
131                    // No `subagents` ancestor — unrecognised layout.
132                    // Fall back to the historical inference.
133                    None => SubAgentStatus::Abandoned,
134                };
135                (agent_id, status)
136            })
137            .collect()
138    }
139
140    /// Write the resolved statuses onto this block's `Active` members, under the
141    /// `sessions` lock. `None` when the session is not tracked.
142    ///
143    /// A session's subagent map can hold entries from a DIFFERENT block (the watcher
144    /// dedupes by agent_id alone), and only this one `parent_block_id` was read as idle,
145    /// so a sibling block's subagent is left alone (#2131).
146    pub(super) fn apply_resolved_statuses(
147        &self,
148        parent_block_id: &str,
149        session_id: &str,
150        resolved_statuses: &HashMap<String, SubAgentStatus>,
151    ) -> Option<Reconciled> {
152        let mut sessions = self.sessions.lock().unwrap();
153        let session = sessions.get_mut(session_id)?;
154        let mut reconciled_agent_ids = Vec::new();
155        let mut completed_members: Vec<(String, String, usize)> = Vec::new();
156        let mut member_statuses_by_dispatch: HashMap<String, Vec<SubAgentStatus>> =
157            std::collections::HashMap::new();
158        for state in session.subagents.values_mut() {
159            if state.info.parent_block_id != parent_block_id {
160                continue;
161            }
162            if state.info.status == SubAgentStatus::Active {
163                // Absent a resolution (no sidecar, unreadable parent, an
164                // entry that appeared after the snapshot above) fall back
165                // to the historical `Abandoned` — never optimistically
166                // complete something we could not correlate.
167                let resolved = resolved_statuses
168                    .get(&state.info.agent_id)
169                    .cloned()
170                    .unwrap_or(SubAgentStatus::Abandoned);
171                state.info.status = resolved.clone();
172                state.release_events_if_finished();
173                if resolved == SubAgentStatus::Completed {
174                    tracing::info!(
175                        agent_id = %state.info.agent_id,
176                        parent_block_id = %parent_block_id,
177                        session_id = %session_id,
178                        dispatch_id = %state.info.dispatch_id,
179                        "subagent reconciled: active -> completed (parent recorded a tool_result)"
180                    );
181                    completed_members.push((
182                        state.info.agent_id.clone(),
183                        state.info.dispatch_id.clone(),
184                        state.info.event_count,
185                    ));
186                    member_statuses_by_dispatch
187                        .entry(state.info.dispatch_id.clone())
188                        .or_default()
189                        .push(state.info.status.clone());
190                    continue;
191                }
192                reconciled_agent_ids.push(state.info.agent_id.clone());
193                // Every field a NAME-based grouping/dedup bug needs to
194                // reconstruct offline: which subagent, which dispatch,
195                // which display_name it had already resolved (grouping is
196                // keyed on this), and which block/session it's bound to.
197                tracing::info!(
198                    agent_id = %state.info.agent_id,
199                    parent_block_id = %parent_block_id,
200                    session_id = %session_id,
201                    dispatch_id = %state.info.dispatch_id,
202                    display_name = ?state.info.display_name,
203                    slug = %state.info.slug,
204                    "subagent reconciled: active -> abandoned (parent turn ended)"
205                );
206            }
207            member_statuses_by_dispatch
208                .entry(state.info.dispatch_id.clone())
209                .or_default()
210                .push(state.info.status.clone());
211        }
212        Some(Reconciled {
213            abandoned_ids: reconciled_agent_ids,
214            completed: completed_members,
215            statuses_by_dispatch: member_statuses_by_dispatch,
216        })
217    }
218
219    /// Push the corrections the same way the abandoned ones are pushed — an
220    /// already-open Swarm pane otherwise keeps showing these as running until some
221    /// unrelated reload happens to refresh it.
222    pub(super) fn announce_reconciled(&self, parent_block_id: &str, session_id: &str, reconciled: &Reconciled) {
223        for (agent_id, dispatch_id, total_events) in &reconciled.completed {
224            self.broadcast_subagent_completed(
225                parent_block_id,
226                agent_id,
227                dispatch_id,
228                *total_events,
229            );
230        }
231        if !reconciled.abandoned_ids.is_empty() {
232            tracing::info!(
233                parent_block_id = %parent_block_id,
234                session_id = %session_id,
235                reconciled = reconciled.abandoned_ids.len(),
236                "reconcile_stale_subagents: pass complete"
237            );
238            self.broadcast_subagents_abandoned(parent_block_id, &reconciled.abandoned_ids);
239        }
240    }
241
242    /// Propagate to the owning Workflow-kind `AgentDispatch` aggregate — a Solo dispatch
243    /// needs no step (its status is synthesized from its one member's status).
244    /// SPEC_SWARM_DISPATCH_ATTRIBUTION_AND_LIFECYCLE_2026_08_19.md §3.2: Abandoned iff
245    /// every member is Completed|Abandoned and at least one is Abandoned — otherwise the
246    /// counts-based Running/Completed status (`refresh_dispatch_status`) is left alone.
247    pub(super) fn abandon_finished_dispatches(
248        &self,
249        parent_block_id: &str,
250        session_id: &str,
251        member_statuses_by_dispatch: &HashMap<String, Vec<SubAgentStatus>>,
252    ) {
253        let abandoned_dispatch_infos: Vec<AgentDispatch> = {
254            let mut dispatches = self.dispatches.lock().unwrap();
255            let mut updated = Vec::new();
256            for (dispatch_id, statuses) in member_statuses_by_dispatch {
257                if dispatch_id.starts_with("solo:") {
258                    continue;
259                }
260                let Some(state) = dispatches.get_mut(dispatch_id) else { continue };
261                // `statuses` only covers members visible in `session.subagents`; one whose
262                // JSONL the filesystem watcher has not picked up yet (notify/debounce lag)
263                // is missing, so `all_done` could hold for an INCOMPLETE set. Trust it only
264                // once every member the dispatch itself counts has a status. Skipping is
265                // safe (the next pass rechecks); abandoning early is not (#2677).
266                if statuses.len() < state.info.member_count {
267                    continue;
268                }
269                let all_done = statuses
270                    .iter()
271                    .all(|s| matches!(s, SubAgentStatus::Completed | SubAgentStatus::Abandoned));
272                let any_abandoned = statuses.iter().any(|s| *s == SubAgentStatus::Abandoned);
273                if !(all_done && any_abandoned) {
274                    continue;
275                }
276                if state.info.status != DispatchStatus::Abandoned {
277                    state.info.status = DispatchStatus::Abandoned;
278                    tracing::info!(
279                        dispatch_id = %dispatch_id,
280                        parent_block_id = %parent_block_id,
281                        session_id = %session_id,
282                        member_count = statuses.len(),
283                        "dispatch reconciled: -> abandoned (all members done, at least one abandoned)"
284                    );
285                    updated.push(state.info.clone());
286                }
287            }
288            updated
289        };
290        for info in &abandoned_dispatch_infos {
291            self.broadcast_dispatch_updated(info);
292        }
293    }
294}