From 796cffb9dbbab6b2b221fc9183818b4bb0ad6165 Mon Sep 17 00:00:00 2001 From: JButton <623118+jbutton@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:10:03 +0100 Subject: [PATCH 1/2] Fork: a background Bash counts as running work until it ends Claude Code's background commands (a Bash with run_in_background, or one moved to the background when its timeout ran out) now hold the agent's turn like a background agent does: crates/core/src/agents/helpers.rs counts one from the result that names it (toolUseResult.backgroundTaskId, or the words the result starts with) until its (completed, failed or killed) or TaskStop's result, which is all a stop writes. Before, only "Async agent launched" counted, so the check, the review and the ready alert started while the command still ran, on what the agent said before it ended. The shapes are taken from real transcripts (Claude Code 2.1.308 to 2.1.322). Tests: tests/helpers/shells.rs (failed on main: the task reached approval with the check and the review run while the command ran). Docs: how-work-gets-done and troubleshooting. Ported from upstream Shepherdr 54a65b23 (SHEP-148, #865), rewritten in Rust. MIT, same notice as this fork's LICENSE. Co-Authored-By: Claude Opus 5.5 --- crates/core/src/agents/helpers.rs | 32 +++++- docs/how-work-gets-done.md | 7 ++ docs/troubleshooting.md | 2 +- tests/fixtures/endings/README.md | 4 + .../endings/claude-shell-back-made.jsonl | 4 + .../endings/claude-shell-running-made.jsonl | 3 + tests/helpers.rs | 12 +- tests/helpers/shells.rs | 107 ++++++++++++++++++ 8 files changed, 161 insertions(+), 10 deletions(-) create mode 100644 tests/fixtures/endings/claude-shell-back-made.jsonl create mode 100644 tests/fixtures/endings/claude-shell-running-made.jsonl create mode 100644 tests/helpers/shells.rs diff --git a/crates/core/src/agents/helpers.rs b/crates/core/src/agents/helpers.rs index f32b3161..deffd076 100644 --- a/crates/core/src/agents/helpers.rs +++ b/crates/core/src/agents/helpers.rs @@ -1,7 +1,7 @@ -//! Helpers an agent runs inside its own work (Codex's sub-agents, Claude Code's background agents). A helper's turn -//! ending is not the agent's: Codex reports it like any turn end, with the helper's own thread, whose saved -//! conversation names the thread that started it. And while a helper the agent started is still at work, the agent's -//! own turn ending is not the end of its work: the helper's answer starts the agent again. +//! Helpers an agent runs inside its own work (Codex's sub-agents, Claude Code's background agents and the commands it +//! runs in the background). A helper's turn ending is not the agent's: Codex reports it like any turn end, with the +//! helper's own thread, whose saved conversation names the thread that started it. And while a helper the agent started +//! is still at work, the agent's own turn ending is not the end of its work: the helper's answer starts the agent again. use super::adapter::transcript; use super::read_turn::{head_of, read_turn, tail_lines, when, Turn, TAIL}; use crate::json::*; @@ -53,15 +53,24 @@ fn word_after(line: &str, key: &str) -> Vec { /// `` comes back. One that comes back while the agent's turn is still going is no message of its own: /// it is written as a queued command (`queue-operation`, then an `attachment` taken into the running turn), as seen on /// HSW-218 (Claude Code 2.1.300, 2026-10-15), where the board waited for a helper back for half an hour. +/// A command it runs in the background (a Bash with `run_in_background`, or one moved there when its timeout ran out) +/// is at work the same way, from the result that names it until its `` (completed, failed or +/// killed), or until TaskStop's result: a stopped one gets no notification (Claude Code 2.1.308 to 2.1.322). Before, a +/// turn that ended while one ran was taken for the end, and the check and the review ran while it still did (upstream +/// Shepherdr SHEP-148). fn claude_running(file: &Path, since: i64) -> usize { let mut live: Vec<(String, i64)> = vec![]; let mut known: Vec = vec![]; - for (l, e) in lines_with(file, &["Async agent launched", "", "\"SendMessage\""]) { + for (l, e) in lines_with(file, &["Async agent launched", "", "\"SendMessage\"", "backgroundTaskId", "in background with ID", "moved to the background", "Successfully stopped task"]) { let at = when(e.at("timestamp")); if e.s("type") == "user" && l.contains("Async agent launched") { for id in word_after(&l, "agentId: ") { live.retain(|(x, _)| *x != id); live.push((id.clone(), at)); known.push(id); } } else if ["user", "attachment", "queue-operation"].contains(&e.s("type")) && l.contains("") { for id in word_after(&l, "") { live.retain(|(x, _)| *x != id); } + } else if e.s("type") == "user" && !e.b("isSidechain") { + let r = e.at("toolUseResult"); + if let Some(id) = shell_started(&e) { live.retain(|(x, _)| *x != id); live.push((id, at)); } + else if r.b("task_id") && r.s("message").to_lowercase().contains("stopped") { let id = r.t("task_id"); live.retain(|(x, _)| *x != id); } } else if e.s("type") == "assistant" { for c in e.at("message").arr("content") { let to = c.at("input").t("to"); @@ -71,6 +80,19 @@ fn claude_running(file: &Path, since: i64) -> usize { } live.iter().filter(|(id, at)| *at >= since && !claude_back(file, id, *at)).count() } +/// The id of a command Claude Code moved to the background, from its result: its `backgroundTaskId`, or the words the +/// result starts with (a command's own output that only quotes them, further in, is none). +fn shell_started(e: &Value) -> Option { + let id = e.at("toolUseResult").t("backgroundTaskId"); + if !id.is_empty() { return Some(id); } + let words = |c: &Value| c.as_str().map(String::from).unwrap_or_else(|| c.as_array().map(|a| a.iter().map(|x| x.t("text")).collect::>().join("\n")).unwrap_or_default()); + e.at("message").arr("content").iter().filter(|c| c.s("type") == "tool_result").find_map(|c| { + let w = words(c.at("content")); + let w = w.trim_start(); + let key = if w.starts_with("Command running in background with ID: ") { "with ID: " } else if w.starts_with("Command did not complete") { "moved to the background (ID: " } else { return None }; + word_after(w, key).into_iter().next() + }) +} /// A Claude Code helper's own conversation (`/subagents/agent-.jsonl`) ends in its finished reply, /// written since it was last started: it is back, whatever the agent's own file shows of its notification. fn claude_back(file: &Path, id: &str, at: i64) -> bool { diff --git a/docs/how-work-gets-done.md b/docs/how-work-gets-done.md index 4dee7fbb..c20c1b9c 100644 --- a/docs/how-work-gets-done.md +++ b/docs/how-work-gets-done.md @@ -137,6 +137,13 @@ When the agent's turn ends, the board: still going. (The same holds for a working agent and its task.) A helper is back when its answer is in the conversation (a message of its own, or a queued one taken into a turn still going), or its own saved conversation ends in its finished reply. + - A command Claude Code runs in the background (a Bash with `run_in_background`, or one moved there when its + timeout ran out) counts the same way: a turn that ends while one runs is not the end. It has ended when its + notification is in the conversation (completed, failed or killed) or the agent stopped it (TaskStop). Its end + starts the agent again, and that turn's end is the one that counts. So the check, the review and the "ready" + alert start once, after the command, not while it runs. Meanwhile the row says `Finishing`. A command that never + ends (a server left running) holds it there: the agents are told to stop theirs before they finish, and `Ctrl+L` + takes the work as it is. - A reviewer whose turn its provider cut off is retried by the board ([a turn cut off by the provider](provider-errors.md)). - The board decides from the findings ([the gate](gate.md)). A review that fails goes straight back to the agent. - The row says the result and a tally (`Pass · 2 minor`). Its `R#2` tag says which review it was and, by its colour, diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index ebd74ab2..abb74c69 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -100,7 +100,7 @@ Find what its row says: | `queued after HSW-12` | it waits for other tasks to be done ([one task after another](after.md)) | wait, or `herdr-projects delegate --now` | | `Has not started yet: pressing enter again` | the task's text sits in the agent's box | wait a moment: the board presses enter again | | `Not started: its instructions sit unsent in its box` | the text never went in | `Ctrl+L` (retry), or go into the agent and press enter ([handing over](handing-over.md)) | -| `Finishing` for a long time, with the agent at rest | the board missed the end of its turn | `Ctrl+L`, or `herdr-projects finish ` | +| `Finishing` for a long time, with the agent at rest | a command the agent runs in the background (Claude Code) has not ended, and the task waits for it ([how work gets done](how-work-gets-done.md)); or the board missed the end of its turn | wait for the command, or have the agent stop it; `Ctrl+L`, or `herdr-projects finish `, takes the work as it is | | `Stopped without a summary` | the agent stopped and the board cannot tell if it finished | `Ctrl+R` tells it to go on; `Ctrl+L` takes the work as it is | | `Agent's connection dropped, trying again in 2m` | the provider cut the turn off | nothing: the board retries by itself ([a turn cut off by the provider](provider-errors.md)) | | `Agent stopped` | an error waiting cannot fix: a usage limit, a refusal | read the reason in the panel; reply, or `Ctrl+R` | diff --git a/tests/fixtures/endings/README.md b/tests/fixtures/endings/README.md index c18a4c7e..9ef98997 100644 --- a/tests/fixtures/endings/README.md +++ b/tests/fixtures/endings/README.md @@ -22,5 +22,9 @@ the API's documented 529 and 429 texts; the two `-finished-made` files are an or - `claude-helper-back-mid-turn-made` (tests/finish_missed.rs): a helper whose answer comes back while the agent's turn is still going, in the shape recorded on HSW-218 (Claude Code 2.1.300): its `` is only a `queue-operation` and an `attachment` (a queued command taken into the running turn), never a message of its own. +- `claude-shell-running-made`, `claude-shell-back-made` (tests/helpers/shells.rs): a turn that ends while a command it + started in the background still runs, and the turn the command's end starts, in the shape recorded from Claude Code + 2.1.314 (a Bash result with `backgroundTaskId`, then its `` queued and taken as a message), with + folder names cut. - `claude-idle-compaction` (tests/turns/ended_late.rs): recorded on 2026-10-24 (Claude Code 2.1.312), summary and file names cut: what Claude Code writes when it compacts a session left idle an hour after its turn ended, with no prompt. diff --git a/tests/fixtures/endings/claude-shell-back-made.jsonl b/tests/fixtures/endings/claude-shell-back-made.jsonl new file mode 100644 index 00000000..02996124 --- /dev/null +++ b/tests/fixtures/endings/claude-shell-back-made.jsonl @@ -0,0 +1,4 @@ +{"type": "queue-operation", "operation": "enqueue", "sessionId": "made", "content": "\nbk3m9x2qa\ntoolu_made_s1\n/private/tmp/claude-501/made/tasks/bk3m9x2qa.output\ncompleted\nBackground command \"Run the full check\" completed (exit code 0)\n"} +{"type": "queue-operation", "operation": "dequeue", "sessionId": "made"} +{"type": "user", "uuid": "made-s4", "isSidechain": false, "message": {"role": "user", "content": "\nbk3m9x2qa\ntoolu_made_s1\n/private/tmp/claude-501/made/tasks/bk3m9x2qa.output\ncompleted\nBackground command \"Run the full check\" completed (exit code 0)\n"}, "origin": {"kind": "task-notification", "producer": "session-task"}, "promptSource": "system", "turnOrigin": "task_notification"} +{"type": "assistant", "uuid": "made-s5", "message": {"id": "msg_made_s5", "role": "assistant", "content": [{"type": "text", "text": "The full check passed. Done."}], "stop_reason": "end_turn"}} diff --git a/tests/fixtures/endings/claude-shell-running-made.jsonl b/tests/fixtures/endings/claude-shell-running-made.jsonl new file mode 100644 index 00000000..7808f0ee --- /dev/null +++ b/tests/fixtures/endings/claude-shell-running-made.jsonl @@ -0,0 +1,3 @@ +{"type": "assistant", "uuid": "made-s1", "message": {"id": "msg_made_s1", "role": "assistant", "content": [{"type": "tool_use", "id": "toolu_made_s1", "name": "Bash", "input": {"command": "npm run check -- --all", "description": "Run the full check", "run_in_background": true}}], "stop_reason": "tool_use"}} +{"type": "user", "uuid": "made-s2", "isSidechain": false, "message": {"role": "user", "content": [{"tool_use_id": "toolu_made_s1", "type": "tool_result", "content": "Command running in background with ID: bk3m9x2qa. Output is being written to: /private/tmp/claude-501/made/tasks/bk3m9x2qa.output. You will be notified when it completes — do not poll that file or sleep while waiting."}]}, "toolUseResult": {"stdout": "", "stderr": "", "interrupted": false, "isImage": false, "noOutputExpected": false, "backgroundTaskId": "bk3m9x2qa"}} +{"type": "assistant", "uuid": "made-s3", "message": {"id": "msg_made_s3", "role": "assistant", "content": [{"type": "text", "text": "Committed. The full check runs in the background; I finish once it has passed."}], "stop_reason": "end_turn"}} diff --git a/tests/helpers.rs b/tests/helpers.rs index 62c8ec6b..3d99ff54 100644 --- a/tests/helpers.rs +++ b/tests/helpers.rs @@ -1,13 +1,17 @@ -//! Helpers an agent runs inside its own work (Codex's sub-agents, Claude Code's background agents): a helper's turn -//! ending is not the review's or the task's end, a turn that ends while a helper is still at work is waited past, and -//! a reviewer that really ended without a verdict is started once more by itself. Seen on HP-1 (2026-10-15): a Codex -//! reviewer's helper `/root/check_plans` finished, and the board failed the review for want of a verdict. +//! Helpers an agent runs inside its own work (Codex's sub-agents, Claude Code's background agents and commands): a +//! helper's turn ending is not the review's or the task's end, a turn that ends while a helper is still at work is +//! waited past, and a reviewer that really ended without a verdict is started once more by itself. Seen on HP-1 +//! (2026-10-15): a Codex reviewer's helper `/root/check_plans` finished, and the board failed the review for want of a +//! verdict. use crate::common; use common::*; use serde_json::{json, Value}; use sw::json::*; use sw::store::reviews::{review_history, review_round}; +/// A command Claude Code runs in the background, at work until it ends (upstream SHEP-148). +mod shells; + fn work() -> Value { json!({ "files": { "f.txt": "v1\n" }, "commit": "v1", "note": "Did v1." }) } fn verdict() -> Value { json!({ "meets": true, "findings": [], "text": "Looks right." }) } fn reviewer_starts(w: &World) -> usize { calls(w).iter().filter(|c| regex::Regex::new(r"^agent start \S+-r ").unwrap().is_match(c)).count() } diff --git a/tests/helpers/shells.rs b/tests/helpers/shells.rs new file mode 100644 index 00000000..1f88d329 --- /dev/null +++ b/tests/helpers/shells.rs @@ -0,0 +1,107 @@ +//! A command Claude Code runs in the background (a Bash with `run_in_background`, or one moved there when its timeout +//! ran out) is the agent's own work still going: a turn that ends while one runs is not the end of the task's work. The +//! check, the review and "ready" start once it has ended, on the turn its end starts. Before, they started while it +//! still ran, on what the agent said before it ended (the fork's report on Shepherdr, row 4; upstream SHEP-148, #865, +//! 54a65b23). +use crate::common; +use common::*; +use serde_json::{json, Value}; +use std::path::{Path, PathBuf}; +use sw::json::*; + +fn reviewer_starts(w: &World) -> usize { calls(w).iter().filter(|c| regex::Regex::new(r"^agent start \S+-r ").unwrap().is_match(c)).count() } +fn checks(w: &World) -> usize { read(&w.base.join("checks.log")).lines().filter(|l| !l.is_empty()).count() } +fn write(file: &Path, lines: &[Value]) { std::fs::create_dir_all(file.parent().unwrap()).unwrap(); std::fs::write(file, lines.iter().map(|l| format!("{l}\n")).collect::()).unwrap(); } +fn result(at: &str, text: &str, extra: Value) -> Value { + let mut r = json!({ "stdout": "", "stderr": "", "interrupted": false, "isImage": false, "noOutputExpected": false }); + for (k, v) in extra.as_object().cloned().unwrap_or_default() { r[k] = v; } + json!({ "timestamp": at, "type": "user", "isSidechain": false, "message": { "role": "user", "content": [{ "tool_use_id": "toolu_x", "type": "tool_result", "content": text }] }, "toolUseResult": r }) +} +/// What Claude Code 2.1.314 writes for a Bash started in the background (recorded; its output file's folder cut). +fn started(at: &str, id: &str) -> Value { result(at, &format!("Command running in background with ID: {id}. Output is being written to: /tmp/tasks/{id}.output. You will be notified when it completes."), json!({ "backgroundTaskId": id })) } +/// And for one moved there when its timeout ran out (2.1.312). +fn moved(at: &str, id: &str) -> Value { result(at, &format!("Command did not complete within its 120s timeout and was moved to the background (ID: {id}). Output is being written to: /tmp/tasks/{id}.output. You will be notified when it completes."), json!({ "backgroundTaskId": id, "timedOutAfterMs": 120000 })) } +/// Its end: a ``, as a message of its own (`user`) or queued into a turn still going. +fn ended(at: &str, kind: &str, id: &str, status: &str) -> Value { + let text = format!("\n{id}\ntoolu_x\n/tmp/tasks/{id}.output\n{status}\nBackground command \"npm test\" {status}\n"); + if kind == "user" { json!({ "timestamp": at, "type": "user", "isSidechain": false, "message": { "role": "user", "content": text } }) } else { json!({ "timestamp": at, "type": kind, "operation": "enqueue", "content": text }) } +} +/// TaskStop's result: a stopped shell gets no notification (seen in every recorded stop, 2.1.308 to 2.1.322). +fn stopped(at: &str, id: &str) -> Value { result(at, &json!({ "message": format!("Successfully stopped task: {id} (npm run dev)"), "task_id": id }).to_string(), json!({ "message": format!("Successfully stopped task: {id} (npm run dev)"), "task_id": id, "task_type": "local_bash" })) } + +#[test] +fn a_claude_worker_whose_background_command_still_runs_is_not_finished_until_it_ends() { + let w = cut_world("30", json!({ "worker.agent": "claude" })); + // Every run of the check leaves a line outside the repo, so the test can count them. + std::fs::write(w.root.join(".herdr-projects.json"), json!({ "check.command": "echo run >> \"$HERDR_PROJECTS_REPO/../checks.log\"" }).to_string()).unwrap(); + git(&w.root, &["add", "-A"]); git(&w.root, &["commit", "-qm", "check"]); + // It commits, starts the full check in the background and ends its turn; the check's end wakes it, and it is done. + let first = json!({ "files": { "f.txt": "v1\n" }, "commit": "v1", "note": "Did v1.", "ends": "claude-shell-running-made", "hook": true, "after": 0, "then": { "ends": "claude-shell-back-made", "hook": true } }); + w.script(json!({ "worker": [first] })); + let id = w.add("Background check"); + delegate(&id); + let t = settle(&id); + assert_eq!((t.s("stage"), checks(&w), reviewer_starts(&w)), ("working", 0, 0), "{}", t.s("msg")); + let looks = calls(&w).len(); + let pane = t.at("link").t("pane"); + set_status(&w, &pane, "working"); set_status(&w, &pane, "idle"); // as herdr saw it: at work, then at rest + assert_eq!(settle(&id).s("stage"), "working"); // looked at again, it still waits for its command + assert_eq!((row(&id).s("note"), checks(&w), reviewer_starts(&w)), ("Finishing", 0, 0)); + assert!(calls(&w).len() - looks < 20, "{:?}", &calls(&w)[looks..]); + w.go_on(&t); + let t = settle(&id); + assert_eq!(t.s("stage"), "approval", "{} {}", t.s("msg"), t.at("failure")); + assert_eq!((checks(&w), reviewer_starts(&w)), (1, 1)); + assert!(t.s("said").contains("The full check passed. Done."), "{}", t.s("said")); +} + +#[test] +fn a_background_command_runs_until_its_notification_or_its_stop() { + let _w = world(); + let started_at = sw::clock::now(); + let at = |ms: i64| sw::clock::iso(started_at + ms); + let file = PathBuf::from(std::env::var("CLAUDE_CONFIG_DIR").unwrap()).join("projects").join("x").join("shells.jsonl"); + let running = |lines: &[Value]| { write(&file, lines); sw::agents::helpers::running("claude", &file, started_at) }; + // Started in the background, however long ago: at work until it ends. + let mut lines = vec![started(&at(1000), "bk3m9x2qa")]; + sw::clock::advance(3 * 3600000); + assert_eq!(running(&lines), 1); + // Its end came back while a turn was still going: queued, taken into that turn. + lines.push(ended(&at(2000), "queue-operation", "bk3m9x2qa", "completed")); + assert_eq!(running(&lines), 0); + // A foreground one moved to the background by its timeout, ending in a failure of its own. + lines.push(moved(&at(3000), "b5ea5sjiy")); + assert_eq!(running(&lines), 1); + lines.push(ended(&at(4000), "user", "b5ea5sjiy", "failed")); + assert_eq!(running(&lines), 0); + // Stopped by the agent: no notification, only TaskStop's result. + lines.push(started(&at(5000), "bumphhsle")); + assert_eq!(running(&lines), 1); + lines.push(stopped(&at(6000), "bumphhsle")); + assert_eq!(running(&lines), 0); + // A command's own output that only quotes such a line, and Claude Code's copies of its requests, start nothing. + lines.push(result(&at(7000), " 10 Command running in background with ID: b0po6ap81", json!({}))); + lines.push(json!({ "type": "api-request-blob", "timestamp": at(7000), "message": { "role": "user", "content": started(&at(1), "bq8w3e5rt").at("message").at("content").clone() }, "toolUseResult": { "backgroundTaskId": "bq8w3e5rt" } })); + assert_eq!(running(&lines), 0); + // A shell lives in the agent's program: one left running by the program before this one is gone with it. + lines.push(started(&at(8000), "b7h2kq0zx")); + assert_eq!(running(&lines), 1); + assert_eq!(sw::agents::helpers::running("claude", &file, sw::clock::now()), 0); +} + +#[test] +fn a_command_that_never_ends_holds_the_task_at_finishing_and_the_finish_key_takes_the_work_as_it_is() { + let w = cut_world("30", json!({ "worker.agent": "claude" })); + w.script(json!({ "worker": [{ "files": { "f.txt": "v1\n" }, "commit": "v1", "note": "Did v1.", "ends": "claude-shell-running-made", "hook": true }] })); + let id = w.add("Left running"); + delegate(&id); + let t = settle(&id); + let pane = t.at("link").t("pane"); + set_status(&w, &pane, "working"); set_status(&w, &pane, "idle"); + assert_eq!((settle(&id).s("stage"), row(&id).s("note"), reviewer_starts(&w)), ("working", "Finishing", 0)); + assert!(sw::shown::states::stuck_finishing(&row(&id))); + sw::actions::finish_line::finish_anyway(&id).unwrap(); + let t = settle(&id); + assert_eq!(t.s("stage"), "approval", "{} {}", t.s("msg"), t.at("failure")); + assert_eq!(reviewer_starts(&w), 1); +} From c8067c12f7e6d781dd580b221b40977266edcc41 Mon Sep 17 00:00:00 2001 From: JButton <623118+jbutton@users.noreply.github.com> Date: Fri, 13 Nov 2026 00:55:10 +0100 Subject: [PATCH 2/2] Fork: a background command only from its backgroundTaskId Review fix: a foreground Bash whose own output began with "Command running in background with ID: ..." was read as a background start that no notification would ever end, holding a finished task at Finishing. Claude Code's result names a background command in toolUseResult.backgroundTaskId (every one recorded, 2.1.308 to 2.1.322), so that alone counts now; the words of a result never do. tests/helpers/shells.rs has the reviewer's case. Upstream Shepherdr 54a65b23 (SHEP-148, #865). Co-Authored-By: Claude Opus 5.5 --- crates/core/src/agents/helpers.rs | 27 +++++++++------------------ tests/helpers/shells.rs | 5 ++++- 2 files changed, 13 insertions(+), 19 deletions(-) diff --git a/crates/core/src/agents/helpers.rs b/crates/core/src/agents/helpers.rs index deffd076..82b97964 100644 --- a/crates/core/src/agents/helpers.rs +++ b/crates/core/src/agents/helpers.rs @@ -54,14 +54,14 @@ fn word_after(line: &str, key: &str) -> Vec { /// it is written as a queued command (`queue-operation`, then an `attachment` taken into the running turn), as seen on /// HSW-218 (Claude Code 2.1.300, 2026-10-15), where the board waited for a helper back for half an hour. /// A command it runs in the background (a Bash with `run_in_background`, or one moved there when its timeout ran out) -/// is at work the same way, from the result that names it until its `` (completed, failed or -/// killed), or until TaskStop's result: a stopped one gets no notification (Claude Code 2.1.308 to 2.1.322). Before, a -/// turn that ended while one ran was taken for the end, and the check and the review ran while it still did (upstream -/// Shepherdr SHEP-148). +/// is at work the same way, from the result that names it (`backgroundTaskId`) until its `` +/// (completed, failed or killed), or until TaskStop's result: a stopped one gets no notification (Claude Code 2.1.308 to +/// 2.1.322). Before, a turn that ended while one ran was taken for the end, and the check and the review ran while it +/// still did (upstream Shepherdr SHEP-148). fn claude_running(file: &Path, since: i64) -> usize { let mut live: Vec<(String, i64)> = vec![]; let mut known: Vec = vec![]; - for (l, e) in lines_with(file, &["Async agent launched", "", "\"SendMessage\"", "backgroundTaskId", "in background with ID", "moved to the background", "Successfully stopped task"]) { + for (l, e) in lines_with(file, &["Async agent launched", "", "\"SendMessage\"", "backgroundTaskId", "Successfully stopped task"]) { let at = when(e.at("timestamp")); if e.s("type") == "user" && l.contains("Async agent launched") { for id in word_after(&l, "agentId: ") { live.retain(|(x, _)| *x != id); live.push((id.clone(), at)); known.push(id); } @@ -80,19 +80,10 @@ fn claude_running(file: &Path, since: i64) -> usize { } live.iter().filter(|(id, at)| *at >= since && !claude_back(file, id, *at)).count() } -/// The id of a command Claude Code moved to the background, from its result: its `backgroundTaskId`, or the words the -/// result starts with (a command's own output that only quotes them, further in, is none). -fn shell_started(e: &Value) -> Option { - let id = e.at("toolUseResult").t("backgroundTaskId"); - if !id.is_empty() { return Some(id); } - let words = |c: &Value| c.as_str().map(String::from).unwrap_or_else(|| c.as_array().map(|a| a.iter().map(|x| x.t("text")).collect::>().join("\n")).unwrap_or_default()); - e.at("message").arr("content").iter().filter(|c| c.s("type") == "tool_result").find_map(|c| { - let w = words(c.at("content")); - let w = w.trim_start(); - let key = if w.starts_with("Command running in background with ID: ") { "with ID: " } else if w.starts_with("Command did not complete") { "moved to the background (ID: " } else { return None }; - word_after(w, key).into_iter().next() - }) -} +/// The id of a command Claude Code moved to the background: its result's `backgroundTaskId` (in every one recorded, +/// 2.1.308 to 2.1.322). Never the words of the result: a foreground command's own output may begin with them, and no +/// notification would ever end a command it never started. +fn shell_started(e: &Value) -> Option { Some(e.at("toolUseResult").t("backgroundTaskId")).filter(|id| !id.is_empty()) } /// A Claude Code helper's own conversation (`/subagents/agent-.jsonl`) ends in its finished reply, /// written since it was last started: it is back, whatever the agent's own file shows of its notification. fn claude_back(file: &Path, id: &str, at: i64) -> bool { diff --git a/tests/helpers/shells.rs b/tests/helpers/shells.rs index 1f88d329..11bc5b50 100644 --- a/tests/helpers/shells.rs +++ b/tests/helpers/shells.rs @@ -79,8 +79,11 @@ fn a_background_command_runs_until_its_notification_or_its_stop() { assert_eq!(running(&lines), 1); lines.push(stopped(&at(6000), "bumphhsle")); assert_eq!(running(&lines), 0); - // A command's own output that only quotes such a line, and Claude Code's copies of its requests, start nothing. + // A foreground command's own output that quotes such a line, even at its start, and Claude Code's copies of its + // requests, start nothing: no notification would ever end them. lines.push(result(&at(7000), " 10 Command running in background with ID: b0po6ap81", json!({}))); + lines.push(result(&at(7000), "Command running in background with ID: example. (a line of a log it printed)", json!({ "stdout": "Command running in background with ID: example." }))); + lines.push(result(&at(7000), "Command did not complete within its 120s timeout and was moved to the background (ID: example2).", json!({}))); lines.push(json!({ "type": "api-request-blob", "timestamp": at(7000), "message": { "role": "user", "content": started(&at(1), "bq8w3e5rt").at("message").at("content").clone() }, "toolUseResult": { "backgroundTaskId": "bq8w3e5rt" } })); assert_eq!(running(&lines), 0); // A shell lives in the agent's program: one left running by the program before this one is gone with it.