Skip to main content

agentmux_srv_core/backend/reactive/
progress_watcher.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Pushed per-agent **progress**: the agent's current todo checklist and the
5//! tool it is running right now, published as an `agent:progress` MuxEvent so
6//! the Swarm pane can list them under the agent's name.
7//!
8//! Sibling of [`super::activity_watcher`], and deliberately a separate loop:
9//! that one spends a Haiku call per agent to write an English one-liner and is
10//! throttled accordingly. This one only reads NEW bytes of a block's `output`
11//! file and parses JSON, so it costs nothing per tick and can run far more
12//! often — which is the point, since a checklist that lags 20s behind the agent
13//! is worse than no checklist.
14//!
15//! Why the backend and not the frontend: `agent-document-store` already holds
16//! every tool call, but only for panes that are currently MOUNTED. The Swarm
17//! pane's whole value is seeing agents you are not looking at, so the data has
18//! to come from the same place the shell/cron/summary rows come from.
19//!
20//! **Why state is carried across ticks** (reagent P1 on PR #2952): the
21//! checklist cannot be rebuilt from a fixed tail window. `TodoWrite`-style
22//! calls are immune — one call carries the whole list — but the vocabulary
23//! AgentMux actually ships against (`TaskCreate`/`TaskUpdate`) describes ONE
24//! item per call, so reconstructing the list needs every still-open task's
25//! original `TaskCreate` to be inside the window. A verbose `Bash` or a large
26//! `Read` pushes those out within seconds, and the task would then vanish from
27//! the checklist while still open, silently. So each block keeps an accumulated
28//! [`BlockState`] and each tick only consumes the bytes appended since the last
29//! one.
30
31use std::collections::HashMap;
32use std::sync::Arc;
33use std::time::Duration;
34
35use tokio::time::interval;
36
37use crate::backend::blockcontroller::{get_block_controller_status, STATUS_RUNNING};
38use crate::backend::storage::filestore::FileStore;
39use crate::backend::storage::store::Store;
40use crate::backend::transcript::source::TranscriptSource;
41use crate::backend::mps::Broker;
42use crate::backend::work_facts::overlap_notes::{NewEdit, NewPr};
43
44use super::get_global_handler;
45
46/// How often to sweep registered agents. Much tighter than the summary loop's
47/// 20s: this is an incremental read + JSON parse, with no model call to bill.
48const SWEEP_INTERVAL_SECS: u64 = 3;
49
50/// Most bytes consumed in one tick, and the most read when first catching up on
51/// a block. A block seen from its first byte is exact; one that already had
52/// more than this when we first saw it (srv restarted mid-session) is seeded
53/// from its tail and flagged — see [`BlockState::partial`].
54const MAX_READ_BYTES: i64 = 4 * 1024 * 1024;
55
56/// Cap on rows published per agent, so one pathological checklist can't flood
57/// the Swarm tree. Truncation is reported rather than silent — see
58/// [`AgentProgress::todos_truncated`].
59const MAX_TODOS: usize = 24;
60
61/// Bound on remembered in-flight tool calls. Real concurrency is a handful; a
62/// larger number means results are being missed, and the oldest entries are the
63/// ones least likely to still be running.
64const MAX_OPEN_TOOLS: usize = 32;
65
66pub const EVENT_AGENT_PROGRESS: &str = "agent:progress";
67
68/// Republish an unchanged payload every N ticks (~15s at a 3s sweep).
69///
70/// The change-suppression below is what keeps this loop quiet, but on its own
71/// it strands a LATE subscriber (codex P1 on PR #2952): open the Swarm after an
72/// agent's checklist has settled and there is no further change to deliver, so
73/// the pane shows nothing indefinitely for a perfectly active agent. The event
74/// is also published with `persist: 1` so the broker replays the latest one to
75/// a freshly-subscribed route; this periodic republish is the belt to that
76/// suspenders, and covers any subscriber the replay path does not.
77const REPUBLISH_EVERY_TICKS: u64 = 5;
78
79/// Tool names whose **call arguments** carry checklist state.
80///
81/// Deliberately a list rather than the single `TodoWrite` everyone expects:
82/// Claude Code 2.1.177 — the version AgentMux ships against today — advertises
83/// `TaskCreate`/`TaskUpdate` and no `TodoWrite` at all, and other providers
84/// differ again. Matching by a known set plus the `Todo` substring below means
85/// a version bump that renames the tool degrades to "no rows" rather than to
86/// wrong rows.
87///
88/// READ-style tools (`TaskList`, `TodoRead`) are deliberately absent. Their
89/// task data lives in the tool RESULT, not the call's `input`, and this parser
90/// only reads `input` — so listing them would advertise support that silently
91/// contributes nothing (reagent P2 on PR #2952). Supporting them means parsing
92/// tool_result payloads, which is its own change.
93const TODO_TOOL_NAMES: &[&str] = &["TodoWrite", "TaskCreate", "TaskUpdate"];
94
95#[path = "progress_codex_plan.rs"]
96pub mod codex_plan;
97use codex_plan::codex_plan;
98
99fn is_todo_tool(name: &str) -> bool {
100    TODO_TOOL_NAMES.contains(&name) || name.contains("Todo")
101}
102
103/// Tools whose input names a file the agent is changing. Their paths become
104/// the agent's recent files, which `backend::work_facts` compares across
105/// agents (docs/specs/SPEC_AGENT_OVERLAP_AWARENESS_2026_10_10.md §3.1).
106const FILE_EDIT_TOOL_NAMES: &[&str] = &["Edit", "Write", "MultiEdit", "NotebookEdit"];
107
108/// A tool that runs a shell command (Claude's `Bash`, a provider's `shell`,
109/// AgentMux's own `Terminal`), by name.
110fn is_shell_tool(name: &str) -> bool {
111    let lower = name.to_ascii_lowercase();
112    lower.contains("bash") || lower.ends_with("shell") || lower.ends_with("terminal")
113}
114
115/// Whether a shell command opens a PR: `gh-agent pr create` or `gh pr create`,
116/// anywhere in it (`cd x && gh-agent pr create --title …`, or inside a quoted
117/// shell call like Codex's `pwsh -Command 'gh-agent pr create …'`), the
118/// program named by its path or with `.cmd`/`.exe` too.
119#[cfg(test)]
120fn is_pr_create(command: &str) -> bool {
121    pr_create(command).is_some()
122}
123
124/// The PR being opened in a shell command (see [`is_pr_create`]), with the
125/// `--head` and `--base` it names, if any. Flags may sit between the words
126/// (`gh --repo o/r pr create`, `gh pr -R o/r create`); the command ends at a
127/// shell separator.
128fn pr_create(command: &str) -> Option<NewPrCommand> {
129    let clean = |w: &str| w.trim_matches(|c| matches!(c, '"' | '\'' | '(' | ')' | ';')).to_string();
130    let raw: Vec<&str> = command.split_whitespace().collect();
131    for (i, first) in raw.iter().enumerate() {
132        let word = clean(first);
133        let program = word.rsplit(['/', '\\']).next().unwrap_or(&word);
134        let program = program.trim_end_matches(".cmd").trim_end_matches(".exe");
135        if !matches!(program, "gh" | "gh-agent") {
136            continue;
137        }
138        let mut rest: Vec<String> = Vec::new();
139        for w in &raw[i + 1..] {
140            if matches!(*w, "&&" | "||" | "|" | ";") {
141                break;
142            }
143            rest.push(clean(w));
144            if w.ends_with(';') {
145                break;
146            }
147        }
148        // `pr create`, skipping flags (`-R`/`--repo` take a value).
149        let (mut k, mut words) = (0, Vec::new());
150        while k < rest.len() && words.len() < 2 {
151            match rest[k].as_str() {
152                "-R" | "--repo" => k += 2,
153                w if w.starts_with('-') => k += 1,
154                w => {
155                    words.push(w.to_string());
156                    k += 1;
157                }
158            }
159        }
160        if words != ["pr", "create"] {
161            continue;
162        }
163        let mut pr = NewPrCommand::default();
164        while k < rest.len() {
165            let w = rest[k].as_str();
166            let next = || rest.get(k + 1).cloned();
167            match w {
168                "-H" | "--head" => {
169                    pr.head = next();
170                    k += 2;
171                    continue;
172                }
173                "-B" | "--base" => {
174                    pr.base = next();
175                    k += 2;
176                    continue;
177                }
178                _ => {}
179            }
180            if let Some(v) = w.strip_prefix("--head=") {
181                pr.head = Some(v.to_string());
182            } else if let Some(v) = w.strip_prefix("--base=") {
183                pr.base = Some(v.to_string());
184            }
185            k += 1;
186        }
187        return Some(pr);
188    }
189    None
190}
191
192/// The head and base a PR-create command names (`--head`, `--base`).
193#[derive(Debug, Clone, Default, PartialEq, Eq)]
194struct NewPrCommand {
195    head: Option<String>,
196    base: Option<String>,
197}
198
199/// PR creations kept per sweep, at most.
200const MAX_NEW_PRS: usize = 4;
201
202/// Most recent files kept per block, distinct paths, newest first.
203pub const MAX_RECENT_FILES: usize = 50;
204
205/// One file an agent changed, as its tool call named it.
206#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
207pub struct RecentFile {
208    /// The path exactly as the tool input wrote it (usually absolute).
209    pub path: String,
210    pub tool: String,
211    /// When the call was made: the transcript line's own `timestamp`, else
212    /// the moment this watcher read it live. A line without a timestamp read
213    /// as backlog (see [`apply_lines`]) is not recorded at all, so a block
214    /// first seen mid-session never reads as "edited just now".
215    pub ts_ms: u64,
216}
217
218/// A transcript line's own time, when it carries one (`timestamp`, RFC 3339
219/// or Unix ms, as Claude's session lines do).
220fn line_timestamp(v: &serde_json::Value) -> Option<u64> {
221    let ts = v.get("timestamp")?;
222    if let Some(n) = ts.as_u64() {
223        return Some(n);
224    }
225    chrono::DateTime::parse_from_rfc3339(ts.as_str()?)
226        .ok()
227        .and_then(|dt| u64::try_from(dt.timestamp_millis()).ok())
228}
229
230/// What the watcher currently knows about one block, for readers outside
231/// the sweep loop.
232#[derive(Debug, Clone, Default)]
233pub struct WatchedWork {
234    pub progress: AgentProgress,
235    pub recent_files: Vec<RecentFile>,
236}
237
238/// The latest [`WatchedWork`] per block id, replaced after every sweep.
239fn snapshot() -> &'static parking_lot::RwLock<HashMap<String, WatchedWork>> {
240    static SNAPSHOT: std::sync::LazyLock<parking_lot::RwLock<HashMap<String, WatchedWork>>> =
241        std::sync::LazyLock::new(Default::default);
242    &SNAPSHOT
243}
244
245/// Read access to the watcher's state for one block: its checklist, current
246/// tool and recent files. `None` until the watcher has swept it once.
247pub fn watched_work(block_id: &str) -> Option<WatchedWork> {
248    snapshot().read().get(block_id).cloned()
249}
250
251/// Record that `path` was just changed by `tool`: moved to the front if it
252/// was already listed, and the list kept to [`MAX_RECENT_FILES`].
253fn note_recent_file(files: &mut Vec<RecentFile>, path: &str, tool: &str, ts_ms: u64) {
254    files.retain(|f| f.path != path);
255    files.insert(0, RecentFile { path: path.to_string(), tool: tool.to_string(), ts_ms });
256    files.truncate(MAX_RECENT_FILES);
257}
258
259/// One checklist entry as the Swarm renders it.
260#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ts_rs::TS)]
261#[ts(export, export_to = "../../../frontend/types/rpc/")]
262pub struct TodoItem {
263    pub text: String,
264    /// `pending` | `in_progress` | `completed`. Passed through as the provider
265    /// wrote it where possible; unknown values are kept verbatim rather than
266    /// coerced, so a new provider status shows up as itself instead of
267    /// silently becoming "pending".
268    pub status: String,
269}
270
271/// What we currently believe about one agent.
272#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
273pub struct AgentProgress {
274    pub todos: Vec<TodoItem>,
275    /// How many rows [`MAX_TODOS`] dropped, so the UI can say "+N more"
276    /// instead of quietly showing a partial list as if it were the whole one.
277    pub todos_truncated: usize,
278    /// True when this block was first seen mid-stream, so item-at-a-time
279    /// (`TaskCreate`) calls from before that point were never observed and the
280    /// checklist may be missing entries. Distinct from `todos_truncated`,
281    /// which is a cap we chose; this is history we could not see.
282    pub todos_partial: bool,
283    /// The tool this agent is running right now — the oldest `tool_use` with no
284    /// matching `tool_result` yet. `None` when the agent is between tools.
285    pub current_tool: Option<String>,
286}
287
288impl AgentProgress {
289    /// Nothing worth publishing — avoids a MuxEvent per tick per idle agent.
290    fn is_empty(&self) -> bool {
291        self.todos.is_empty() && self.current_tool.is_none()
292    }
293}
294
295/// Everything we accumulate for one block across ticks.
296#[derive(Debug, Default)]
297struct BlockState {
298    /// Byte offset of the next unread line in the block's `output`.
299    next_offset: i64,
300    /// Item-at-a-time accumulation (`TaskCreate`/`TaskUpdate`), keyed so an
301    /// update revises its own row. Insertion order is the agent's own creation
302    /// order, the only ordering it ever expressed.
303    tasks: Vec<(String, TodoItem)>,
304    /// Last whole-list call. Supersedes `tasks` outright when present, because
305    /// that is the tool's own replace-everything semantics.
306    list: Option<Vec<TodoItem>>,
307    /// In-flight `tool_use` calls, oldest first.
308    open: Vec<(String, String)>,
309    /// See [`AgentProgress::todos_partial`].
310    partial: bool,
311    /// Files named by edit tools, newest first (see [`note_recent_file`]).
312    recent_files: Vec<RecentFile>,
313    /// Edits read live since the sweep last took them, oldest first: what
314    /// the overlap notes check (`work_facts::overlap_notes`).
315    new_edits: Vec<RecentFile>,
316    /// PRs it started opening, read live since the sweep last took them: what
317    /// the PR overlap note checks (`work_facts::overlap_notes::on_new_prs`).
318    new_prs: Vec<NewPrCommand>,
319    /// This block's output has been looked at before.
320    seen: bool,
321    /// `next_offset` counts bytes of the agent's zone, not of the block's own
322    /// copy. The offsets of the two differ, so a change of source starts over.
323    global: bool,
324}
325
326impl BlockState {
327    fn progress(&self) -> AgentProgress {
328        let mut todos = self
329            .list
330            .clone()
331            .unwrap_or_else(|| self.tasks.iter().map(|(_, i)| i.clone()).collect());
332        let todos_truncated = todos.len().saturating_sub(MAX_TODOS);
333        todos.truncate(MAX_TODOS);
334        AgentProgress {
335            todos,
336            todos_truncated,
337            // A whole-list call is self-contained, so once one has been seen
338            // the checklist is complete regardless of what we missed earlier.
339            todos_partial: self.partial && self.list.is_none(),
340            current_tool: self.open.first().map(|(_, name)| name.clone()),
341        }
342    }
343}
344
345/// Fold newly-appended transcript lines into `state`.
346///
347/// Pure w.r.t. I/O so it can be unit-tested against real transcript shapes
348/// without a FileStore. Called once per tick with only the lines appended since
349/// the previous call — never the whole file.
350///
351/// A recent file takes its line's own timestamp. Without one it takes
352/// `live_now_ms`: the read time when these lines were just written, `None`
353/// when they are backlog read on first sight of the block (srv restarted, or
354/// the block predates the watcher), whose read time says nothing about when
355/// the edit happened. Such an edit is not recorded.
356fn apply_lines(state: &mut BlockState, lines: &[&str], live_now_ms: Option<u64>) {
357    for line in lines {
358        let Ok(v) = serde_json::from_str::<serde_json::Value>(line) else {
359            continue;
360        };
361
362        // Resolve finished calls first: a tool_use and its result never share a
363        // line, so ordering within the line is not a concern.
364        for id in tool_result_ids(&v) {
365            state.open.retain(|(open_id, _)| *open_id != id);
366        }
367
368        // Codex reports a shell command as an `item.started` event of type
369        // `command_execution`, not a `tool_use`.
370        if v.get("type").and_then(|t| t.as_str()) == Some("item.started") {
371            let item = v.get("item");
372            let is_command = item.and_then(|i| i.get("type")).and_then(|t| t.as_str()) == Some("command_execution");
373            let command = item.and_then(|i| i.get("command")).and_then(|c| c.as_str());
374            if let Some(pr) = command.filter(|_| is_command).and_then(pr_create) {
375                if live_now_ms.is_some() && state.new_prs.len() < MAX_NEW_PRS {
376                    state.new_prs.push(pr);
377                }
378            }
379        }
380
381        // Codex's plan: a whole list each time (`todo_list` items in `codex exec`
382        // events, `plan_update`, or an `update_plan` call), so it replaces the
383        // checklist like TodoWrite does (Kanban §6.12).
384        if let Some(items) = codex_plan(&v) {
385            state.list = Some(items);
386            state.tasks.clear();
387            continue;
388        }
389
390        for frame in tool_frames(&v) {
391            if frame.get("type").and_then(|t| t.as_str()) != Some("tool_use") {
392                continue;
393            }
394            let Some(name) = frame_tool_name(frame) else { continue };
395            if let Some(id) = frame_tool_id(frame) {
396                state.open.push((id.to_string(), name.to_string()));
397                // Drop the oldest if we're clearly missing results, rather than
398                // letting this grow for the life of the block.
399                if state.open.len() > MAX_OPEN_TOOLS {
400                    state.open.remove(0);
401                }
402            }
403
404            if is_shell_tool(name) {
405                let opens = frame_input(frame).and_then(|i| first_string(i, &["command", "cmd"])).and_then(|c| pr_create(&c));
406                if let Some(pr) = opens {
407                    if live_now_ms.is_some() && state.new_prs.len() < MAX_NEW_PRS {
408                        state.new_prs.push(pr);
409                    }
410                }
411                continue;
412            }
413
414            if FILE_EDIT_TOOL_NAMES.contains(&name) {
415                if let Some(path) = frame_input(frame)
416                    .and_then(|i| first_string(i, &["file_path", "notebook_path"]))
417                {
418                    if let Some(ts) = line_timestamp(&v).or(live_now_ms) {
419                        note_recent_file(&mut state.recent_files, &path, name, ts);
420                        // Backlog is history, not something the agent is
421                        // doing now: only live edits are checked for overlap.
422                        if live_now_ms.is_some() && state.new_edits.len() < MAX_RECENT_FILES {
423                            state.new_edits.push(RecentFile { path, tool: name.to_string(), ts_ms: ts });
424                        }
425                    }
426                }
427                continue;
428            }
429
430            if !is_todo_tool(name) {
431                continue;
432            }
433            let Some(input) = frame_input(frame) else { continue };
434
435            if let Some(items) = parse_todo_array(input) {
436                state.list = Some(items);
437                state.tasks.clear();
438                continue;
439            }
440            // A whole-list call, once seen, owns the checklist — an
441            // item-at-a-time call after it would be describing a different
442            // vocabulary than the one currently in force.
443            if state.list.is_none() {
444                merge_single_task(&mut state.tasks, input, name);
445            }
446        }
447    }
448}
449
450/// Every frame in a transcript line that could be a tool call or result.
451///
452/// Covers two genuinely different provider shapes (codex P2 on PR #2952):
453///   * Claude stream-json — blocks inside `message.content` (or a bare
454///     top-level `content` array).
455///   * Gemini and friends — the LINE ITSELF is the frame:
456///     `{"type":"tool_use","tool_name":…,"tool_id":…,"parameters":{…}}`
457///     (see `frontend/app/view/agent/providers/gemini-translator.ts`).
458///
459/// Without the second, every non-Claude agent silently showed no in-flight
460/// tool and no todos at all, since the array lookup just yielded nothing.
461fn tool_frames(v: &serde_json::Value) -> Vec<&serde_json::Value> {
462    let mut frames: Vec<&serde_json::Value> = v
463        .get("message")
464        .and_then(|m| m.get("content"))
465        .or_else(|| v.get("content"))
466        .and_then(|c| c.as_array())
467        .map(|a| a.iter().collect())
468        .unwrap_or_default();
469    // A bare frame is only a frame if it declares one of the two types we
470    // care about — otherwise every ordinary line would look like one.
471    if matches!(v.get("type").and_then(|t| t.as_str()), Some("tool_use") | Some("tool_result")) {
472        frames.push(v);
473    }
474    frames
475}
476
477/// Tool name under either vocabulary (`name` for Claude, `tool_name` for
478/// Gemini-shaped frames).
479fn frame_tool_name(frame: &serde_json::Value) -> Option<&str> {
480    frame
481        .get("name")
482        .or_else(|| frame.get("tool_name"))
483        .and_then(|n| n.as_str())
484}
485
486/// Call id under either vocabulary.
487fn frame_tool_id(frame: &serde_json::Value) -> Option<&str> {
488    frame
489        .get("id")
490        .or_else(|| frame.get("tool_id"))
491        .and_then(|i| i.as_str())
492}
493
494/// Call arguments under either vocabulary.
495fn frame_input(frame: &serde_json::Value) -> Option<&serde_json::Value> {
496    frame.get("input").or_else(|| frame.get("parameters"))
497}
498
499fn tool_result_ids(v: &serde_json::Value) -> Vec<String> {
500    let mut ids = Vec::new();
501    if let Some(id) = v.get("tool_use_id").and_then(|i| i.as_str()) {
502        ids.push(id.to_string());
503    }
504    for frame in tool_frames(v) {
505        if frame.get("type").and_then(|t| t.as_str()) != Some("tool_result") {
506            continue;
507        }
508        // `tool_use_id` (Claude) or `tool_id` (Gemini) — a result names the
509        // call it belongs to under whichever key its provider uses.
510        if let Some(id) = frame
511            .get("tool_use_id")
512            .or_else(|| frame.get("tool_id"))
513            .and_then(|i| i.as_str())
514        {
515            ids.push(id.to_string());
516        }
517    }
518    ids
519}
520
521/// `input.todos` (or `input.items`) as a whole checklist.
522fn parse_todo_array(input: &serde_json::Value) -> Option<Vec<TodoItem>> {
523    let arr = input
524        .get("todos")
525        .or_else(|| input.get("items"))
526        .and_then(|t| t.as_array())?;
527    // An empty array is a real state ("checklist cleared"), so return it as
528    // such rather than falling through to the single-item path.
529    Some(arr.iter().filter_map(parse_todo_entry).collect())
530}
531
532fn parse_todo_entry(entry: &serde_json::Value) -> Option<TodoItem> {
533    let text = first_string(entry, &["content", "title", "text", "step", "activeForm", "description"])?;
534    let status = first_string(entry, &["status", "state"]).unwrap_or_else(|| "pending".to_string());
535    Some(TodoItem { text, status })
536}
537
538/// Fold a Task-style call describing a SINGLE item into the accumulated rows.
539///
540/// Keyed by whatever id the tool uses so a later call revises the same row,
541/// falling back to the text for tools that hand back no id.
542///
543/// Fields are merged, not replaced (codex P1 on PR #2952). A `TaskUpdate`
544/// legitimately carries only `task_id` + the changed `status` — it has no
545/// reason to resend text that did not change. Requiring a complete item meant
546/// such a call parsed to nothing and the row sat at `pending` forever, which is
547/// precisely the case a checklist exists to show moving.
548/// Does this tool name describe CREATING an item, as opposed to revising one?
549///
550/// Only consulted for calls that carry no id (reagent P2 on PR #2952). With an
551/// id the key is unambiguous; without one, text is the only identity available,
552/// and keying on it alone silently collapses two genuinely distinct in-flight
553/// tasks that happen to share a title. Two visible duplicate rows are a much
554/// smaller harm than one invisibly missing row, so an idless CREATE always
555/// appends and only an idless UPDATE matches by text.
556fn is_create_call(tool_name: &str) -> bool {
557    tool_name.contains("Create") || tool_name.contains("Add") || tool_name.contains("New")
558}
559
560fn merge_single_task(items: &mut Vec<(String, TodoItem)>, input: &serde_json::Value, tool_name: &str) {
561    let text = first_string(input, &["content", "title", "text", "activeForm", "description"]);
562    let status = first_string(input, &["status", "state"]);
563    let id = first_string(input, &["task_id", "taskId", "id"]);
564
565    // An idless create is its own row, always — see `is_create_call`.
566    if id.is_none() && is_create_call(tool_name) {
567        let Some(text) = text else { return };
568        items.push((
569            // Unique so no later call can match it by key; an idless tool
570            // gives us nothing to correlate a future update against anyway.
571            format!("{}#{}", text, items.len()),
572            TodoItem { text, status: status.unwrap_or_else(|| "pending".to_string()) },
573        ));
574        return;
575    }
576
577    // Find the row this call refers to. An id matches the key it was stored
578    // under; an idless update has only its text, and must compare against each
579    // row's TEXT rather than its key — a row created WITH an id is keyed by
580    // that id, so a key comparison would miss it and append a duplicate.
581    let existing = match &id {
582        Some(id) => items.iter_mut().find(|(k, _)| k == id),
583        None => match &text {
584            Some(text) => items.iter_mut().find(|(_, item)| item.text == *text),
585            None => None,
586        },
587    };
588    if let Some(slot) = existing {
589        if let Some(text) = text {
590            slot.1.text = text;
591        }
592        if let Some(status) = status {
593            slot.1.status = status;
594        }
595        return;
596    }
597
598    let Some(key) = id.or_else(|| text.clone()) else {
599        // Neither an id nor any text — nothing identifies a row to touch.
600        return;
601    };
602
603    // Creating a row still needs something to display; an update for a task we
604    // never saw created (seeded mid-stream) has no text to show.
605    let Some(text) = text else { return };
606    items.push((key, TodoItem { text, status: status.unwrap_or_else(|| "pending".to_string()) }));
607}
608
609fn first_string(v: &serde_json::Value, keys: &[&str]) -> Option<String> {
610    keys.iter()
611        .find_map(|k| v.get(*k).and_then(|s| s.as_str()))
612        .map(|s| s.trim().to_string())
613        .filter(|s| !s.is_empty())
614}
615
616/// Consume whatever has been appended to this block's `output` since the last
617/// tick, folding it into `state`.
618///
619/// Returns false when there was nothing to do, so the caller can skip the rest
620/// of the work for this block.
621fn consume_new_output(source: &TranscriptSource<'_>, state: &mut BlockState) -> bool {
622    let size = match source.stat() {
623        Some((size, _)) => size,
624        None => 0,
625    };
626    // The cursor counts bytes of one copy. When the copy it reads from changes
627    // (the agent's zone got its first line), start over rather than mix offsets.
628    if state.seen && state.global != source.global {
629        *state = BlockState::default();
630    }
631    state.global = source.global;
632    // Whatever is already there the first time this block is looked at is
633    // backlog; only what appears after that was written live (see
634    // `apply_lines` on stamping recent files).
635    let first_sight = !state.seen;
636    state.seen = true;
637    if size <= 0 {
638        return false;
639    }
640
641    // The file shrank — a new session reusing the block, or a truncation. Our
642    // accumulated state describes a transcript that no longer exists, so start
643    // over rather than mixing two conversations' checklists.
644    if size < state.next_offset {
645        *state = BlockState { seen: true, global: source.global, ..BlockState::default() };
646    }
647
648    if state.next_offset == 0 && size > MAX_READ_BYTES {
649        // First sight of a block that is already long (srv restarted
650        // mid-session). Seed from the tail and admit the list may be missing
651        // item-at-a-time entries from before this point.
652        state.next_offset = size - MAX_READ_BYTES;
653        state.partial = true;
654    }
655
656    let available = size - state.next_offset;
657    if available <= 0 {
658        return false;
659    }
660    let want = available.min(MAX_READ_BYTES);
661    let Some(bytes) = source.read_range(state.next_offset, want) else {
662        return false;
663    };
664    if bytes.is_empty() {
665        return false;
666    }
667
668    // Only consume up to the last complete line: a read boundary lands
669    // anywhere, and half a JSON object would be dropped as malformed and then
670    // never seen again in its complete form.
671    let consumed = match bytes.iter().rposition(|b| *b == b'\n') {
672        Some(idx) => idx + 1,
673        // No newline anywhere in the chunk — an unterminated line longer than
674        // the read. Skip it wholesale rather than stalling forever on it.
675        None if want == MAX_READ_BYTES => bytes.len(),
676        None => return false,
677    };
678    state.next_offset += consumed as i64;
679
680    let text = String::from_utf8_lossy(&bytes[..consumed]);
681    let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
682    if lines.is_empty() {
683        return false;
684    }
685    let live_now_ms = (!first_sight).then(agentmux_common::time::now_ms_u64);
686    apply_lines(state, &lines, live_now_ms);
687    true
688}
689
690/// Run the progress sweep loop. Never returns.
691/// One block's worth of work decided by a sweep — what to publish, if anything.
692struct SweepOutcome {
693    agent_id: String,
694    block_id: String,
695    progress: AgentProgress,
696}
697
698/// One sweep's result: the states back, what to publish, and the edits and
699/// PRs the overlap notes check.
700type Swept = (HashMap<String, BlockState>, Vec<SweepOutcome>, (Vec<NewEdit>, Vec<NewPr>));
701
702/// The whole file-reading half of a sweep, run OFF the async runtime.
703///
704/// `FileStore::stat`/`read_at` are synchronous, mutex-guarded SQLite reads, and
705/// this loop runs them for every live agent at a 3s cadence (reagent P2 on PR
706/// #2952). Doing that inline would park a Tokio worker thread on disk I/O
707/// several times a second — tolerable at `activity_watcher`'s 20s, much less so
708/// here. `states` is moved in and back out rather than shared behind a lock:
709/// only this loop ever touches it, and one owner is simpler than one mutex.
710fn sweep_blocking(
711    filestore: &FileStore,
712    mstore: &Store,
713    agents: Vec<(String, String)>,
714    mut states: HashMap<String, BlockState>,
715    last_published: &HashMap<String, AgentProgress>,
716    force_republish: bool,
717) -> Swept {
718    let mut out = Vec::new();
719    let mut edits = Vec::new();
720    let mut prs = Vec::new();
721
722    for (agent_id, block_id) in agents {
723        // Same gate as the summary loop: an idle or non-agent pane has no
724        // progress to report and shouldn't be read every tick.
725        let Some(status) = get_block_controller_status(&block_id) else { continue };
726        if status.shellprocstatus != STATUS_RUNNING || !status.is_agent_pane {
727            continue;
728        }
729
730        let state = states.entry(block_id.clone()).or_default();
731        // The agent's zone for a defined agent, the block's own copy otherwise.
732        let source = TranscriptSource::resolve(filestore, mstore, &block_id);
733        let had_new = consume_new_output(&source, state);
734        edits.extend(state.new_edits.drain(..).map(|f| NewEdit {
735            agent_id: agent_id.clone(),
736            block_id: block_id.clone(),
737            path: f.path,
738        }));
739        prs.extend(state.new_prs.drain(..).map(|p| NewPr {
740            agent_id: agent_id.clone(),
741            block_id: block_id.clone(),
742            head: p.head,
743            base: p.base,
744        }));
745        let progress = state.progress();
746
747        // Nothing new AND nothing already published for this block — an agent
748        // that has never had progress costs no events at all.
749        if !had_new && !last_published.contains_key(&block_id) {
750            continue;
751        }
752        if progress.is_empty() && !last_published.contains_key(&block_id) {
753            continue;
754        }
755        if !force_republish && last_published.get(&block_id) == Some(&progress) {
756            continue;
757        }
758        out.push(SweepOutcome { agent_id, block_id, progress });
759    }
760
761    (states, out, (edits, prs))
762}
763
764/// Run the progress sweep loop. Never returns.
765pub async fn run_agent_progress_loop(filestore: Arc<FileStore>, mstore: Arc<Store>, broker: Arc<Broker>) {
766    let mut ticker = interval(Duration::from_secs(SWEEP_INTERVAL_SECS));
767    let mut tick: u64 = 0;
768    let mut states: HashMap<String, BlockState> = HashMap::new();
769    // Last payload published per block, so an unchanged checklist doesn't
770    // re-publish every 3s.
771    let mut last_published: HashMap<String, AgentProgress> = HashMap::new();
772
773    loop {
774        ticker.tick().await;
775        tick += 1;
776        let force_republish = tick % REPUBLISH_EVERY_TICKS == 0;
777
778        let agents: Vec<(String, String)> = get_global_handler()
779            .list_agents()
780            .into_iter()
781            .map(|a| (a.agent_id, a.block_id))
782            .collect();
783        let registered: std::collections::HashSet<String> =
784            agents.iter().map(|(_, block_id)| block_id.clone()).collect();
785        // Both maps are bounded by the live agent count, not by every block_id
786        // ever seen in the process's lifetime.
787        states.retain(|block_id, _| registered.contains(block_id));
788        last_published.retain(|block_id, _| registered.contains(block_id));
789
790        let fs = filestore.clone();
791        let ms = mstore.clone();
792        let published = last_published.clone();
793        let taken = std::mem::take(&mut states);
794        let joined = tokio::task::spawn_blocking(move || {
795            sweep_blocking(&fs, &ms, agents, taken, &published, force_republish)
796        })
797        .await;
798
799        // A panic inside the blocking closure loses that tick's accumulated
800        // state. Start clean rather than killing the loop: the next sweep
801        // re-seeds from the tail (flagged partial), which is degraded but
802        // recoverable, whereas returning here would end progress reporting for
803        // the life of the process.
804        let (returned_states, outcomes, (edits, prs)) = match joined {
805            Ok(v) => v,
806            Err(e) => {
807                tracing::error!(error = %e, "progress sweep task failed; state reset for next tick");
808                continue;
809            }
810        };
811        states = returned_states;
812        // Hands off and returns at once: the check runs on its own task.
813        crate::backend::work_facts::overlap_notes::on_new_edits(edits);
814        crate::backend::kanban::on_new_prs(&prs);
815        crate::backend::work_facts::overlap_notes::on_new_prs(prs);
816        *snapshot().write() = states
817            .iter()
818            .map(|(block_id, s)| {
819                (block_id.clone(), WatchedWork { progress: s.progress(), recent_files: s.recent_files.clone() })
820            })
821            .collect();
822
823        for SweepOutcome { agent_id, block_id, progress } in outcomes {
824            last_published.insert(block_id.clone(), progress.clone());
825
826            let ts = agentmux_common::time::now_ms_u64();
827
828            let event = crate::backend::mps_events::AgentProgressEvent {
829                agent_id,
830                block_id: block_id.clone(),
831                todos: progress.todos,
832                todos_truncated: progress.todos_truncated,
833                todos_partial: progress.todos_partial,
834                current_tool: progress.current_tool,
835                ts,
836            };
837            // persist 1: replayed to a freshly-subscribed route, so a Swarm opened
838            // mid-session sees the current checklist rather than waiting
839            // for the agent's next change — see REPUBLISH_EVERY_TICKS.
840            broker.publish_event::<crate::backend::mps_events::AgentProgress>(&event, vec![format!("block:{}", block_id)], 1);
841        }
842    }
843}
844
845#[cfg(test)]
846mod tests {
847    use super::*;
848
849    fn todo_write(id: &str, todos: &str) -> String {
850        format!(
851            r#"{{"type":"assistant","message":{{"content":[{{"type":"tool_use","id":"{id}","name":"TodoWrite","input":{{"todos":{todos}}}}}]}}}}"#
852        )
853    }
854
855    fn task_call(id: &str, tool: &str, tid: &str, title: &str, status: &str) -> String {
856        format!(
857            r#"{{"type":"assistant","message":{{"content":[{{"type":"tool_use","id":"{id}","name":"{tool}","input":{{"task_id":"{tid}","title":"{title}","status":"{status}"}}}}]}}}}"#
858        )
859    }
860
861    fn tool_use(id: &str, name: &str) -> String {
862        format!(
863            r#"{{"type":"assistant","message":{{"content":[{{"type":"tool_use","id":"{id}","name":"{name}","input":{{}}}}]}}}}"#
864        )
865    }
866
867    fn tool_result(id: &str) -> String {
868        format!(
869            r#"{{"type":"user","message":{{"content":[{{"type":"tool_result","tool_use_id":"{id}"}}]}}}}"#
870        )
871    }
872
873    /// One tick's worth of lines.
874    fn feed(state: &mut BlockState, lines: &[String]) {
875        feed_at(state, lines, 1_000);
876    }
877
878    fn feed_at(state: &mut BlockState, lines: &[String], now_ms: u64) {
879        let refs: Vec<&str> = lines.iter().map(|s| s.as_str()).collect();
880        apply_lines(state, &refs, Some(now_ms));
881    }
882
883    /// A block's own copy, as `consume_new_output` reads it.
884    fn consume(fs: &FileStore, block: &str, st: &mut BlockState) -> bool {
885        consume_new_output(&TranscriptSource::own(fs, block), st)
886    }
887
888    fn output_store(block: &str, text: &str) -> FileStore {
889        use crate::backend::storage::filestore::{FileMeta, FileOpts};
890        let fs = FileStore::open_in_memory().unwrap();
891        fs.make_file(block, "output", FileMeta::default(), FileOpts::default()).unwrap();
892        fs.append_data(block, "output", text.as_bytes()).unwrap();
893        fs
894    }
895
896    /// An srv restart (or any first sight of a block) reads the backlog: an
897    /// edit there without its own timestamp must not read as "edited now",
898    /// one with a timestamp keeps it, and what is written afterwards is live.
899    #[test]
900    fn a_first_sight_backlog_does_not_read_as_just_edited() {
901        let block = "b-backlog";
902        let stamped = r#"{"type":"assistant","timestamp":"2026-10-01T10:00:00Z","message":{"content":[{"type":"tool_use","id":"s1","name":"Edit","input":{"file_path":"/r/stamped.rs"}}]}}"#;
903        let backlog = format!("{}
904{}
905", edit_call("e1", "Edit", "file_path", "/r/old.rs"), stamped);
906        let fs = output_store(block, &backlog);
907        let mut st = BlockState::default();
908        assert!(consume(&fs, block, &mut st));
909        let got: Vec<(&str, u64)> = st.recent_files.iter().map(|f| (f.path.as_str(), f.ts_ms)).collect();
910        assert_eq!(got, vec![("/r/stamped.rs", 1_790_848_800_000)], "the untimed backlog edit is not recorded");
911        assert!(st.new_edits.is_empty(), "backlog edits are never checked for overlap");
912
913        let before = agentmux_common::time::now_ms_u64();
914        fs.append_data(block, "output", format!("{}
915", edit_call("e2", "Write", "file_path", "/r/new.rs")).as_bytes())
916            .unwrap();
917        assert!(consume(&fs, block, &mut st));
918        assert_eq!(st.recent_files[0].path, "/r/new.rs");
919        assert!(st.recent_files[0].ts_ms >= before, "a live edit takes the read time");
920        let live: Vec<&str> = st.new_edits.iter().map(|f| f.path.as_str()).collect();
921        assert_eq!(live, vec!["/r/new.rs"], "a live edit is handed to the overlap check");
922    }
923
924    /// A block first seen while still empty: everything after is live.
925    #[test]
926    fn a_block_first_seen_empty_records_its_first_edits() {
927        let block = "b-empty";
928        let fs = FileStore::open_in_memory().unwrap();
929        let mut st = BlockState::default();
930        assert!(!consume(&fs, block, &mut st));
931        let fs = output_store(block, &format!("{}
932", edit_call("e1", "Edit", "file_path", "/r/a.rs")));
933        assert!(consume(&fs, block, &mut st));
934        assert_eq!(st.recent_files.len(), 1);
935    }
936
937    /// A defined agent's progress is read from the agent's zone, with nothing
938    /// in the block's own store.
939    #[test]
940    fn progress_is_read_from_the_agents_zone() {
941        let zone = "agent:progress-global:current";
942        let global = output_store(zone, "");
943        let mut st = BlockState::default();
944        let source = TranscriptSource { fs: &global, zone: zone.to_string(), global: true, own: None };
945        assert!(!consume_new_output(&source, &mut st), "an empty zone has nothing");
946        global
947            .append_data(zone, "output", format!("{}\n", edit_call("e1", "Edit", "file_path", "/r/zone.rs")).as_bytes())
948            .unwrap();
949        assert!(consume_new_output(&source, &mut st));
950        assert_eq!(st.recent_files.len(), 1);
951        assert_eq!(st.recent_files[0].path, "/r/zone.rs");
952        assert!(st.global);
953    }
954
955    /// The cursor counts bytes of one copy: when the source changes (the agent's
956    /// zone got its first line while the block's own copy had history), the
957    /// watcher starts over instead of reading the zone from the block's offset.
958    #[test]
959    fn a_change_of_source_starts_the_cursor_over() {
960        let block = "b-flip";
961        let own = output_store(block, &format!("{}\n{}\n", edit_call("e1", "Edit", "file_path", "/r/own1.rs"), edit_call("e2", "Edit", "file_path", "/r/own2.rs")));
962        let mut st = BlockState::default();
963        assert!(consume(&own, block, &mut st));
964        let offset_in_own = st.next_offset;
965        assert!(offset_in_own > 0 && !st.global);
966
967        let zone = "agent:progress-flip:current";
968        let global = output_store(zone, &format!("{}\n", edit_call("g1", "Edit", "file_path", "/r/zone1.rs")));
969        let source = TranscriptSource { fs: &global, zone: zone.to_string(), global: true, own: None };
970        // What the zone already holds is backlog (a first sight), as for any new
971        // source: nothing recorded as just edited, and nothing carried over from
972        // the other copy; the cursor sits at the end of the zone.
973        assert!(consume_new_output(&source, &mut st));
974        assert!(st.global);
975        assert!(st.recent_files.is_empty(), "{:?}", st.recent_files.iter().map(|f| &f.path).collect::<Vec<_>>());
976        assert_eq!(st.next_offset, global.stat(zone, "output").unwrap().unwrap().size);
977        // What is written after that is live.
978        global
979            .append_data(zone, "output", format!("{}\n", edit_call("g2", "Edit", "file_path", "/r/zone2.rs")).as_bytes())
980            .unwrap();
981        assert!(consume_new_output(&source, &mut st));
982        let paths: Vec<&str> = st.recent_files.iter().map(|f| f.path.as_str()).collect();
983        assert_eq!(paths, vec!["/r/zone2.rs"]);
984    }
985
986    fn edit_call(id: &str, tool: &str, key: &str, path: &str) -> String {
987        format!(
988            r#"{{"type":"assistant","message":{{"content":[{{"type":"tool_use","id":"{id}","name":"{tool}","input":{{"{key}":"{path}","old_string":"a","new_string":"b"}}}}]}}}}"#
989        )
990    }
991
992    /// A fake output stream with Edit / Write / MultiEdit / NotebookEdit
993    /// calls fills recent files, newest first, with the read time.
994    #[test]
995    fn edit_tools_fill_recent_files_newest_first() {
996        let mut st = BlockState::default();
997        feed_at(
998            &mut st,
999            &[
1000                edit_call("e1", "Edit", "file_path", "C:/r/a.rs"),
1001                tool_result("e1"),
1002                edit_call("e2", "Write", "file_path", "C:/r/b.rs"),
1003                edit_call("e3", "MultiEdit", "file_path", "C:/r/c.rs"),
1004            ],
1005            10,
1006        );
1007        feed_at(&mut st, &[edit_call("e4", "NotebookEdit", "notebook_path", "C:/r/n.ipynb")], 20);
1008        let got: Vec<(&str, &str, u64)> =
1009            st.recent_files.iter().map(|f| (f.path.as_str(), f.tool.as_str(), f.ts_ms)).collect();
1010        assert_eq!(
1011            got,
1012            vec![
1013                ("C:/r/n.ipynb", "NotebookEdit", 20),
1014                ("C:/r/c.rs", "MultiEdit", 10),
1015                ("C:/r/b.rs", "Write", 10),
1016                ("C:/r/a.rs", "Edit", 10),
1017            ]
1018        );
1019        // The checklist and current tool are unchanged by the new bookkeeping.
1020        assert!(st.progress().todos.is_empty());
1021        assert_eq!(st.progress().current_tool.as_deref(), Some("Write"));
1022    }
1023
1024    #[test]
1025    fn editing_a_file_again_moves_it_to_the_front_without_duplicating_it() {
1026        let mut st = BlockState::default();
1027        feed_at(&mut st, &[edit_call("e1", "Edit", "file_path", "/r/a.rs")], 1);
1028        feed_at(&mut st, &[edit_call("e2", "Edit", "file_path", "/r/b.rs")], 2);
1029        feed_at(&mut st, &[edit_call("e3", "Write", "file_path", "/r/a.rs")], 3);
1030        let got: Vec<(&str, u64)> = st.recent_files.iter().map(|f| (f.path.as_str(), f.ts_ms)).collect();
1031        assert_eq!(got, vec![("/r/a.rs", 3), ("/r/b.rs", 2)]);
1032        assert_eq!(st.recent_files[0].tool, "Write");
1033    }
1034
1035    #[test]
1036    fn recent_files_stay_bounded() {
1037        let mut st = BlockState::default();
1038        let calls: Vec<String> = (0..MAX_RECENT_FILES + 7)
1039            .map(|i| edit_call(&format!("e{i}"), "Edit", "file_path", &format!("/r/f{i}.rs")))
1040            .collect();
1041        feed(&mut st, &calls);
1042        assert_eq!(st.recent_files.len(), MAX_RECENT_FILES);
1043        assert_eq!(st.recent_files[0].path, format!("/r/f{}.rs", MAX_RECENT_FILES + 6));
1044    }
1045
1046    #[test]
1047    fn reads_and_other_tools_add_no_recent_files() {
1048        let mut st = BlockState::default();
1049        feed(
1050            &mut st,
1051            &[
1052                edit_call("r1", "Read", "file_path", "/r/a.rs"),
1053                edit_call("g1", "Grep", "file_path", "/r/b.rs"),
1054                edit_call("w1", "Edit", "old_string", "no path"),
1055            ],
1056        );
1057        assert!(st.recent_files.is_empty());
1058    }
1059
1060    fn run(lines: &[String]) -> AgentProgress {
1061        let mut st = BlockState::default();
1062        feed(&mut st, lines);
1063        st.progress()
1064    }
1065
1066    #[test]
1067    fn extracts_a_todowrite_checklist() {
1068        let p = run(&[todo_write(
1069            "t1",
1070            r#"[{"content":"Fix the bug","status":"in_progress"},{"content":"Write tests","status":"pending"}]"#,
1071        )]);
1072        assert_eq!(
1073            p.todos,
1074            vec![
1075                TodoItem { text: "Fix the bug".into(), status: "in_progress".into() },
1076                TodoItem { text: "Write tests".into(), status: "pending".into() },
1077            ]
1078        );
1079    }
1080
1081    #[test]
1082    fn the_latest_full_list_supersedes_earlier_ones() {
1083        let p = run(&[
1084            todo_write("t1", r#"[{"content":"A","status":"pending"}, {"content":"B","status":"pending"}]"#),
1085            todo_write("t2", r#"[{"content":"A","status":"completed"}]"#),
1086        ]);
1087        assert_eq!(p.todos, vec![TodoItem { text: "A".into(), status: "completed".into() }]);
1088    }
1089
1090    #[test]
1091    fn task_style_calls_accumulate_and_update_in_place() {
1092        let p = run(&[
1093            task_call("c1", "TaskCreate", "k1", "First", "pending"),
1094            task_call("c2", "TaskCreate", "k2", "Second", "pending"),
1095            task_call("u1", "TaskUpdate", "k1", "First", "completed"),
1096        ]);
1097        assert_eq!(
1098            p.todos,
1099            vec![
1100                TodoItem { text: "First".into(), status: "completed".into() },
1101                TodoItem { text: "Second".into(), status: "pending".into() },
1102            ],
1103            "an update revises its own row and preserves creation order",
1104        );
1105    }
1106
1107    /// THE reagent P1 regression: a TaskCreate seen in an EARLIER tick must
1108    /// survive once its line has scrolled out of any fixed tail window. A
1109    /// stateless, tail-only parser drops it silently while the task is still
1110    /// open — the failure this whole accumulate-across-ticks design exists for.
1111    #[test]
1112    fn a_task_created_in_an_earlier_tick_survives_later_unrelated_output() {
1113        let mut st = BlockState::default();
1114        feed(&mut st, &[task_call("c1", "TaskCreate", "k1", "Long-lived task", "pending")]);
1115
1116        // A later tick carrying only unrelated chatter — no todo tool in sight.
1117        let noise: Vec<String> = (0..50).map(|i| tool_use(&format!("n{i}"), "Read")).collect();
1118        feed(&mut st, &noise);
1119
1120        assert_eq!(
1121            st.progress().todos,
1122            vec![TodoItem { text: "Long-lived task".into(), status: "pending".into() }],
1123            "the task is still open and must still be listed",
1124        );
1125    }
1126
1127    #[test]
1128    fn an_update_arriving_a_tick_later_still_finds_its_row() {
1129        let mut st = BlockState::default();
1130        feed(&mut st, &[task_call("c1", "TaskCreate", "k1", "Task", "pending")]);
1131        feed(&mut st, &[tool_use("n1", "Bash"), tool_result("n1")]);
1132        feed(&mut st, &[task_call("u1", "TaskUpdate", "k1", "Task", "completed")]);
1133
1134        assert_eq!(st.progress().todos, vec![TodoItem { text: "Task".into(), status: "completed".into() }]);
1135    }
1136
1137    #[test]
1138    fn current_tool_is_the_outstanding_tool_use() {
1139        let p = run(&[tool_use("a", "Read"), tool_result("a"), tool_use("b", "Bash")]);
1140        assert_eq!(p.current_tool.as_deref(), Some("Bash"));
1141    }
1142
1143    #[test]
1144    fn no_current_tool_once_every_call_has_returned() {
1145        let p = run(&[tool_use("a", "Read"), tool_result("a")]);
1146        assert_eq!(p.current_tool, None);
1147    }
1148
1149    /// A result arriving in a later tick than its call must still clear it —
1150    /// the common case now that ticks are 3s and tools are slower than that.
1151    #[test]
1152    fn a_result_in_a_later_tick_clears_the_call_from_an_earlier_one() {
1153        let mut st = BlockState::default();
1154        feed(&mut st, &[tool_use("a", "Bash")]);
1155        assert_eq!(st.progress().current_tool.as_deref(), Some("Bash"));
1156        feed(&mut st, &[tool_result("a")]);
1157        assert_eq!(st.progress().current_tool, None);
1158    }
1159
1160    #[test]
1161    fn an_explicitly_cleared_checklist_reads_as_empty() {
1162        let p = run(&[
1163            todo_write("t1", r#"[{"content":"A","status":"pending"}]"#),
1164            todo_write("t2", "[]"),
1165        ]);
1166        assert!(p.todos.is_empty());
1167    }
1168
1169    #[test]
1170    fn truncates_a_pathological_list_and_reports_how_many_were_dropped() {
1171        let entries: Vec<String> = (0..MAX_TODOS + 5)
1172            .map(|i| format!(r#"{{"content":"item {i}","status":"pending"}}"#))
1173            .collect();
1174        let p = run(&[todo_write("t1", &format!("[{}]", entries.join(",")))]);
1175        assert_eq!(p.todos.len(), MAX_TODOS);
1176        assert_eq!(p.todos_truncated, 5);
1177    }
1178
1179    /// `partial` is about history we could not see; `todos_truncated` is a cap
1180    /// we chose. They are different claims and must not be conflated.
1181    #[test]
1182    fn a_tail_seeded_block_reports_its_checklist_as_partial() {
1183        let mut st = BlockState { partial: true, ..Default::default() };
1184        feed(&mut st, &[task_call("c1", "TaskCreate", "k1", "Only what we saw", "pending")]);
1185        let p = st.progress();
1186        assert!(p.todos_partial, "item-at-a-time rows may be missing earlier entries");
1187        assert_eq!(p.todos_truncated, 0, "nothing was dropped by the cap");
1188    }
1189
1190    /// …but a whole-list call is self-contained, so seeing one makes the
1191    /// checklist complete regardless of what came before.
1192    #[test]
1193    fn a_full_list_call_clears_the_partial_flag() {
1194        let mut st = BlockState { partial: true, ..Default::default() };
1195        feed(&mut st, &[todo_write("t1", r#"[{"content":"Whole list","status":"pending"}]"#)]);
1196        assert!(!st.progress().todos_partial);
1197    }
1198
1199    #[test]
1200    fn ignores_malformed_lines_instead_of_giving_up_on_the_whole_batch() {
1201        let p = run(&[
1202            "not json at all".to_string(),
1203            String::new(),
1204            todo_write("t1", r#"[{"content":"Survives","status":"pending"}]"#),
1205        ]);
1206        assert_eq!(p.todos.len(), 1);
1207    }
1208
1209    #[test]
1210    fn a_non_todo_tool_never_contributes_checklist_rows() {
1211        let p = run(&[tool_use("a", "Read"), tool_use("b", "Bash")]);
1212        assert!(p.todos.is_empty());
1213    }
1214
1215    #[test]
1216    fn recognizes_todo_tools_by_name_across_provider_vocabularies() {
1217        assert!(is_todo_tool("TodoWrite"));
1218        assert!(is_todo_tool("TaskCreate"));
1219        assert!(is_todo_tool("TaskUpdate"));
1220        // Substring fallback for a renamed/namespaced variant.
1221        assert!(is_todo_tool("mcp__planner__TodoSync"));
1222        assert!(!is_todo_tool("Read"));
1223        assert!(!is_todo_tool("Task"), "the subagent-spawning Task tool is not a checklist");
1224    }
1225
1226    /// Read-style tools return their data in the RESULT, which this parser
1227    /// never reads — so claiming to support them would be advertising a
1228    /// no-op (reagent P2 on PR #2952).
1229    #[test]
1230    fn read_style_task_tools_are_not_claimed_as_supported() {
1231        assert!(
1232            !TODO_TOOL_NAMES.contains(&"TaskList"),
1233            "TaskList's tasks live in its tool_result, not its input",
1234        );
1235        // TodoRead matches only via the deliberate `Todo` substring fallback,
1236        // and still contributes nothing because its input carries no items —
1237        // which is correct behavior, not a supported path.
1238        assert!(parse_todo_array(&serde_json::json!({})).is_none());
1239    }
1240
1241    #[test]
1242    fn the_open_tool_list_stays_bounded_when_results_go_missing() {
1243        let mut st = BlockState::default();
1244        let calls: Vec<String> = (0..MAX_OPEN_TOOLS + 20)
1245            .map(|i| tool_use(&format!("t{i}"), "Read"))
1246            .collect();
1247        feed(&mut st, &calls);
1248        assert_eq!(st.open.len(), MAX_OPEN_TOOLS);
1249    }
1250
1251    /// codex P1: a TaskUpdate legitimately carries only the id and the changed
1252    /// status. Requiring a complete item meant the row sat at `pending`
1253    /// forever — precisely the transition a checklist exists to show.
1254    #[test]
1255    fn a_status_only_update_moves_the_row_without_resending_its_text() {
1256        let mut st = BlockState::default();
1257        feed(&mut st, &[task_call("c1", "TaskCreate", "k1", "Ship it", "pending")]);
1258        feed(
1259            &mut st,
1260            &[format!(
1261                r#"{{"type":"assistant","message":{{"content":[{{"type":"tool_use","id":"u1","name":"TaskUpdate","input":{{"task_id":"k1","status":"completed"}}}}]}}}}"#
1262            )],
1263        );
1264        assert_eq!(
1265            st.progress().todos,
1266            vec![TodoItem { text: "Ship it".into(), status: "completed".into() }],
1267            "text is preserved from the create, status taken from the update",
1268        );
1269    }
1270
1271    /// The mirror: a text-only edit must not reset a status back to pending.
1272    #[test]
1273    fn a_text_only_update_preserves_the_existing_status() {
1274        let mut st = BlockState::default();
1275        feed(&mut st, &[task_call("c1", "TaskCreate", "k1", "Old wording", "in_progress")]);
1276        feed(
1277            &mut st,
1278            &[format!(
1279                r#"{{"type":"assistant","message":{{"content":[{{"type":"tool_use","id":"u1","name":"TaskUpdate","input":{{"task_id":"k1","title":"New wording"}}}}]}}}}"#
1280            )],
1281        );
1282        assert_eq!(
1283            st.progress().todos,
1284            vec![TodoItem { text: "New wording".into(), status: "in_progress".into() }],
1285        );
1286    }
1287
1288    /// An update for a task we never saw created (seeded mid-stream) has no
1289    /// text to display, so it must not invent a blank row.
1290    #[test]
1291    fn a_status_only_update_for_an_unknown_task_creates_no_row() {
1292        let mut st = BlockState::default();
1293        feed(
1294            &mut st,
1295            &[format!(
1296                r#"{{"type":"assistant","message":{{"content":[{{"type":"tool_use","id":"u1","name":"TaskUpdate","input":{{"task_id":"ghost","status":"completed"}}}}]}}}}"#
1297            )],
1298        );
1299        assert!(st.progress().todos.is_empty());
1300    }
1301
1302    /// codex P2: Gemini-shaped transcripts put the frame at the TOP LEVEL with
1303    /// `tool_name`/`tool_id`/`parameters`. Before this, every non-Claude agent
1304    /// showed no in-flight tool and no todos at all.
1305    #[test]
1306    fn parses_provider_native_top_level_tool_frames() {
1307        let mut st = BlockState::default();
1308        feed(
1309            &mut st,
1310            &[r#"{"type":"tool_use","tool_name":"Bash","tool_id":"g1","parameters":{}}"#.to_string()],
1311        );
1312        assert_eq!(st.progress().current_tool.as_deref(), Some("Bash"));
1313
1314        feed(
1315            &mut st,
1316            &[r#"{"type":"tool_result","tool_id":"g1","status":"success"}"#.to_string()],
1317        );
1318        assert_eq!(st.progress().current_tool, None, "a tool_id result clears its call");
1319    }
1320
1321    #[test]
1322    fn parses_a_todo_checklist_from_a_top_level_frame() {
1323        let mut st = BlockState::default();
1324        feed(
1325            &mut st,
1326            &[r#"{"type":"tool_use","tool_name":"TodoWrite","tool_id":"g2","parameters":{"todos":[{"content":"From Gemini","status":"pending"}]}}"#.to_string()],
1327        );
1328        assert_eq!(
1329            st.progress().todos,
1330            vec![TodoItem { text: "From Gemini".into(), status: "pending".into() }],
1331        );
1332    }
1333
1334    /// An ordinary transcript line must not be mistaken for a bare tool frame.
1335    #[test]
1336    fn a_plain_line_is_not_treated_as_a_tool_frame() {
1337        let mut st = BlockState::default();
1338        feed(&mut st, &[r#"{"type":"system","subtype":"init","name":"TodoWrite"}"#.to_string()]);
1339        assert!(st.progress().todos.is_empty());
1340        assert_eq!(st.progress().current_tool, None);
1341    }
1342
1343    /// reagent P2: with no id, text is the only identity available, and keying
1344    /// on it alone silently merged two genuinely distinct in-flight tasks that
1345    /// happened to share a title. One invisibly missing row is a worse failure
1346    /// than two visible duplicates, so an idless CREATE always appends.
1347    #[test]
1348    fn two_idless_creates_with_the_same_title_stay_two_rows() {
1349        let idless_create = |id: &str, title: &str| {
1350            format!(
1351                r#"{{"type":"assistant","message":{{"content":[{{"type":"tool_use","id":"{id}","name":"TaskCreate","input":{{"title":"{title}","status":"pending"}}}}]}}}}"#
1352            )
1353        };
1354        let p = run(&[idless_create("c1", "Retry the flaky step"), idless_create("c2", "Retry the flaky step")]);
1355        assert_eq!(p.todos.len(), 2, "two distinct tasks must not collapse into one row");
1356        assert!(p.todos.iter().all(|t| t.text == "Retry the flaky step"));
1357    }
1358
1359    /// …but an idless UPDATE still has to find its row, since matching by text
1360    /// is the only correlation available and appending would be a duplicate.
1361    #[test]
1362    fn an_idless_update_still_matches_its_row_by_text() {
1363        let mut st = BlockState::default();
1364        feed(&mut st, &[task_call("c1", "TaskCreate", "k1", "Ship it", "pending")]);
1365        feed(
1366            &mut st,
1367            &[format!(
1368                r#"{{"type":"assistant","message":{{"content":[{{"type":"tool_use","id":"u1","name":"TaskUpdate","input":{{"title":"Ship it","status":"completed"}}}}]}}}}"#
1369            )],
1370        );
1371        assert_eq!(
1372            st.progress().todos,
1373            vec![TodoItem { text: "Ship it".into(), status: "completed".into() }],
1374        );
1375    }
1376
1377    /// An id, when present, is always the key — two same-titled tasks with
1378    /// distinct ids stay distinct, and an update by id finds its own row.
1379    #[test]
1380    fn ids_take_precedence_over_text_for_identity() {
1381        let p = run(&[
1382            task_call("c1", "TaskCreate", "k1", "Same title", "pending"),
1383            task_call("c2", "TaskCreate", "k2", "Same title", "pending"),
1384            task_call("u1", "TaskUpdate", "k2", "Same title", "completed"),
1385        ]);
1386        assert_eq!(
1387            p.todos,
1388            vec![
1389                TodoItem { text: "Same title".into(), status: "pending".into() },
1390                TodoItem { text: "Same title".into(), status: "completed".into() },
1391            ],
1392        );
1393    }
1394
1395    #[test]
1396    fn create_style_tool_names_are_recognized() {
1397        assert!(is_create_call("TaskCreate"));
1398        assert!(is_create_call("TodoAdd"));
1399        assert!(!is_create_call("TaskUpdate"));
1400        assert!(!is_create_call("TodoWrite"), "a whole-list write never reaches the single-item path");
1401    }
1402
1403    #[test]
1404    fn empty_progress_is_recognized_so_idle_agents_publish_nothing() {
1405        assert!(AgentProgress::default().is_empty());
1406        let p = run(&[tool_use("a", "Read")]);
1407        assert!(!p.is_empty(), "an in-flight tool is worth publishing on its own");
1408    }
1409
1410    #[test]
1411    fn a_pr_create_is_recognized_in_any_shell_command() {
1412        assert!(is_pr_create("gh-agent pr create --title x --body y"));
1413        assert!(is_pr_create("cd /w/agentmux && gh pr create --fill"));
1414        assert!(is_pr_create("/usr/local/bin/gh-agent pr create -t x"));
1415        assert!(is_pr_create("C:\\npm\\gh-agent.cmd pr create -t x"));
1416        assert!(!is_pr_create("gh-agent pr view 12"));
1417        assert!(!is_pr_create("echo gh pr list; grep create"));
1418        assert!(!is_pr_create("git commit -m 'gh-agent pr: create'"));
1419        assert!(is_shell_tool("Bash") && is_shell_tool("mcp__agentmux__Terminal") && !is_shell_tool("Edit"));
1420        assert!(is_pr_create("pwsh.exe -NoProfile -Command 'gh-agent pr create -t x'"));
1421    }
1422
1423    /// gh's inherited flags can sit between the words, and the PR's head and
1424    /// base can be named.
1425    #[test]
1426    fn a_pr_create_with_flags_and_its_head_and_base() {
1427        assert!(is_pr_create("gh --repo owner/repo pr create -t x"));
1428        assert!(is_pr_create("gh pr -R owner/repo create -t x"));
1429        assert!(!is_pr_create("gh --repo pr view create"), "the value of --repo is not a word");
1430        assert!(!is_pr_create("gh pr view 1 && echo create"));
1431        let pr = |c: &str| pr_create(c).unwrap();
1432        assert_eq!(pr("gh-agent pr create -H agenty/x -B release"), NewPrCommand {
1433            head: Some("agenty/x".into()),
1434            base: Some("release".into())
1435        });
1436        assert_eq!(pr("gh pr create --head=me:feature --title t").head.as_deref(), Some("me:feature"));
1437        assert_eq!(pr("gh pr create -t x && git push --base y"), NewPrCommand::default(), "flags of the next command are not its");
1438    }
1439
1440    /// Codex's shell commands are `item.started` events, as its 0.154.0
1441    /// fixture records them (frontend/test/fixtures/providers/codex/0.154.0/command.jsonl).
1442    #[test]
1443    fn a_codex_pr_create_is_handed_to_the_overlap_note() {
1444        let started = r#"{"type":"item.started","item":{"id":"item_0","type":"command_execution","command":"pwsh.exe -NoProfile -Command 'gh-agent pr create -t x'","aggregated_output":"","exit_code":null,"status":"in_progress"}}"#;
1445        let completed = started.replace("item.started", "item.completed");
1446        let mut st = BlockState::default();
1447        apply_lines(&mut st, &[started, completed.as_str()], Some(1_000));
1448        assert_eq!(st.new_prs.len(), 1, "the start counts, its completion does not");
1449    }
1450
1451    #[test]
1452    fn only_a_live_pr_create_is_handed_to_the_overlap_note() {
1453        let line = |cmd: &str| format!(
1454            r#"{{"type":"assistant","message":{{"content":[{{"type":"tool_use","id":"p1","name":"Bash","input":{{"command":"{cmd}"}}}}]}}}}"#
1455        );
1456        let mut backlog = BlockState::default();
1457        apply_lines(&mut backlog, &[line("gh-agent pr create -t x").as_str()], None);
1458        assert!(backlog.new_prs.is_empty(), "backlog is history");
1459        let mut live = BlockState::default();
1460        apply_lines(&mut live, &[line("gh-agent pr create -t x").as_str(), line("ls").as_str()], Some(1_000));
1461        assert_eq!(live.new_prs, vec![NewPrCommand::default()]);
1462        assert_eq!(live.open.len(), 2, "both calls still count as in flight");
1463    }
1464}