diff --git a/docs/4-implementation/agent-tools/subagent.md b/docs/4-implementation/agent-tools/subagent.md index 4649dd02e..24a3ae50d 100644 --- a/docs/4-implementation/agent-tools/subagent.md +++ b/docs/4-implementation/agent-tools/subagent.md @@ -412,7 +412,7 @@ On `acp`: other value does nothing (`hive_runtime::AcpRuntime`). - the agent's permission requests get the same answers a claude subagent's tool list gives: MCP tools and file tools, `fetch` with `web_tools`, - `execute` with `execution` (`session::acp_permits`). + `execute` with `execution` (`session::run::acp_permits`). ## The tool surface a subagent gets diff --git a/hive-subagent-mcp/README.md b/hive-subagent-mcp/README.md index 5e5d8f51b..4a7d09875 100644 --- a/hive-subagent-mcp/README.md +++ b/hive-subagent-mcp/README.md @@ -16,14 +16,18 @@ its own deployable/restartable unit. One bin (`hive-subagent-daemon`, `src/main.rs`) built from the crate's own lib (`src/lib.rs`): -- **`session.rs`** — the actual claude-facing logic: `Claude::spawn` + - `RunningClaude::wait`/`cancel_handle` (not `InfiniteSession::run`, - which has no cancel handle to reach in — see the module doc for the - v1 scope this trades away), the turn-continuation loop a `goal` - switches on, and the in-memory maps that are the _only_ state this - daemon keeps (no task files — a restart stops whatever's running; - the actual claude session is the durable store, found again by name - via `hive_claude::SessionStore`). +- **`session.rs` and `session/`** — the actual claude-facing logic. The + entry file has the module doc (the v1 scope: `Claude::spawn` + + `RunningClaude::wait`/`cancel_handle` rather than `InfiniteSession::run`, + which has no cancel handle to reach in), the shared types and a table of + the parts: `session/run.rs` holds `start`, `continue_` and the loop over + a run's turns, `session/goal.rs` the goal prompts and the `goal` + switch, and `session/state.rs` the in-memory maps that are the _only_ + state this daemon keeps (no task files — a restart stops whatever's + running; the actual claude session is the durable store, found again by + name via `hive_claude::SessionStore`). `session/config.rs` and + `session/status.rs` hold the run's configuration and what `status` and + `interrupt` say. - **`mcp.rs`** — the `rmcp` tool routers (the parent's `start`/`continue`/`status`/`interrupt` on `/mcp`, the subagent's `goal_reached`/`need_help` on `/signal/mcp/`) + `serve_http`. diff --git a/hive-subagent-mcp/src/session.rs b/hive-subagent-mcp/src/session.rs index 6d32fc966..70ea351a2 100644 --- a/hive-subagent-mcp/src/session.rs +++ b/hive-subagent-mcp/src/session.rs @@ -86,6 +86,40 @@ //! and never `Killed`, and `model`/`effort` apply only as values the ACP //! session offers. +//! **Where things are.** This file keeps the types every part shares (`Slot`, +//! `StopReason`, `TurnEnd` and the rest) and re-exports the public calls: +//! +//! | module | holds | +//! | --- | --- | +//! | `state` | `State`: the claims, goals, stop reasons and signal tokens per name | +//! | `config` | the model list and the swarm cap, the claude config, prompts, the session store | +//! | `run` | `start`, `continue_`, the spawns on either runtime and the loop over a run's turns | +//! | `goal` | the goal prompts, `goal_reached`, `need_help` and the report file | +//! | `status` | `status`, `interrupt`, their wording, and the todo a turn's end pushes | +//! | `tests` | the unit tests, split by the same topics | + +mod config; +mod goal; +mod run; +mod state; +mod status; + +use self::{ + config::{ + available_models, build_config, build_store, check_model, model_list, resume_target, + subagent_cap, system_prompt_and_trigger, + }, + goal::{continuation_prompt, goal_briefing, write_stop_to_report}, + run::{acp_session_file, exit_status}, + status::{push_turn_end_todo, refused}, +}; +pub use self::{ + goal::{goal_reached, need_help}, + run::{StartRequest, continue_, start}, + state::State, + status::{interrupt, status}, +}; + use std::collections::HashMap; use std::os::unix::process::ExitStatusExt as _; use std::path::{Path, PathBuf}; @@ -353,709 +387,6 @@ fn searched_location(config: &Config) -> Option { )) } -/// This daemon's whole state: which names have a live process or a -/// reservation in flight, what each is working toward and how it stopped, -/// and where to push the completion todo. `Arc`-wrapped so the background -/// task driving a run outlives the tool call that started it. -/// -/// The map value is a `Slot`: `Starting` means `name` is reserved for an -/// in-flight `start`/`continue` that hasn't reached a confirmed spawn yet; -/// `Running` means a real turn is tracked and interruptible; `Stopping` -/// means it was interrupted and its process is still winding down. Each -/// claims the name. `Starting` closes a TOCTOU window: checking "is `name` -/// free" and committing to it are two different lock acquisitions unless -/// the check *is* the reservation — see `reserve_under`. -/// -/// `killed` is the other half of that map's story: `running` says what is in -/// flight *now*, `killed` remembers the names whose last turn ended on a -/// signal rather than on its own, keyed to the signal number. Without it a -/// killed session is indistinguishable from a finished one the moment its -/// entry leaves `running` — the whole point of this record. -/// -/// `last_event` splits `running` a second way — *in flight* against -/// *making progress*, since a wedged child is tracked exactly like a busy -/// one (`note_event` / `last_event_age`). -/// -/// ⚠️ This concurrency guard is keyed by `name` alone — a `start`/`continue` -/// for `name` with a *different* `dir` than one already in flight under -/// that name is refused as "already running," even though the two would -/// resolve to entirely separate on-disk sessions. Deliberate: `name` is the -/// caller's one chosen identity for a subagent, not `(name, dir)` — reuse a -/// name across directories at your own risk, the tool doesn't disambiguate -/// it (flagged in review when `dir` was added). -pub struct State { - running: Mutex>, - dirs: Mutex>, - killed: Mutex>, - last_event: Mutex>, - /// Turn continuation's three records. Unlike the four maps above they - /// deliberately **outlive the turn** — a stop reason that vanished with - /// the process it described would be unreadable by the time anyone - /// asked — so they're cleared by the next `start` under the same name, - /// not by a turn ending. - goals: Mutex>, - stops: Mutex>, - reports: Mutex>, - socket: PathBuf, - /// The prefix of every subagent's signal URL — this daemon's own `--http` - /// address with [`crate::mcp::SIGNAL_PATH`] on the end, and *not* a - /// reachable route by itself. It lives here because the daemon can only - /// learn it from its own `--http` argument — deriving it from a - /// convention would be the same inference the report path is careful not - /// to make. - signal_base: String, - signal_tokens: Mutex, - /// What a subagent's turns run on: claude unless [`State::on_runtime`] - /// says otherwise. - runtime: SubagentRuntime, - /// Where every subagent's output lines go up to the swarm, when this - /// agent can publish there ([`State::publishing_to`]). - term: Option, - /// Where the swarm's `subagent_models` and `max_subagents` for this agent - /// are read from, when this agent can read them - /// ([`State::reading_models_from`]). - models: Option, - /// The agent's own model list, checked when the swarm sets none: - /// [`available_models`] outside tests. - local_models: fn() -> Option, - /// Whether runs start through this binary's entry wrapper - /// ([`State::entering_runs`]). - runs_entered: bool, - /// Where each run gets its own cgroup, when this daemon was delegated - /// one. - run_cgroups: Option, - /// The `` of the next run cgroup `-`. - run_seq: AtomicU64, -} - -/// Which opaque URL segment belongs to which session — the whole of a -/// subagent's identity, as far as `goal_reached`/`need_help` are concerned. -/// -/// A subagent is told one URL, in its own `--mcp-config`, and that URL is -/// what says who it is: it has no field to name a session in and no second -/// session's URL to reach for. Both directions live under one lock because a -/// half-updated pair is exactly the state in which a token could resolve to -/// a session that has since minted another one. -#[derive(Default)] -struct SignalTokens { - /// The token currently minted for a session, so a re-mint can retire it. - by_name: HashMap, - /// The resolution the route does: token -> the session it speaks for. - by_token: HashMap, -} - -/// What a session is being continued toward, and how far through its turn -/// budget it is. Present only for a session `start`ed with a `goal`; its -/// absence is what makes a session single-turn. -struct GoalState { - /// Verbatim from `start` — re-prompted at the subagent each turn rather - /// than paraphrased, since the caller wrote it for the subagent to read. - goal: String, - /// The cap this session runs under (`start`'s `max_turns`). - max_turns: u32, - /// Turns started so far, counting the first — so the very first turn is - /// `1 of max_turns`, not `0`. - turn: u32, -} - -impl State { - /// `signal_base` is where the streamable-http endpoint a subagent's own - /// claude reaches `goal_reached`/`need_help` on *starts* — this daemon's - /// `--http` address with the signal route appended (see - /// `crate::mcp::serve_http`). Each session's actual URL is that plus its - /// own token; see `State::mint_signal_url`. - #[must_use] - pub fn new(socket: PathBuf, signal_base: String) -> Self { - Self { - running: Mutex::new(HashMap::new()), - dirs: Mutex::new(HashMap::new()), - killed: Mutex::new(HashMap::new()), - last_event: Mutex::new(HashMap::new()), - goals: Mutex::new(HashMap::new()), - stops: Mutex::new(HashMap::new()), - reports: Mutex::new(HashMap::new()), - socket, - signal_base, - signal_tokens: Mutex::new(SignalTokens::default()), - runtime: SubagentRuntime::Claude, - term: None, - models: None, - local_models: available_models, - runs_entered: false, - run_cgroups: None, - run_seq: AtomicU64::new(0), - } - } - - /// Hand every subagent's output lines to `term` as they arrive. - #[must_use] - pub fn publishing_to(mut self, term: Option) -> Self { - self.term = term; - self - } - - /// Check every named `model` against the swarm's `subagent_models`, and - /// every new run against its `max_subagents`, as `models` reads them, - /// where the swarm sets them. - #[must_use] - pub fn reading_models_from(mut self, models: Option) -> Self { - self.models = models; - self - } - - /// Start every subagent run through this binary's entry wrapper, whose - /// `main` calls `run_cgroup::exec_entry` first: at `oom_score_adj` +900 - /// always, and in its own cgroup under `cgroups` when there are any. - #[must_use] - pub fn entering_runs(mut self, cgroups: Option) -> Self { - self.runs_entered = true; - self.run_cgroups = cgroups; - self - } - - /// A new cgroup for one run of `name`; `None` without run cgroups, or - /// (logged) when creating it failed, and the run then stays in the - /// daemon's cgroup. Whatever a run left running in it (a tool child that - /// left claude's process group, which `interrupt`'s SIGINT never - /// reaches) is killed once the run has ended. - fn run_cgroup(&self, name: &str) -> Option { - let cgroups = self.run_cgroups.as_ref()?; - let n = self.run_seq.fetch_add(1, Ordering::Relaxed); - cgroups - .create(&format!("{name}-{n}")) - .inspect_err(|e| tracing::warn!(name, error = %e, "subagent: run cgroup unavailable")) - .ok() - .map(RunCgroup::killing_leftovers) - } - - /// `config` with its program started through the entry wrapper, at - /// [`RUN_OOM_SCORE_ADJ`] and inside `cgroup` if there is one; unchanged - /// without [`State::entering_runs`]. `hive-claude` builds the `Command` - /// itself and offers no `pre_exec`, hence the wrapper. - fn entered_config(&self, config: &Config, cgroup: Option<&RunCgroup>) -> Config { - let mut config = config.clone(); - if self.runs_entered { - // `hive-claude`'s own default program. - let program = config.program.take().unwrap_or_else(|| "claude".into()); - let (entry, env) = run_cgroup::entry(&program, RUN_OOM_SCORE_ADJ, cgroup); - config.program = Some(entry); - config.env.extend(env); - } - config - } - - /// [`State::entered_config`] for an ACP agent's command. - fn entered_command(&self, mut command: AcpCommand, cgroup: Option<&RunCgroup>) -> AcpCommand { - if self.runs_entered { - let (entry, env) = - run_cgroup::entry(Path::new(&command.command), RUN_OOM_SCORE_ADJ, cgroup); - command.command = entry.to_string_lossy().into_owned(); - command.env.extend(env); - } - command - } - - /// Read the swarm's keys once: refresh this agent's permissions (the - /// tools the subagent about to run gets), refuse a `model` outside the list - /// in effect for this agent (see `check_model`), and return the subagent - /// cap in effect (see `subagent_cap`). - async fn swarm_limits(&self, model: Option<&str>) -> anyhow::Result> { - let read = match &self.models { - Some(reader) => { - reader.refresh_permissions().await; - Some(reader.read().await) - } - None => None, - }; - let agent = self - .models - .as_ref() - .map_or("", crate::swarm_models::Reader::agent); - let cap = subagent_cap(read.as_ref(), agent); - if model.is_some() { - check_model(model, &model_list(read, (self.local_models)()))?; - } - Ok(cap) - } - - /// Run every subagent on `runtime` — the daemon passes the parent - /// agent's, read from its environment at startup. On ACP this resolves - /// the harness dir, which only exists inside a container. - #[must_use] - pub fn on_runtime(mut self, runtime: RuntimeSpec) -> Self { - self.runtime = match runtime { - RuntimeSpec::Claude => SubagentRuntime::Claude, - RuntimeSpec::Acp(command) => SubagentRuntime::Acp { - command, - sessions: crate::paths::harness_dir(), - }, - }; - self - } - - /// Mint `name` a fresh signal URL: an unguessable token appended to - /// [`State::signal_base`], resolvable back to this one session and to no - /// other. Called once per spawned run, and the result goes into exactly - /// one place — that subagent's own `--mcp-config` (`crate::mcp_config`). - /// - /// A v4 UUID's 122 bits come from the OS CSPRNG, so the segment is not - /// derived from the name, the port or anything else a sibling subagent - /// could compute; a subagent that wants to signal as somebody else has - /// nothing to guess *from*. Minting replaces any token the name held - /// before, which is what stops a name's old URL surviving the run it was - /// issued for. - pub(crate) fn mint_signal_url(&self, name: &str) -> String { - let token = uuid::Uuid::new_v4().simple().to_string(); - let mut tokens = self - .signal_tokens - .lock() - .unwrap_or_else(PoisonError::into_inner); - if let Some(previous) = tokens.by_name.insert(name.to_owned(), token.clone()) { - tokens.by_token.remove(&previous); - } - tokens.by_token.insert(token.clone(), name.to_owned()); - drop(tokens); - format!("{}/{token}", self.signal_base) - } - - /// Which session an incoming signal request speaks for, or `None` for a - /// token this daemon never minted or has since revoked — which the route - /// answers with a bare 404 (see `crate::mcp::serve_http`). `None` is the - /// only failure shape there is: nothing about the answer distinguishes - /// "never existed" from "that run is over", so a caller holding a wrong - /// token learns nothing from being refused. - pub(crate) fn session_for_signal_token(&self, token: &str) -> Option { - self.signal_tokens - .lock() - .unwrap_or_else(PoisonError::into_inner) - .by_token - .get(token) - .cloned() - } - - /// Retire `name`'s signal URL — its run is over (or never started), so - /// the route it was handed stops resolving and answers 404 from here on. - /// This is the expiry half of "unknown or expired token ⇒ 404": without - /// it a finished subagent's config file would still name a live route. - fn revoke_signal_token(&self, name: &str) { - let mut tokens = self - .signal_tokens - .lock() - .unwrap_or_else(PoisonError::into_inner); - if let Some(token) = tokens.by_name.remove(name) { - tokens.by_token.remove(&token); - } - } - - /// Which [`Slot`] `name` is in; `None` with nothing tracked under it. - fn occupancy(&self, name: &str) -> Option { - self.running - .lock() - .unwrap_or_else(PoisonError::into_inner) - .get(name) - .map(|slot| match slot { - Slot::Starting => Occupancy::Starting, - Slot::Running(_) => Occupancy::Running, - Slot::Stopping => Occupancy::Stopping, - }) - } - - /// Atomically claim `name` for an in-flight start/continue: check - /// "is anything tracked under this name" and "commit to this call - /// owning it" in the *same* lock acquisition, so two calls racing the - /// same name can't both pass a check before either commits (the exact - /// same-name concurrent-run hazard this module's doc warns about). - /// Refuses (reserving nothing) a `name` already tracked, or any name - /// once `cap` names are tracked. The count is checked under the same - /// lock, so two racing calls can't both take the last place. - /// - /// Every tracked name counts toward `cap`, a goal run between turns - /// and an interrupted one still winding down included: each holds a - /// process or is about to. A goal's next turn never comes through here, - /// so a run already counted is never refused its re-prompt. - fn reserve_under(&self, name: &str, cap: Option) -> Result<(), Refusal> { - let mut running = self.running.lock().unwrap_or_else(PoisonError::into_inner); - if running.contains_key(name) { - return Err(Refusal::Taken); - } - if let Some(cap) = cap - && running.len() >= usize::try_from(cap).unwrap_or(usize::MAX) - { - return Err(Refusal::AtCap { - running: running.len(), - cap, - }); - } - running.insert(name.to_owned(), Slot::Starting); - tracing::info!(name, "subagent name reserved"); - Ok(()) - } - - /// [`State::reserve_under`] with no cap: `false` if `name` is taken. - #[cfg(test)] - fn reserve(&self, name: &str) -> bool { - self.reserve_under(name, None).is_ok() - } - - /// Release a reservation that never made it to a real spawn (an error - /// on the slow path between `reserve_under` and `Claude::spawn` succeeding). - /// A no-op if the entry was already upgraded to `Running` — this only - /// ever clears a still-`Starting` placeholder, never a live process. - /// - /// The signal token the failed call minted goes with it: no process ever - /// read that URL, and a token outliving the call that minted it is the - /// one way a route could resolve to a session that isn't there. - fn release_reservation(&self, name: &str) { - let mut running = self.running.lock().unwrap_or_else(PoisonError::into_inner); - let released = matches!(running.get(name), Some(Slot::Starting)); - if released { - running.remove(name); - tracing::info!(name, "subagent reservation released: the spawn failed"); - } - drop(running); - // Only alongside a reservation this actually released: a call that - // found a live process left it running, and revoking that run's URL - // would cut off a subagent which is still using it. - if released { - self.revoke_signal_token(name); - } - } - - /// Retire the finished turn's tracking for `name` and remember how it - /// ended: a `Killed` end is recorded so `status`, the end-of-turn todo - /// and a later `continue` can all say so; any other end clears a stale - /// record from an earlier turn. - /// - /// The kill is recorded *before* the `running` entry goes away, so there - /// is no instant in which `name` is neither running nor known-killed — - /// a `status` landing between the two would otherwise read the session - /// as plainly idle, which is the exact confusion this record exists to - /// remove. - /// - /// The liveness clock goes with the `running` entry, for the same reason - /// it's kept at all: it answers "is this turn still making progress", - /// and a turn that has ended has no progress left to make. - /// - /// So does the session's signal token. Every caller of this is a point - /// where the *run* stops — a continued run's own turn boundary goes - /// through `between_turns` instead, and keeps its URL because the next - /// turn is the same subagent against the same rendered config. Revoking - /// here is what makes a signal for a session that already ended a 404 - /// rather than a late stop reason recorded against it. - fn finish_turn(&self, name: &str, end: &TurnEnd) { - if let Some(term) = &self.term { - term.finished(name, exit_status(end)); - } - self.revoke_signal_token(name); - let mut killed = self.killed.lock().unwrap_or_else(PoisonError::into_inner); - match end { - TurnEnd::Killed { signal } => killed.insert(name.to_owned(), *signal), - TurnEnd::Complete | TurnEnd::Failed(_) => killed.remove(name), - }; - drop(killed); - self.running - .lock() - .unwrap_or_else(PoisonError::into_inner) - .remove(name); - self.last_event - .lock() - .unwrap_or_else(PoisonError::into_inner) - .remove(name); - tracing::info!(name, "subagent name freed: the run ended"); - } - - /// Tell the swarm `name`'s run began, with the model and effort `info` - /// names. The end is reported by `finish_turn`, which every run's end goes - /// through; the gaps between a goal run's turns are not an end. - fn announce_running(&self, name: &str, info: &Arc) { - if let Some(term) = &self.term { - term.running(name, info); - } - } - - /// The signal `name`'s last turn died on, if it died on one. - fn killed_by(&self, name: &str) -> Option { - self.killed - .lock() - .unwrap_or_else(PoisonError::into_inner) - .get(name) - .copied() - } - - /// Forget that `name`'s last turn was killed — called once a new turn is - /// confirmed spawned, since the record describes the turn before it and - /// would otherwise keep flagging a session that has since run again. - fn clear_kill(&self, name: &str) { - self.killed - .lock() - .unwrap_or_else(PoisonError::into_inner) - .remove(name); - } - - /// `name`'s turn just produced output — record *when*, and nothing else. - /// Called from `LivenessSink` for every line of every stream, so it runs - /// far more often than anything else in this type and stays a single - /// map write for that reason. - /// - /// A monotonic [`Instant`], not a wall clock: what's ever read back out - /// is an elapsed age, which a clock adjustment must not be able to - /// distort into a stall that never happened. - /// - /// Also called by `spawn_and_track` the moment each turn's child exists, - /// so the clock starts at the spawn rather than at the first line. - /// Without that seed a subagent that wedged before emitting anything at - /// all would report no age forever — the one case where an age is most - /// worth having. The value therefore reads as "how long since the daemon - /// last heard anything from this child", counting the spawn itself as - /// the first thing it heard. A continued run re-seeds it per turn, for - /// the same reason: the age describes the turn in flight, not the run. - fn note_event(&self, name: &str) { - self.last_event - .lock() - .unwrap_or_else(PoisonError::into_inner) - .insert(name.to_owned(), Instant::now()); - } - - /// How long since `name`'s turn last produced output. `None` once the - /// turn is over (`finish_turn` drops the entry) or for a name that never - /// reached a spawn — in both cases there's no *running* turn whose - /// progress the age would describe, and a leftover age from a turn that - /// has already ended would read as a stall that isn't one. - fn last_event_age(&self, name: &str) -> Option { - self.last_event - .lock() - .unwrap_or_else(PoisonError::into_inner) - .get(name) - .map(Instant::elapsed) - } - - /// An explicit `dir` is remembered against `name` and returned as-is; an - /// omitted one (`None`) falls back to whatever was last remembered for - /// `name`, so a `start` that gave a `dir` doesn't force every later - /// `continue`/`status` against the same name to repeat it. Explicit - /// always wins and updates the memory — there's no way to say "forget - /// it, use the default" once something's been remembered short of - /// giving a genuinely different `dir`, a deliberate simplicity trade, - /// not an oversight. In-memory only, same durability envelope as - /// `running`: a daemon restart forgets it same as it forgets everything - /// else here — the caller re-supplies `dir` once, same as it always - /// could. - /// - /// ⚠️ **Callers must only call this once the call is known to proceed** - /// — after `reserve_under` in `start`, after the session lookup in a - /// `continue` (`begin_continue`) — so a refused call never changes what - /// a later bare `continue` resolves to. `peek_dir` is the non-committing - /// variant for a call that might still be refused, or that shouldn't - /// persist its `dir` at all, like `status`. - fn resolve_dir(&self, name: &str, dir: Option<&str>) -> Option { - let mut dirs = self.dirs.lock().unwrap_or_else(PoisonError::into_inner); - match dir { - Some(d) => { - dirs.insert(name.to_owned(), d.to_owned()); - Some(d.to_owned()) - } - None => dirs.get(name).cloned(), - } - } - - /// Same resolution as `resolve_dir` (explicit wins, omitted falls back - /// to the remembered value) but never writes — for a call that must not - /// change what a later bare `continue`/`status` resolves to. `status`'s - /// own doc offers `dir` as a one-off "check a different directory" - /// knob; if that call committed the same way `start`/`continue_` do, the - /// one-off peek would silently become the new remembered default (the - /// second bug argus flagged in the same review). - fn peek_dir(&self, name: &str, dir: Option<&str>) -> Option { - match dir { - Some(d) => Some(d.to_owned()), - None => self - .dirs - .lock() - .unwrap_or_else(PoisonError::into_inner) - .get(name) - .cloned(), - } - } - - /// Upgrade `name`'s `Starting` reservation to a real, interruptible - /// process. Same key as the reservation, so there is no window in which - /// `name` reads as unoccupied between the two. - fn track(&self, name: &str, stop: TurnStop) { - self.running - .lock() - .unwrap_or_else(PoisonError::into_inner) - .insert(name.to_owned(), Slot::Running(stop)); - tracing::info!(name, "subagent process tracked"); - } - - /// Drop `name`'s cancel handle but keep the name claimed — the moment - /// between a continued turn's child exiting and its successor being - /// spawned. Without it the name would read as free mid-loop and a - /// concurrent `start` could take it out from under the continuation; - /// with it, `status` says "starting" and `interrupt` says "still - /// starting, retry shortly", both of which are true of the sub-second - /// gap it covers. - fn between_turns(&self, name: &str) { - self.running - .lock() - .unwrap_or_else(PoisonError::into_inner) - .insert(name.to_owned(), Slot::Starting); - tracing::info!(name, "subagent name held between goal turns"); - } - - /// Set (or clear) `name`'s goal and start its turn budget over at turn - /// one. Called by `start` only: the goal is a property of the session - /// being created, and a later `continue` re-prompts toward whatever - /// `start` set rather than redefining it. - fn set_goal(&self, name: &str, goal: Option, max_turns: u32) { - let mut goals = self.goals.lock().unwrap_or_else(PoisonError::into_inner); - match goal { - Some(goal) => { - goals.insert( - name.to_owned(), - GoalState { - goal, - max_turns, - turn: 1, - }, - ); - } - None => { - goals.remove(name); - } - } - } - - /// Put `name` back at turn one, keeping whatever goal `start` set. A - /// `continue` is the parent's own deliberate turn, and the cap exists to - /// bound *unattended* continuation — so its allowance starts over rather - /// than a capped session being permanently un-continuable. The parent - /// was always the authority on whether more turns are worth spending. - fn restart_turns(&self, name: &str) { - if let Some(goal) = self - .goals - .lock() - .unwrap_or_else(PoisonError::into_inner) - .get_mut(name) - { - goal.turn = 1; - } - } - - /// Commit a `continue` whose session has been found: remember its `dir` - /// (see `resolve_dir`), drop the stop reason that described the run - /// before it, and give a goal session its allowance back (see - /// `restart_turns`). - fn begin_continue(&self, name: &str, dir: Option<&str>) { - self.resolve_dir(name, dir); - self.clear_stop(name); - self.restart_turns(name); - } - - /// `(turn, max_turns)` for `name`. `None` for a session with no goal, - /// which has no turn budget to be partway through — reporting `1 of 1` - /// there would invent a cap that isn't enforced. - fn turns(&self, name: &str) -> Option<(u32, u32)> { - self.goals - .lock() - .unwrap_or_else(PoisonError::into_inner) - .get(name) - .map(|g| (g.turn, g.max_turns)) - } - - /// Record why `name` stopped. Idempotent by design: the subagent's own - /// signal lands here mid-turn and the loop re-records the same reason at - /// the turn's end, so both paths can write without checking. - fn record_stop(&self, name: &str, stop: StopReason) { - self.stops - .lock() - .unwrap_or_else(PoisonError::into_inner) - .insert(name.to_owned(), stop); - } - - fn stop_reason(&self, name: &str) -> Option { - self.stops - .lock() - .unwrap_or_else(PoisonError::into_inner) - .get(name) - .cloned() - } - - /// Forget why `name` last stopped — called when a new turn is starting, - /// since the record describes the run before it and would otherwise make - /// a session that has since been given another turn still read as - /// blocked or out of turns. - fn clear_stop(&self, name: &str) { - self.stops - .lock() - .unwrap_or_else(PoisonError::into_inner) - .remove(name); - } - - /// Remember where `name` writes its report, so a stop reason can be - /// appended to the artifact a parent already reads rather than living - /// only in a todo. `None` leaves whatever was remembered alone, so a - /// signal tool that doesn't name a path doesn't erase the one `start` - /// gave. - /// - /// Never inferred: `start` carries what the brief named, and the signal - /// tools carry where the subagent says it actually wrote. A daemon that - /// derived this from a path convention would be guessing about someone - /// else's layout. - fn set_report_file(&self, name: &str, path: Option<&str>) { - if let Some(path) = path { - self.reports - .lock() - .unwrap_or_else(PoisonError::into_inner) - .insert(name.to_owned(), PathBuf::from(path)); - } - } - - /// Forget `name`'s report path — a fresh `start` under the same name is - /// a different piece of work, and inheriting the last one's artifact - /// path would append its stop reason to a file this run never wrote. - fn clear_report_file(&self, name: &str) { - self.reports - .lock() - .unwrap_or_else(PoisonError::into_inner) - .remove(name); - } - - fn report_file(&self, name: &str) -> Option { - self.reports - .lock() - .unwrap_or_else(PoisonError::into_inner) - .get(name) - .cloned() - } - - /// What the continuation loop does after a turn that ran to completion: - /// stop with a reason, or spend another turn re-prompting toward the - /// goal. Advances the turn counter itself, since deciding to continue - /// and consuming a turn are the same act. - /// - /// A signal the subagent raised mid-turn is already in `stops` and wins - /// outright — that is what "both stop goal continues" means, and it's - /// checked before the goal so a `goal_reached` on the last allowed turn - /// reads as reached rather than as capped. - fn plan_after_turn(&self, name: &str) -> Continuation { - if let Some(stop) = self.stop_reason(name) { - return Continuation::Stop(stop); - } - let mut goals = self.goals.lock().unwrap_or_else(PoisonError::into_inner); - let Some(state) = goals.get_mut(name) else { - return Continuation::Stop(StopReason::Done); - }; - if state.turn >= state.max_turns { - return Continuation::Stop(StopReason::TurnCap { turns: state.turn }); - } - state.turn += 1; - Continuation::Continue { - prompt: continuation_prompt(name, &state.goal, state.turn, state.max_turns), - } - } -} - /// `plan_after_turn`'s answer: the loop either stops with a reason to /// report, or has the next turn's prompt ready to spawn against. #[derive(Debug, PartialEq, Eq)] @@ -1073,4534 +404,10 @@ fn validate_name(name: &str) -> anyhow::Result<()> { .map_err(|e| anyhow::anyhow!("invalid subagent name {name:?}: {e}")) } -/// Env var carrying the nix-configured `services.hyperhive.agent.availableModels` as a -/// comma-separated list, forwarded onto this daemon's unit by -/// `nix/agent-modules/mcp.nix` from the harness unit. -const AVAILABLE_MODELS_ENV: &str = "HIVE_AVAILABLE_MODELS"; - -/// The models this daemon may spawn a subagent on, from -/// [`AVAILABLE_MODELS_ENV`]. `None` when the var is absent. -fn available_models() -> Option { - std::env::var(AVAILABLE_MODELS_ENV).ok() -} - -/// The list a named `model` is checked against. -#[derive(Debug, PartialEq, Eq)] -enum ModelList { - /// The swarm's `subagent_models` for this agent. - Swarm(Vec), - /// [`AVAILABLE_MODELS_ENV`]; `None` when the var is absent. - Local(Option), -} - -/// The swarm's list when it sets one, else `local`. `read` is `None` when -/// this daemon has no swarm queue to read from; a failed read is logged and -/// falls back to `local`. -fn model_list(read: Option, local: Option) -> ModelList { - use crate::swarm_models::Read; - match read { - Some(Read::Current(AgentInference { - subagent_models: Some(models), - .. - })) => ModelList::Swarm(models), - Some(Read::Failed(error)) => { - tracing::warn!( - %error, - "reading this agent's subagent_models from the swarm failed; checking against \ - {AVAILABLE_MODELS_ENV}" - ); - ModelList::Local(local) - } - Some(Read::Current(_)) | None => ModelList::Local(local), - } -} - -/// The swarm's `max_subagents` for this agent, or `None`, no cap: when it -/// sets none, when `read` is `None` because this daemon has no swarm queue, -/// or when the read failed, which is logged as a warning naming the agent and the error. -fn subagent_cap(read: Option<&crate::swarm_models::Read>, agent: &str) -> Option { - use crate::swarm_models::Read; - match read? { - Read::Current(settings) => settings.max_subagents, - Read::Failed(error) => { - tracing::warn!( - agent, - %error, - "reading this agent's subagent settings from the swarm failed; applying no \ - subagent cap" - ); - None - } - } -} - -/// Refuse a `model` the operator hasn't made available to this agent. -/// -/// Default-open on purpose: this is a safety rail, not a security boundary, -/// so an absent list (or one naming nothing) restricts nothing and an -/// agent deployed before this gate existed keeps working unchanged. A `None` -/// model isn't a choice of model either — it lets claude fall back to its own -/// default — so there is nothing to check. -/// -/// # Errors -/// -/// A named model absent from `list`; the message names it, every permitted -/// one and where the list came from, since it is all the caller sees. -fn check_model(model: Option<&str>, list: &ModelList) -> anyhow::Result<()> { - let Some(model) = model else { - return Ok(()); - }; - let (allowed, source): (Vec<&str>, &str) = match list { - ModelList::Swarm(models) => ( - models - .iter() - .map(|m| m.trim()) - .filter(|m| !m.is_empty()) - .collect(), - "the swarm's subagent_models for this agent", - ), - ModelList::Local(None) => return Ok(()), - // Split, trim, skip empty tokens. - ModelList::Local(Some(env)) => ( - env.split(',') - .map(str::trim) - .filter(|token| !token.is_empty()) - .collect(), - AVAILABLE_MODELS_ENV, - ), - }; - if allowed.is_empty() - || allowed - .iter() - .any(|entry| entry.eq_ignore_ascii_case(model.trim())) - { - return Ok(()); - } - anyhow::bail!( - "model `{model}` is not available to this agent — {source} permits: {}", - allowed.join(", ") - ); -} - -/// Extend the ambient `OTEL_RESOURCE_ATTRIBUTES` with a `subagent=` -/// attribute, so every token/cost/tool-call data point this subagent's own -/// claude process emits carries it alongside the parent's `agent=` -/// label. `Config.env` applies after the inherited environment, so this one -/// entry overriding the ambient value is the intended shape, not a -/// wholesale replacement. -fn subagent_otel_attrs(name: &str) -> String { - match std::env::var("OTEL_RESOURCE_ATTRIBUTES") { - Ok(existing) if !existing.is_empty() => format!("{existing},subagent={name}"), - _ => format!("subagent={name}"), - } -} - -/// Build the `Config` one subagent turn runs against. `model` maps straight -/// onto `Config::model` — `--model`, omitted when `None` so claude falls -/// back to its own default. `effort` does not: an omitted `effort` defaults -/// to `"medium"` here rather than falling through to claude's own default -/// (`high` on most models) — a deliberate hive policy for subagent work -/// specifically, not a reflection of Anthropic's own recommendation, on the -/// same "cheaper than you" cost-consciousness the `base:claude-subagents` -/// skill already asks of `model`. `prompt_file`, when given, becomes -/// `--append-system-prompt-file` — the subagent's task instructions. -/// `dir`, when given, becomes `Config::cwd` (e.g. a prepared worktree); `None` -/// is [`crate::paths::default_cwd`]. -/// Always `--dangerously-skip-permissions --strict-mcp-config --tools` — two -/// gates covering one half each, neither substituting for the other: -/// `strict_mcp_config` over **MCP** tools (no ambient discovery, so exactly -/// what [`crate::mcp_config::build`] renders), `--tools` over **built-in** -/// ones, via [`hive_sh4re::permissions::subagent_builtin_tools_for`] over the -/// agent's permissions ([`crate::swarm_models::permissions_now`]), which -/// documents its one `Bash` exception. `--tools` does not filter `mcp__*`, -/// so the signal tools are unnamed in it (`docs/4-implementation/agent-tools/subagent.md`). -/// -/// `signal_url` is what makes `goal_reached`/`need_help` callable at all: a -/// subagent reaches them over the same streamable-http listener its parent -/// uses, on a route that serves those two tools and nothing else, so being -/// able to say "I'm done" never carries the ability to spawn a subagent of -/// its own. It is also *this* session's own URL — minted per run by -/// [`State::mint_signal_url`] and written only into this session's config -/// file — which is where the signal tools get the identity they no longer -/// ask the caller for. `None` — which only `status` passes, building a -/// config purely to resolve the session store — leaves the surface out -/// entirely. -fn build_config( - name: &str, - model: Option, - effort: Option, - prompt_file: Option<&str>, - dir: Option<&str>, - signal_url: Option<&str>, -) -> Config { - let tools = hive_sh4re::permissions::subagent_builtin_tools_for( - &crate::swarm_models::permissions_now(), - ) - .join(","); - // Refuse to spawn on an empty `--tools` rather than reason about what it - // would do: what an empty value means is disputed and depends on the - // installed claude release (see `builtin_tools_for`). Nothing here wants - // "a subagent with no built-ins" anyway, so an empty resolution is a bug - // either way, and failing on it is safe under every reading. - assert!( - !tools.is_empty(), - "resolved an empty --tools value — a subagent is never spawned on one, \ - since what an empty value grants is release-dependent" - ); - let mut extra_args = vec![ - "--dangerously-skip-permissions".to_owned(), - "--tools".to_owned(), - tools, - ]; - if let Some(path) = prompt_file { - extra_args.push("--append-system-prompt-file".to_owned()); - extra_args.push(path.to_owned()); - } - Config { - model, - effort: Some(effort.unwrap_or_else(|| "medium".to_owned())), - cwd: dir.map(PathBuf::from).or_else(crate::paths::default_cwd), - mcp_config: crate::mcp_config::build(name, signal_url), - strict_mcp_config: true, - extra_args, - env: vec![( - "OTEL_RESOURCE_ATTRIBUTES".to_owned(), - subagent_otel_attrs(name), - )], - ..Default::default() - } -} - -/// Which file `--append-system-prompt-file` is pointed at, if any, and the -/// prompt this turn actually opens with, for one spawn. -/// -/// **The task is always the turn, never a standing system prompt — with or -/// without a role.** A task baked into the system prompt re-asserts itself -/// as an instruction on every later turn of the session (`continue`, -/// `goal`), not just the one the caller wrote it for; the system prompt is -/// the subagent's standing identity, not a one-shot channel. So the task -/// instructions (`prompt_file`) are always read and folded ahead of -/// `trigger` instead, the one channel that has always carried them. -/// -/// No role: that folded trigger is the whole story — `None` comes back for -/// the system-prompt file, since there is no role text to put there. -/// A role: its text, alone, becomes the system-prompt file under -/// [`crate::paths::harness_dir`] — nothing about the task reaches it. -/// Per session, like the generated `--mcp-config` beside it, so two -/// concurrent `start`s never share a system-prompt file. -/// -/// # Errors -/// -/// Unreadable task instructions, or (with a role) a harness dir that -/// cannot be written. Both refuse the spawn rather than dropping either -/// half — see `docs/4-implementation/agent-tools/subagent.md`. -fn system_prompt_and_trigger( - name: &str, - role: Option<&str>, - prompt_file: &str, - trigger: &str, -) -> anyhow::Result<(Option, String)> { - // `harness_dir` panics outside a container (`HYPERHIVE_HARNESS_DIR` - // unset) — read lazily, only when a role means a system-prompt file - // actually needs somewhere to land. `compose_prompt` only touches `dir` - // inside its `Some(role)` branch, so a no-role call never forces this, - // in tests or otherwise. - let dir = role.map_or_else(PathBuf::new, |_| crate::paths::harness_dir()); - compose_prompt(&dir, name, role, prompt_file, trigger) -} - -/// [`system_prompt_and_trigger`] with the harness dir as an argument rather -/// than an ambient container-only environment read — the split a test uses -/// to control where the role-only file lands. -/// -/// # Errors -/// -/// See [`system_prompt_and_trigger`]. -fn compose_prompt( - dir: &Path, - name: &str, - role: Option<&str>, - prompt_file: &str, - trigger: &str, -) -> anyhow::Result<(Option, String)> { - let task = std::fs::read_to_string(prompt_file).map_err(|e| { - anyhow::anyhow!("reading the task instructions at {prompt_file} failed: {e}") - })?; - let trigger = format!("{}\n\n{trigger}", task.trim_end()); - let Some(role) = role else { - return Ok((None, trigger)); - }; - let path = render_role_prompt(dir, name, role)?; - Ok((Some(path), trigger)) -} - -/// Write `name`'s system-prompt file — `role`'s text, alone — into `dir`, -/// returning the file's path. Split from [`compose_prompt`] so the -/// directory is an argument rather than an ambient container-only -/// environment read. -/// -/// # Errors -/// -/// A `dir` that cannot be created or written. -fn render_role_prompt(dir: &Path, name: &str, role: &str) -> anyhow::Result { - std::fs::create_dir_all(dir) - .map_err(|e| anyhow::anyhow!("creating {} failed: {e}", dir.display()))?; - let path = dir.join(format!("subagent-system-prompt-{name}.md")); - std::fs::write(&path, role) - .map_err(|e| anyhow::anyhow!("writing {} failed: {e}", path.display()))?; - Ok(path) -} - -/// The [`SessionStore`] a subagent's turn actually runs against — same -/// resolution `hive_claude::Claude` itself uses, so a lookup here can't -/// disagree with what the driver does a moment later. -fn build_store(config: &Config) -> std::io::Result { - Ok(SessionStore::new( - config.resolved_claude_home()?, - config.resolved_cwd()?, - )) -} - -/// The session id a resume of `name` hands `--resume`: the live session -/// titled `name` in `config`'s own project dir. -/// -/// claude resolves a *title* across the project dirs of every git worktree -/// of the repo, and refuses when more than one matches; `start` archives only -/// in its own cwd, so a name reused under a sibling worktree's `dir` stays -/// live there. An id names one file, and a name is never handed over in its -/// place: a session that is not in this dir is refused, not looked for -/// elsewhere. -/// -/// # Errors -/// -/// A store that cannot be resolved, or a project dir with no session titled -/// `name`; either message names what was searched. -fn resume_target(config: &Config, name: &str) -> anyhow::Result { - let store = build_store(config) - .map_err(|e| anyhow::anyhow!("no session titled `{name}` can be looked for: {e}"))?; - store - .find_by_title(name) - .and_then(|path| path.file_stem().map(|id| id.to_string_lossy().into_owned())) - .ok_or_else(|| { - anyhow::anyhow!( - "no session titled `{name}` under {}; pass the `dir` the session was started in", - store.project_dir().display() - ) - }) -} - -/// Everything a `start` needs, as one struct rather than a parameter list: -/// the call already carried six mostly-optional values before goals were -/// added, and nine positional arguments is both unreadable at the call site -/// and a lint. -pub struct StartRequest { - /// Session name — the tracking key and claude's own session title. - pub name: String, - pub model: Option, - pub effort: Option, - /// File holding the subagent's task instructions. - pub prompt_file: String, - /// Which named role this subagent runs as — a file in this agent's own - /// role directory, named without its extension. `None` is the - /// pre-role shape: the task instructions alone. A name with no file - /// refuses the whole `start` (see [`crate::role`]). - pub role: Option, - /// The first turn's prompt. A goal, when given, is appended to it. - pub trigger: String, - /// Working directory for the session; `None` means the agent's work dir when it - /// exists, else the daemon's cwd. - pub dir: Option, - /// What this session is being continued *toward*. `None` keeps the - /// pre-continuation shape: one turn, one todo, no re-prompting. - pub goal: Option, - /// Turn cap for the continuation, defaulting to `DEFAULT_MAX_TURNS`. - /// Ignored without a `goal`, which is what continuation continues - /// toward — there is nothing to re-prompt against otherwise. - pub max_turns: Option, - /// Where this session's brief told it to write its report, so the stop - /// reason can be appended to that artifact. Never inferred — see - /// `State::set_report_file`. - pub report_file: Option, -} - -/// Start a fresh subagent under `name`. A prior *finished* session under -/// the same name is archived first (so this is a real fresh start, not a -/// silent resume of old history) — a *currently running* one is refused -/// outright, since `hive_claude::InfiniteSession`'s own docs warn that two -/// concurrent runs against the same name corrupt both. -/// -/// With a `goal` set this starts a whole *run*, not a single turn: see -/// `spawn_and_track` for the continuation loop. The return is unchanged -/// either way — it reports the first turn's spawn, not the run's outcome. -/// -/// # Errors -/// -/// A name already running, an invalid name, a `model` the operator hasn't -/// made available (see `check_model`), this agent at its subagent cap (see -/// `subagent_cap`), an archive failure, or the -/// underlying `Claude::spawn` failing (binary missing, etc.) — the last -/// case is the only one that can happen *after* commit-to-run, and it's -/// exactly why nothing is registered in `running` until spawn actually -/// succeeds. -pub async fn start(state: &Arc, req: StartRequest) -> anyhow::Result { - let name = req.name.as_str(); - validate_name(name)?; - let cap = state.swarm_limits(req.model.as_deref()).await?; - // Before `reserve_under`, so a role this agent does not have costs the caller - // an error and nothing else: no name claimed, no session archived, no - // process spawned. - let role = req.role.as_deref().map(crate::role::load).transpose()?; - if let Err(refusal) = state.reserve_under(name, cap) { - return Err(refused( - state, - name, - &refusal, - "use `continue` or `interrupt`", - )); - } - // Only commit the remembered `dir` now that `reserve_under` has actually - // claimed `name` — see `resolve_dir`'s doc for why the order matters, - // and the same reasoning governs the three records below it. - let dir = state.resolve_dir(name, req.dir.as_deref()); - // A fresh start owns none of the previous run's records: its goal, its - // turn budget, why it stopped and where it wrote are all about work this - // call is deliberately replacing. - state.clear_stop(name); - state.clear_report_file(name); - state.set_report_file(name, req.report_file.as_deref()); - let max_turns = req.max_turns.unwrap_or(DEFAULT_MAX_TURNS).max(1); - state.set_goal(name, req.goal.clone(), max_turns); - let trigger = match req.goal.as_deref() { - None => req.trigger, - Some(goal) => format!("{}{}", req.trigger, goal_briefing(name, goal, max_turns)), - }; - let result = start_reserved( - state, - name, - SpawnSpec { - model: req.model, - effort: req.effort, - prompt_file: req.prompt_file, - role, - }, - &trigger, - dir.as_deref(), - ); - if result.is_err() { - state.release_reservation(name); - } - result -} - -/// How one spawn is shaped, as against which session it is for: the four -/// values `start` has already resolved by the time it commits to running. -/// A struct rather than four more parameters — the role made -/// `start_reserved`'s list long enough to be both unreadable and a lint, -/// the same reason [`StartRequest`] exists. -struct SpawnSpec { - model: Option, - effort: Option, - /// The caller's task-instruction file, as given. - prompt_file: String, - /// The named role's *text*, already loaded — `start` reads it before - /// reserving the name, so an unknown role never gets this far. - role: Option, -} - -/// The slow, fallible part of `start`, run only after `reserve_under` has -/// already closed the TOCTOU window — split out so `start` can release the -/// reservation on any error path here without duplicating that logic per -/// failure site. -fn start_reserved( - state: &Arc, - name: &str, - spec: SpawnSpec, - trigger: &str, - dir: Option<&str>, -) -> anyhow::Result { - let signal_url = state.mint_signal_url(name); - let (system_prompt, trigger) = - system_prompt_and_trigger(name, spec.role.as_deref(), &spec.prompt_file, trigger)?; - let system_prompt = system_prompt.map(|p| p.to_string_lossy().into_owned()); - let config = build_config( - name, - spec.model, - spec.effort, - system_prompt.as_deref(), - dir, - Some(&signal_url), - ); - start_on_runtime( - state, - name, - config, - system_prompt.map(PathBuf::from), - trigger, - ) -} - -/// Archive any prior session under `name` and spawn a fresh run on the -/// daemon's runtime. `system_prompt` is the role file `config` already -/// hands claude; ACP has no system prompt, so it goes to the ACP runtime, -/// which puts it in front of the session's first prompt. -fn start_on_runtime( - state: &Arc, - name: &str, - config: Config, - system_prompt: Option, - trigger: String, -) -> anyhow::Result { - if let SubagentRuntime::Acp { command, sessions } = &state.runtime { - let cgroup = state.run_cgroup(name); - let runtime = acp_runtime( - state.entered_command(command.clone(), cgroup.as_ref()), - sessions, - name, - ); - if let Some(archived) = runtime - .archive() - .map_err(|e| anyhow::anyhow!("archiving the prior `{name}` session failed: {e}"))? - { - tracing::info!( - name, - archived = %archived.display(), - "start: archived a finished prior session for a fresh start" - ); - } - let config = Config { - system_prompt_file: system_prompt, - ..config - }; - return spawn_and_track_acp(state, name, runtime, cgroup, config, trigger, None); - } - let store = build_store(&config)?; - if store.find_by_title(name).is_some() { - tracing::info!( - name, - "start: archiving a finished prior session for a fresh start" - ); - store - .archive_by_title(name) - .map_err(|e| anyhow::anyhow!("archiving the prior `{name}` session failed: {e}"))?; - } - // No verdict channel: a `start` creates its session, so there is no - // resume to miss and nothing for the caller to wait on past the spawn — - // see `spawn_and_track`'s doc. - spawn_and_track( - state, - name, - &config, - &Attach::Create(name.to_owned()), - trigger, - None, - ) -} - -/// Give an existing named session a new turn — resuming it whether that -/// means "the previous turn finished, here's the next instruction" or "the -/// daemon restarted, reattaching." Refuses a name already running. -/// -/// A name with no session titled it in the project dir of the `dir` in -/// effect is refused before anything spawns, naming the directory searched -/// (`resume_target`): the session is only ever resumed by its id, from that -/// dir. A turn that still misses — the session vanished between the lookup -/// and the spawn — comes back as this call's own `Err` too, because -/// `continue` waits for the driver's answer instead of returning ahead of it -/// (`classify_end`). A `continue` that reports "started" therefore means the -/// turn started. See `await_resume` for the bound, and `spawn_and_track`'s -/// doc for why `start` keeps the older, unconditional contract. -/// -/// Resuming a session whose last turn was *killed* is allowed — that is -/// often exactly what the caller wants — but never silent: the reply says -/// so, since a caller that never ran `status` and missed the todo would -/// otherwise carry on from cut-off work believing it was finished work. -/// -/// A goal session re-enters its continuation loop here with a fresh turn -/// budget — the cap bounds *unattended* re-prompting, not the parent's own. -/// -/// # Errors -/// -/// An invalid name, one already running, a `model` the operator hasn't made -/// available (see `check_model`), this agent at its subagent cap (see -/// `subagent_cap`), no session titled `name` in the project -/// dir searched, `Claude::spawn` failing, or the resumed turn failing within -/// `RESUME_GRACE`. -pub async fn continue_( - state: &Arc, - name: &str, - prompt: String, - model: Option, - effort: Option, - dir: Option<&str>, -) -> anyhow::Result { - validate_name(name)?; - let cap = state.swarm_limits(model.as_deref()).await?; - if let Err(refusal) = state.reserve_under(name, cap) { - return Err(refused( - state, - name, - &refusal, - "use `interrupt` first if you meant to redirect it", - )); - } - // Read before the spawn, which clears the record as soon as the new turn - // is confirmed — this reply is the last chance to mention it. - let killed = state.killed_by(name); - let (tx, rx) = oneshot::channel(); - let verdict: VerdictTx = Arc::new(Mutex::new(Some(tx))); - let started = match continue_reserved(state, name, prompt, model, effort, dir, &verdict) { - Ok(spawned) => spawned, - Err(e) => { - state.release_reservation(name); - return Err(e); - } - }; - // Nothing to release on this path either way: a turn that ended inside - // the grace has already been through `finish_turn`, which clears the - // tracking the spawn put there, and one that a goal carried into another - // turn still owns the name via `between_turns`. - await_resume(rx).await?; - Ok(note_resumed_after_kill(&started, killed)) -} - -/// Hold a `continue` open until its resume is known to have landed — or -/// until [`RESUME_GRACE`] says that waiting any longer costs more than the -/// answer is worth. -/// -/// Returns as soon as *either* side of the race reports, so a successful -/// `continue` pays no fixed delay: its first stream event settles the wait -/// at roughly the same moment a miss's exit would have. The timeout is the -/// floor under a child that does neither, and a turn that reaches it is -/// reported as started — which it is, with the end-of-turn todo left to say -/// how it goes. -/// -/// The third case is the channel closing with nothing ever sent — both the -/// sink and the background task dropping their `Arc` without calling -/// `settle`, which only a panic in the task can produce. That reads here as -/// "started", the same as `Underway`, and the fail-open is deliberate: the -/// one thing already known is that `Claude::spawn` returned a live pid, so -/// answering "the resume missed" would be a claim about the session that -/// nothing observed. The turn's real end still reaches the caller as a todo. -/// -/// # Errors -/// -/// The turn's own failure message, verbatim: the caller asked claude to -/// resume a session and claude said why it couldn't, which is a better -/// answer than anything this daemon could paraphrase it into. -async fn await_resume(rx: oneshot::Receiver) -> anyhow::Result<()> { - match tokio::time::timeout(RESUME_GRACE, rx).await { - Ok(Ok(ResumeVerdict::Ended(TurnEnd::Failed(e)))) => anyhow::bail!("{e}"), - // Everything else is a turn that started: it spoke (`Underway`), or - // it ended on its own terms within the grace — `Complete`, or a - // `Killed` that some concurrent `interrupt` asked for and whose todo - // says so — or it is still going when the grace runs out, or nobody - // ever sent at all, which only a panicked task produces and which - // this deliberately fails open on. See the doc above. - _ => Ok(()), - } -} - -/// Append the "you are resuming a killed session" note to `continue`'s reply -/// when its previous turn was signalled; pass the reply through unchanged -/// otherwise. -fn note_resumed_after_kill(msg: &str, killed: Option) -> String { - match killed { - None => msg.to_owned(), - Some(signal) => format!( - "{msg} — note: its previous turn was killed ({}) rather than finishing, so this turn \ - resumes from work that was cut off mid-way", - describe_signal(signal) - ), - } -} - -/// The slow, fallible part of `continue_`, run only after `reserve_under` has -/// already closed the TOCTOU window — same split rationale as -/// `start_reserved`. `dir` is the caller's own, not yet resolved against the -/// remembered one. -fn continue_reserved( - state: &Arc, - name: &str, - prompt: String, - model: Option, - effort: Option, - dir: Option<&str>, - verdict: &VerdictTx, -) -> anyhow::Result { - // A fresh URL for the resumed run, not the one the last run was handed: - // a token is per run, and this is a new one. - let signal_url = state.mint_signal_url(name); - let resolved = state.peek_dir(name, dir); - let config = build_config( - name, - model, - effort, - None, - resolved.as_deref(), - Some(&signal_url), - ); - continue_on_runtime(state, name, config, dir, prompt, verdict) -} - -/// Resume `name`'s session on the daemon's runtime for one more run. -/// -/// The session is looked up before any of `name`'s records change, so a -/// refused call leaves `status` and the remembered `dir` as they were; only -/// a session that is there gets `State::begin_continue`. -/// -/// # Errors -/// -/// On claude, a name with no session in `config`'s project dir (see -/// `resume_target`). On ACP, a name with no recorded session: the ACP -/// runtime would start a new one rather than fail, so the check has to -/// happen here. -fn continue_on_runtime( - state: &Arc, - name: &str, - config: Config, - dir: Option<&str>, - prompt: String, - verdict: &VerdictTx, -) -> anyhow::Result { - if let SubagentRuntime::Acp { command, sessions } = &state.runtime { - let session = acp_session_file(sessions, name); - if !session.exists() { - anyhow::bail!( - "no ACP session is recorded for subagent `{name}` (looked for {}) — `start` \ - creates one", - session.display() - ); - } - state.begin_continue(name, dir); - let cgroup = state.run_cgroup(name); - let runtime = acp_runtime( - state.entered_command(command.clone(), cgroup.as_ref()), - sessions, - name, - ); - return spawn_and_track_acp( - state, - name, - runtime, - cgroup, - config, - prompt, - Some(Arc::clone(verdict)), - ); - } - // The lookup in `resume_target` refuses before anything spawns. `verdict` - // still carries claude's own answer back in time to be the call's error, - // for a session that vanishes between the lookup and the spawn. See this - // module's doc. - let id = resume_target(&config, name)?; - state.begin_continue(name, dir); - spawn_and_track( - state, - name, - &config, - &Attach::Resume(id), - prompt, - Some(Arc::clone(verdict)), - ) -} - -/// Bumps `name`'s liveness clock on every line of the turn's output, and -/// offers the line to the swarm terminal publisher when this agent has one -/// ([`crate::swarm_term`]). -/// -/// **All three callbacks, deliberately.** A stderr line or a stdout line -/// that didn't parse as JSON is proof the child is alive every bit as much -/// as a stream-json event is, and the failure that matters here is reporting -/// a live subagent as wedged — so anything the child says counts. Liveness -/// never reads what it said: classifying *what* the subagent is doing is the -/// publisher's job and a separate question from whether it's doing anything. -/// -/// Sink methods are called synchronously from the driver's stream readers as -/// lines arrive, so the body has to stay cheap — one uncontended map write -/// is, and forwarding to a channel to do the same write elsewhere would cost -/// more than it saved. `settle` adds a second uncontended lock on a -/// `resume`d turn only, and finds an already-emptied slot after the first -/// event — strictly less work than the map write next to it. The publisher's -/// `offer` copies the line into a bounded channel and never waits. -/// -/// **Liveness counts every callback; "the turn is underway" does not.** A -/// resume that matched nothing is not silent: claude writes the reason to -/// stderr *and* emits a terminal stream-json `result` event before exiting, -/// so treating any callback at all as proof the turn began would report -/// every missed resume as a successful start. The narrowest fact that -/// separates the two is the event's own kind — a `result` is stream-json's -/// end-of-turn marker, so an event that isn't one is a turn still in -/// progress. That's the envelope, not the content. -struct LivenessSink { - state: Arc, - name: String, - /// The model and effort this run was started with, stamped on every row - /// it publishes. - info: Arc, - /// Where to report the first non-terminal event, on a `resume` whose - /// caller is still waiting to hear whether it landed. `None` on a - /// `start`, which has nobody waiting. - verdict: Option, -} - -impl hive_claude::Sink for LivenessSink { - fn on_event(&self, event: &serde_json::Value) { - self.state.note_event(&self.name); - if event.get("type").and_then(serde_json::Value::as_str) != Some("result") { - settle(self.verdict.as_ref(), ResumeVerdict::Underway); - } - self.publish(|| Output::Event(event.clone())); - } - - fn on_stdout_line(&self, line: &str) { - self.state.note_event(&self.name); - self.publish(|| Output::Stdout(line.to_owned())); - } - - fn on_stderr_line(&self, line: &str) { - self.state.note_event(&self.name); - self.publish(|| Output::Stderr(line.to_owned())); - } -} - -impl LivenessSink { - /// Offer a line to the publisher, building the copy only when there is - /// one to take it. - fn publish(&self, line: impl FnOnce() -> Output) { - if let Some(term) = &self.state.term { - term.offer(&self.name, &self.info, line()); - } - } -} - -/// The exit status a run's end reports to the swarm: `0` when it completed, -/// nothing when a signal killed it, and `1` for any other failure. A failed -/// turn's own exit code is not kept on [`TurnEnd`] (it carries the message -/// shown to the caller), and an ACP failure has no process status at all, so -/// the swarm sees "failed" and the end todo has the detail. -fn exit_status(end: &TurnEnd) -> Option { - match end { - TurnEnd::Complete => Some(0), - TurnEnd::Killed { .. } => None, - TurnEnd::Failed(_) => Some(1), - } -} - -/// What a run's rows say about how it was started: its `config`'s model and -/// effort, which the swarm shows beside the subagent's name. -fn run_info(config: &Config) -> Arc { - Arc::new(crate::swarm_term::RunInfo { - model: config.model.clone(), - effort: config.effort.clone(), - }) -} - -/// Spawn the child (synchronous — `Claude::spawn` returns with a real pid -/// the instant the process exists), track it in `running`, and hand the -/// actual turn off to a background task so nobody blocks on the whole turn. -/// -/// **A pid is "confirmed running" for a `start`, and only for a `start`.** -/// A `start` creates its session, so the only thing that can go wrong at -/// attach time is the spawn itself, which has already either succeeded or -/// returned here as an error — there is no stronger signal to wait for, and -/// waiting would slow every call down for no reason. A `resume` breaks that -/// reasoning: the session it names may not be there, and claude only says so -/// a fraction of a second *after* the process exists, so for a `continue` a -/// pid is not proof the turn began. That's what `verdict` is for — `Some` -/// only on the resume path, carrying the first real answer back to a caller -/// that is waiting for it (`await_resume`); `None` on a `start`, which keeps -/// the immediate-return contract unchanged. -/// -/// **The turn *continuation* loop lives in that background task, and only -/// there.** A session `start`ed with a goal runs turn after turn until -/// something stops it, and every one of those turns is a fresh -/// `Claude::spawn` against `Attach::Resume` — the driver's `wait` consumes -/// its child, so there is no other shape it could take. Keeping the loop -/// behind the same `tokio::spawn` is what leaves both tool-call contracts -/// untouched: `start` still returns at the first spawn, `continue` still -/// returns when its own turn is underway, and neither waits on turns two -/// through five. -/// -/// Not `async` itself — `tokio::spawn` needs an active runtime to spawn -/// *onto*, not an `async` caller to spawn *from*. -fn spawn_and_track( - state: &Arc, - name: &str, - config: &Config, - attach: &Attach, - prompt: String, - verdict: Option, -) -> anyhow::Result { - // Every turn of the run, and all they start, share one cgroup, released - // when the background task below ends. - let cgroup = state.run_cgroup(name); - let config = &state.entered_config(config, cgroup.as_ref()); - let running = Claude::spawn(config, attach) - .map_err(|e| anyhow::anyhow!("starting the subagent process failed: {e}"))?; - state.track(name, running.cancel_handle().into()); - // This turn supersedes whatever the previous one did, including having - // been killed — the record is about the turn before this one. - state.clear_kill(name); - // Start the liveness clock at the spawn, so the age is already an answer - // before the child's first line — see `note_event`. - state.note_event(name); - - // Resolved here, on the calling thread, while the config is still to - // hand: only a resume can miss, and only `classify_end` finding a - // `SessionNotFound` ever uses it. Every continuation turn is a resume, - // so this is worth having even when the *first* attach is a `Create`. - let resume_searched = searched_location(config); - let mut searched = if matches!(attach, Attach::Resume(_)) { - resume_searched.clone() - } else { - None - }; - - let info = run_info(config); - state.announce_running(name, &info); - let config = config.clone(); - let state = Arc::clone(state); - let task_name = name.to_owned(); - tokio::spawn(async move { - let _cgroup = cgroup; - let mut running = running; - let mut prompt = prompt; - loop { - let sink = LivenessSink { - state: Arc::clone(&state), - name: task_name.clone(), - info: Arc::clone(&info), - verdict: verdict.clone(), - }; - let end = classify_end(running.wait(&prompt, &sink).await, searched.as_deref()); - let Some(next) = after_turn(&state, &task_name, end, verdict.as_ref()).await else { - return; - }; - match resume_target(&config, &task_name) - .and_then(|id| Ok(Claude::spawn(&config, &Attach::Resume(id))?)) - { - Ok(next_running) => { - state.track(&task_name, next_running.cancel_handle().into()); - state.note_event(&task_name); - running = next_running; - prompt = next; - searched = resume_searched.clone(); - } - Err(e) => { - let end = TurnEnd::Failed(format!( - "claude error: starting the next goal turn failed: {e}" - )); - log_turn_end(&task_name, &end); - state.finish_turn(&task_name, &end); - push_turn_end_todo(&state.socket, &task_name, &end, None).await; - return; - } - } - } - }); - - Ok(format!("subagent `{name}` started")) -} - -/// Everything a run does once one of its turns has ended, on either -/// runtime: report it, and either stop the run or claim the name for the -/// next goal turn. Returns that turn's prompt, or `None` once the run is -/// over. -async fn after_turn( - state: &State, - name: &str, - end: TurnEnd, - verdict: Option<&VerdictTx>, -) -> Option { - log_turn_end(name, &end); - // The todo is how a turn's end reaches an agent that is no - // longer looking — so it is pushed for every end *except* the - // one the caller is being handed as a tool-call error right now. - // `settle` saying the verdict was delivered is what makes that - // certain: a `continue` whose grace had already run out gets - // `false` here and its todo, same as before. Only the first turn - // can ever win this — the sender is consumed — which is right, - // since only the first turn is one a caller is still waiting on. - let reported = settle(verdict, ResumeVerdict::Ended(end.clone())); - - if !matches!(end, TurnEnd::Complete) { - // A killed or failed turn ends the run, goal or not: there is - // nothing to re-prompt a child that isn't there any more, and - // these two ends already have records of their own. - state.finish_turn(name, &end); - if !(matches!(end, TurnEnd::Failed(_)) && reported) { - push_turn_end_todo(&state.socket, name, &end, None).await; - } - return None; - } - - match state.plan_after_turn(name) { - Continuation::Stop(stop) => { - state.record_stop(name, stop.clone()); - state.finish_turn(name, &end); - write_stop_to_report(state.report_file(name), name, &stop).await; - push_turn_end_todo(&state.socket, name, &end, Some(&stop)).await; - None - } - Continuation::Continue { prompt } => { - // The name stays claimed across the gap — see - // `between_turns` for what a concurrent `start` would - // otherwise be able to do with it. - state.between_turns(name); - Some(prompt) - } - } -} - -/// [`spawn_and_track`] on ACP: every turn of the run goes through -/// `runtime`, whose agent process is spawned by the first turn and killed -/// when the run ends and the runtime is dropped. Returns before the agent -/// exists, so a spawn failure is the first turn's `Failed` end rather than -/// this call's error. The run's `cgroup` is released after the runtime. -fn spawn_and_track_acp( - state: &Arc, - name: &str, - runtime: AcpRuntime, - cgroup: Option, - config: Config, - prompt: String, - verdict: Option, -) -> anyhow::Result { - let canceller = runtime - .canceller() - .ok_or_else(|| anyhow::anyhow!("the ACP runtime offers no cancel handle"))?; - state.track(name, canceller.clone().into()); - state.clear_kill(name); - state.note_event(name); - - let info = run_info(&config); - state.announce_running(name, &info); - let state = Arc::clone(state); - let task_name = name.to_owned(); - tokio::spawn(async move { - let mut prompt = prompt; - loop { - let sink = LivenessSink { - state: Arc::clone(&state), - name: task_name.clone(), - info: Arc::clone(&info), - verdict: verdict.clone(), - }; - let end = match runtime.run(&config, &prompt, &sink).await { - Ok(_) => TurnEnd::Complete, - Err(e) => TurnEnd::Failed(format!("ACP error: {e}")), - }; - let Some(next) = after_turn(&state, &task_name, end, verdict.as_ref()).await else { - break; - }; - state.track(&task_name, canceller.clone().into()); - state.note_event(&task_name); - prompt = next; - } - drop(runtime); - drop(cgroup); - }); - - Ok(format!("subagent `{name}` started")) -} - -/// The file `name`'s ACP session id is kept in, under `sessions`. Named -/// like the per-session MCP config and system-prompt files beside it. -fn acp_session_file(sessions: &Path, name: &str) -> PathBuf { - sessions.join(format!("subagent-acp-session-{name}")) -} - /// A subagent run's `oom_score_adj`: under memory pressure the kernel takes a /// bash task (1000) first, then a subagent run, then the agent's own session /// (-500, `nix/agent-modules/agent-service.nix`). const RUN_OOM_SCORE_ADJ: i32 = run_cgroup::SUBAGENT_RUN_OOM_SCORE_ADJ; -/// The ACP runtime `name`'s run drives, keeping its session id in -/// [`acp_session_file`] and answering permission requests per -/// [`acp_permits`]. -fn acp_runtime( - command: AcpCommand, - sessions: &Path, - name: &str, -) -> AcpRuntime { - let perms = crate::swarm_models::permissions_now(); - let permit: PermissionPolicy = - Arc::new(move |ask: &PermissionAsk<'_>| acp_permits(ask, &perms)); - AcpRuntime::new( - command, - acp_session_file(sessions, name), - permit, - hive_claude::NeverCompact, - ) -} - -/// Whether an ACP subagent may run the tool call it asks about. -/// Default-deny, allowing what a claude subagent gets from `build_config`: -/// -/// - `other`-kind calls to tools of the MCP servers the session was handed; -/// - the file tools: `read`, `edit`, `search`; -/// - `fetch` with the `web_tools` permission; -/// - `execute` with the `execution` permission, as a claude subagent gets `Bash` -/// ([`hive_sh4re::permissions::subagent_builtin_tools_for`]). -fn acp_permits(ask: &PermissionAsk<'_>, perms: &[Permission]) -> bool { - match ask.kind { - "other" => ask.mcp_server.is_some(), - "read" | "edit" | "search" => true, - "fetch" => perms.contains(&Permission::WebTools), - "execute" => perms.contains(&Permission::Execution), - _ => false, - } -} - -/// Log a turn's end at the level its severity deserves: a completion is -/// unremarkable, the other two are not. -fn log_turn_end(name: &str, end: &TurnEnd) { - match end { - TurnEnd::Complete => {} - TurnEnd::Killed { signal } => { - tracing::warn!( - name = %name, - signal, - "subagent: turn killed — the child died on a signal, it did not finish" - ); - } - TurnEnd::Failed(e) => { - tracing::warn!(name = %name, error = %e, "subagent: turn failed"); - } - } -} - -/// Append the stop reason to the session's own report file, so the artifact -/// a parent already reads is where the run's ending is recorded too — rather -/// than the parent having to correlate a todo against a file. -/// -/// Best-effort and appended, never rewritten: the subagent wrote that file, -/// and this adds a line under what it wrote instead of taking a position on -/// the rest of it. A path this daemon can't write to is logged and dropped — -/// the todo still carries the same sentence, so nothing is only here. -async fn write_stop_to_report(path: Option, name: &str, stop: &StopReason) { - let Some(path) = path else { return }; - let line = format!("\n**Subagent `{name}` stopped:** {}\n", stop.sentence()); - let appended = tokio::fs::OpenOptions::new() - .create(true) - .append(true) - .open(&path) - .await; - let result = match appended { - Ok(mut file) => { - use tokio::io::AsyncWriteExt as _; - // `flush`, not just `write_all`: a `tokio::fs::File` buffers, and - // dropping one discards whatever hasn't been handed to the - // blocking pool — so without this the line is written to nothing - // and the failure is silent. A unit test caught exactly that. - match file.write_all(line.as_bytes()).await { - Ok(()) => file.flush().await, - Err(e) => Err(e), - } - } - Err(e) => Err(e), - }; - if let Err(e) = result { - tracing::warn!( - name, - path = %path.display(), - error = ?e, - "subagent: could not record the stop reason in the session's report file", - ); - } -} - -/// The goal contract appended to a `start`'s first prompt when a goal was -/// given. Spelled out to the subagent rather than left implicit: it is about -/// to be re-prompted by something it can't see, and the two tools that stop -/// that are the only way it has to say "done" or "stuck". -fn goal_briefing(name: &str, goal: &str, max_turns: u32) -> String { - format!( - "\n\nYou are the subagent session `{name}`.\n\nYour goal for this session: {goal}\n\nYou \ - have up to {max_turns} turns to reach it. When a turn of yours ends and you haven't \ - reported the goal reached, the harness starts another turn re-prompting you toward it. \ - Call the `goal_reached` tool once you've genuinely reached it, or `need_help` with what \ - is blocking you if you can't proceed — either one stops the re-prompting. Neither takes \ - a session name: the endpoint you call them on is yours alone, so they always apply to \ - this session and can't be aimed at another one. Running out of turns stops it too, with \ - the work left wherever it had got to." - ) -} - -/// The prompt a continuation turn opens with. It states the one fact the -/// subagent can't observe for itself — that its last turn ended without the -/// goal being reported reached — and says plainly that claiming the goal -/// isn't the same as reaching it, since being re-prompted is precisely the -/// pressure to claim it. -fn continuation_prompt(name: &str, goal: &str, turn: u32, max_turns: u32) -> String { - format!( - "Your previous turn ended and you have not reported the goal reached.\n\nYou are the \ - subagent session `{name}`.\n\nGoal: {goal}\n\nThis is turn {turn} of {max_turns}. Carry \ - on toward the goal. If you have in fact reached it, call `goal_reached`; if you are \ - blocked, call `need_help` with what is blocking you. Neither is a substitute for \ - the work: whoever spawned you reads what you actually changed, not what you claim about \ - it." - ) -} - -/// Record the subagent's own "I have reached the goal" signal and stop its -/// turn continuation. Called by the subagent, from inside its own turn, over -/// the signal route this daemon hands it (see `build_config`). -/// -/// **`name` is not a parameter of the tool.** It is whatever the route's -/// token resolved to (`State::session_for_signal_token`), so a subagent -/// records a stop against its own session because that is the only session -/// its URL can reach — not because it addressed the right one. -/// -/// **This verifies nothing**, and the answer it returns says so to the -/// subagent's face. It stops the loop and extends the done message; whether -/// the goal was actually reached is a question about the diff and the gate -/// output, which the parent reads for itself. -/// -/// `report_file` is the subagent saying where it wrote its report, which is -/// the only reason this daemon ever knows that path — see -/// `State::set_report_file`. -pub fn goal_reached( - state: &State, - name: &str, - msg: Option, - report_file: Option<&str>, -) -> String { - signal_stop(state, name, StopReason::GoalReached(msg), report_file); - format!( - "noted — `{name}`'s goal is recorded as reported reached, so this turn finishes and no \ - further goal turn is started. It is recorded as your claim, not as verification: whoever \ - spawned you still reads what you changed." - ) -} - -/// Record that the subagent can't proceed, and stop its turn continuation. -/// The blocking signal the run has otherwise no way to raise: without it a -/// stuck subagent would be re-prompted toward a goal it has already told -/// nobody it can't reach, until the turn cap. -/// -/// `msg` is required, unlike `goal_reached`'s — "I'm stuck" with no reason -/// gives the parent nothing to act on, and acting on it is the entire point. -/// -/// `name` comes from the route's token, exactly as in [`goal_reached`]. -pub fn need_help(state: &State, name: &str, msg: String, report_file: Option<&str>) -> String { - signal_stop(state, name, StopReason::NeedHelp(msg), report_file); - format!( - "noted — `{name}` is recorded as blocked, so this turn finishes and no further goal turn \ - is started. Write down what you have done so far where your brief told you to; whoever \ - spawned you sees the block in `status` and in this run's todo." - ) -} - -/// The half [`goal_reached`] and [`need_help`] share: remember where the -/// subagent says it wrote, and record the stop. -/// -/// It checks nothing, and has nothing left to check. `name` reached it by -/// being resolved from the route's own token, so "is this signal about the -/// session it claims" is answered before the request is dispatched at all — -/// a token that names no live session never reaches this function, it gets a -/// 404. What used to stand here was an `occupancy()` liveness check standing -/// in for identity, which two concurrently-running siblings could each -/// satisfy for the other's name. -fn signal_stop(state: &State, name: &str, stop: StopReason, report_file: Option<&str>) { - state.set_report_file(name, report_file); - state.record_stop(name, stop); -} - -/// Report whether `name` is currently running — a zero-cost check that -/// never launches a process, unlike `continue`. Distinguishes running, -/// starting (reserved, not yet a confirmed spawn — see `State`'s doc), -/// killed (its last turn died on a signal), each of the four ways a goal -/// run stops, idle (a session exists, its last turn finished, nothing is in -/// flight), and no such session at all. -/// -/// A *running* answer also carries how long since that turn last produced -/// output, which is the part of this answer a caller can act on: "running" -/// describes a wedged child and a busy one identically, and the age -/// separates them (see `State`'s `last_event` doc). -/// -/// A goal-continued session carries `turn N of M` alongside that, in every -/// state. With the age, it is what lets a caller tell *working* from -/// *wedged* from *out of turns* off one answer, without reaching for `ps` -/// or reading any file. -/// -/// # Errors -/// -/// An invalid name, or no session — running, killed, stopped or on disk — -/// under `name`. -pub fn status(state: &State, name: &str, dir: Option<&str>) -> anyhow::Result { - validate_name(name)?; - // Read-only: an explicit `dir` here is a one-off "check this other - // directory's session" per this fn's own doc, not a new remembered - // default — `peek_dir` resolves the same way but never writes. - let dir = state.peek_dir(name, dir); - let facts = StatusFacts { - occupancy: state.occupancy(name), - killed: state.killed_by(name), - last_event_age: state.last_event_age(name), - turns: state.turns(name), - stop: state.stop_reason(name), - ..StatusFacts::new(name) - }; - // Nothing on disk to look for while something is tracked in memory — - // those states answer on their own, and the store read is the only - // expensive part of this call. A recorded stop reason counts: it is - // proof this daemon ran the session, which is what the lookup asks. - let session_exists = - if facts.occupancy.is_none() && facts.killed.is_none() && facts.stop.is_none() { - if let SubagentRuntime::Acp { sessions, .. } = &state.runtime { - acp_session_file(sessions, name).exists() - } else { - // No signal surface in this config: it exists only to resolve - // the session store, and rendering a subagent's MCP config for - // a read-only status check would be writing a file for nobody. - let config = build_config(name, None, None, None, dir.as_deref(), None); - build_store(&config)?.find_by_title(name).is_some() - } - } else { - false - }; - describe_status(&StatusFacts { - session_exists, - ..facts - }) -} - -/// The liveness clause appended to a *running* answer, and the whole point -/// of recording the timestamp: an age in seconds a caller can read a verdict -/// off directly, rather than one it has to go and measure itself with `ps` -/// and CPU-time deltas. -/// -/// Deliberately just the number now — the full "seconds means working, -/// minutes means wedged, resets each turn" explanation used to repeat here -/// on every single call. It already lives in the `status` tool description -/// and in `docs/4-implementation/agent-tools/subagent.md`'s "Telling working from wedged" -/// section, so restating it in a line meant to be skimmed, possibly several -/// times a minute, was pure repetition. -/// -/// Empty when there's no age to report — a turn that ended between `status` -/// reading `running` and reading the clock. Saying nothing is right there: -/// the alternative is an age that describes a turn which has already -/// finished, which reads as a stall that never happened. -fn describe_liveness(age: Option) -> String { - match age { - None => String::new(), - Some(age) => format!(" Last event {}s ago.", age.as_secs()), - } -} - -/// The progress sentence a goal-continued session carries in every state: -/// which turn of its budget it is on. Empty for a session with no goal, -/// which has no budget to be partway through. -/// -/// On a *running* answer this is the turn in flight; on a stopped one it is -/// the turn it stopped on — the same number either way, since the counter -/// only advances when the loop decides to spend another turn. -fn describe_turns(turns: Option<(u32, u32)>) -> String { - match turns { - None => String::new(), - Some((turn, max_turns)) => format!(" Turn {turn} of {max_turns}."), - } -} - -/// Everything `status` gathers, as one value — seven separate parameters -/// read as noise at both the call site and the test sites, and every one of -/// them is a fact about the same session. -struct StatusFacts<'a> { - name: &'a str, - occupancy: Option, - killed: Option, - session_exists: bool, - last_event_age: Option, - turns: Option<(u32, u32)>, - stop: Option, -} - -impl<'a> StatusFacts<'a> { - /// The nothing-known baseline for `name`: no process, no records, no - /// session. Both the real gathering in `status` and the tests build on - /// it, so neither has to spell out the fields it isn't exercising. - fn new(name: &'a str) -> Self { - Self { - name, - occupancy: None, - killed: None, - session_exists: false, - last_event_age: None, - turns: None, - stop: None, - } - } -} - -/// Render `status`'s answer from the facts it gathers. Split out from the -/// gathering so the killed-versus-idle distinction — and the liveness age, -/// the turn counter and each stop reason — are exercisable without a real -/// spawn, a real signal, a real stream of events and a real on-disk claude -/// session. -/// -/// A recorded kill outranks both the stop reason and the on-disk session: -/// the session file exists either way and a stop reason may be left over -/// from the signal a subagent raised just before something killed it, so -/// neither can tell a killed turn from a finished one. The kill can. -/// -/// Every answer is self-contained — it names the one state the caller got -/// and what to do next — because the tool description deliberately doesn't -/// enumerate the state space (the operator's ruling on this surface: -/// describe the tool, explain the state when returning it). Keep the split: -/// a terser answer here has nowhere left to be explained from. -fn describe_status(facts: &StatusFacts<'_>) -> anyhow::Result { - let name = facts.name; - let turns = describe_turns(facts.turns); - match facts.occupancy { - Some(Occupancy::Running) => { - return Ok(format!( - "subagent `{name}` is running — its turn is still in flight, so there's nothing \ - to do but let it work: the daemon pushes a todo when the run ends, or \ - `interrupt` it if you want it stopped early.{turns}{}{}", - describe_liveness(facts.last_event_age), - describe_pending_signal(facts.stop.as_ref()), - )); - } - Some(Occupancy::Starting) => { - return Ok(format!( - "subagent `{name}` is starting — the name is claimed but no process is confirmed \ - under it yet, either because a `start`/`continue` hasn't spawned one or because \ - a goal run is between turns. Normally over in well under a second: check again \ - shortly rather than starting anything else under this name.{turns}" - )); - } - Some(Occupancy::Stopping) => { - return Ok(format!( - "subagent `{name}` is stopping — `interrupt` sent it SIGINT and its process \ - hasn't exited yet. The name stays claimed until it does, so `start` and \ - `continue` are refused meanwhile. Nothing escalates past that SIGINT: one that \ - never exits needs killing by hand.{turns}{}", - describe_liveness(facts.last_event_age), - )); - } - None => {} - } - if let Some(signal) = facts.killed { - return Ok(format!( - "subagent `{name}` was killed — its last turn died on {}, so its work stopped \ - wherever it had got to rather than finishing. `continue` still resumes it, but \ - whatever it was told to do is unfinished: check what it actually left behind before \ - trusting it.{turns}", - describe_signal(signal) - )); - } - if let Some(stop) = &facts.stop { - return Ok(describe_stopped(name, stop, &turns)); - } - if facts.session_exists { - Ok(format!( - "subagent `{name}` is idle — its session exists, its last turn ended on its own \ - rather than being cut off, and nothing is in flight: that turn's own todo says how \ - it went, and `continue` gives it another.{turns}" - )) - } else { - anyhow::bail!( - "no subagent named `{name}` exists — nothing is running under that name and there's \ - no session on disk to resume, so `start` is what creates one (check the name if you \ - expected something here)." - ) - } -} - -/// The note a *running* answer carries when the subagent has already raised -/// a stop signal for the turn still in flight. Without it a parent polling -/// `status` would read plain "running" for the whole stretch between the -/// subagent saying it is blocked and its turn actually ending — the one -/// stretch where "it's working, leave it alone" is the wrong conclusion. -fn describe_pending_signal(stop: Option<&StopReason>) -> String { - match stop { - None | Some(StopReason::Done | StopReason::TurnCap { .. }) => String::new(), - Some(stop) => format!( - " It has already signalled how this run ends — {} — so this is its last turn.", - stop.sentence() - ), - } -} - -/// The answer for a session whose run has stopped, one per [`StopReason`]. -/// Each names the state, why the continuation stopped, and what `continue` -/// would do about it — and the `GoalReached` one is deliberately the least -/// reassuring of them, because it is the one a caller is most likely to -/// read as "finished successfully" when it means "said so". -fn describe_stopped(name: &str, stop: &StopReason, turns: &str) -> String { - match stop { - StopReason::Done => format!( - "subagent `{name}` is idle — its session exists, its last turn ended on its own \ - rather than being cut off, and nothing is in flight: that turn's own todo says how \ - it went, and `continue` gives it another.{turns}" - ), - StopReason::GoalReached(msg) => format!( - "subagent `{name}` stopped: it reported its goal reached{}. Nothing is in flight and \ - no further goal turn will start.{turns} That report is the subagent's own claim, not \ - a verification of anything — read the diff and whatever gate the work was supposed \ - to pass before you treat the goal as met, exactly as you would a build report saying \ - the tests passed.", - msg.as_deref() - .map_or_else(String::new, |m| format!(": {m}")) - ), - StopReason::NeedHelp(msg) => format!( - "subagent `{name}` is BLOCKED and needs help: {msg}. It called `need_help`, which \ - stopped its goal continuation, and nothing is in flight — it stays blocked until you \ - answer it. `continue` is how you answer: give it what it asked for as the next \ - turn's prompt." - ), - StopReason::TurnCap { turns: spent } => format!( - "subagent `{name}` ran out of turns — the harness limit of {spent} was reached and it \ - never reported its goal reached, so the work stopped wherever it had got to rather \ - than finishing.{turns} Check what it actually left behind; `continue` gives it a \ - fresh allowance if carrying on is worth it." - ), - StopReason::Cancelled => format!( - "subagent `{name}` was CANCELLED — someone called `interrupt` on it, which stopped \ - the run and not merely the turn that was in flight, so nothing further will start \ - on its own.{turns} Its work stopped wherever it had got to: check what it left \ - behind before acting on it. `continue` restarts it, with a fresh turn allowance." - ), - } -} - -/// Stop `name`'s running turn: SIGINT to claude's process group (see -/// `hive_claude::Cancel::cancel`), or `session/cancel` on ACP. Nothing -/// escalates to SIGKILL: each command claude's Bash tool starts leads its -/// own session, and only claude shutting down on SIGINT stops it. -/// -/// Returns without waiting. A claude turn's name stays claimed as -/// `Slot::Stopping` until the turn's own `finish_turn` clears it, so no -/// second claude starts on the session while the first is winding down. -/// -/// It stops the goal run, not just the turn, by **recording -/// `StopReason::Cancelled`**: claude answers SIGINT by emitting its -/// terminal `result` event and exiting 0, which is `TurnEnd::Complete`, so -/// only the recorded reason, which `plan_after_turn` checks before the -/// goal, keeps the loop from re-prompting. It is written while the -/// `running` lock is held, so a turn that ends on its own in between still -/// finds it. -/// -/// # Errors -/// -/// An invalid name, nothing tracked under `name`, nothing to signal right -/// now (a spawn or ACP turn not yet live, or a goal run between turns; the -/// reservation is put back, so a concurrent `start`/`continue` is still -/// refused), or a claude already signalled and not yet exited. -pub fn interrupt(state: &State, name: &str) -> anyhow::Result { - validate_name(name)?; - let mut running = state.running.lock().unwrap_or_else(PoisonError::into_inner); - let mut claimed = ""; - match running.remove(name) { - None => anyhow::bail!("no subagent named `{name}` is currently running"), - Some(Slot::Starting) => { - running.insert(name.to_owned(), Slot::Starting); - tracing::info!(name, "interrupt refused: no process is tracked yet"); - return Err(still_starting(name)); - } - Some(Slot::Stopping) => { - running.insert(name.to_owned(), Slot::Stopping); - anyhow::bail!( - "subagent `{name}` was already interrupted and its process hasn't exited yet — \ - `status` says when it has" - ); - } - // `stop()` is `false` when no turn is in flight (an ACP agent not - // prompted yet, or a turn just ended), and then nothing was stopped. - // The stop goes in before the signal and comes out under the same - // `stops` lock, so `plan_after_turn` never reads a cancel that - // didn't happen. - Some(Slot::Running(stop)) => { - let mut stops = state.stops.lock().unwrap_or_else(PoisonError::into_inner); - let prior = stops.insert(name.to_owned(), StopReason::Cancelled); - if !stop.stop() { - match prior { - Some(prior) => stops.insert(name.to_owned(), prior), - None => stops.remove(name), - }; - drop(stops); - running.insert(name.to_owned(), Slot::Running(stop)); - return Err(still_starting(name)); - } - drop(stops); - if matches!(state.runtime, SubagentRuntime::Claude) { - running.insert(name.to_owned(), Slot::Stopping); - claimed = " The name stays claimed until claude has exited; `status` says \ - `stopping` until then."; - } - } - } - Ok(format!( - "interrupt sent to subagent `{name}` — the run is cancelled, not just the turn that was \ - in flight, so no further goal turn will start. `continue` is what restarts it, with a \ - fresh turn allowance.{claimed}" - )) -} - -/// `start`'s and `continue`'s refusal for a name `reserve_under` would not -/// claim. -fn refused(state: &State, name: &str, refusal: &Refusal, hint: &str) -> anyhow::Error { - match refusal { - Refusal::Taken => name_taken(state, name, hint), - Refusal::AtCap { cap: 0, .. } => anyhow::anyhow!( - "subagents are disabled for this agent: the cap is 0 (set in swarm-ui → this \ - agent → inference)" - ), - Refusal::AtCap { running, cap } => anyhow::anyhow!( - "{running} {} running, cap is {cap} (set in swarm-ui → this agent → \ - inference) — wait for one to finish, or `interrupt` one", - if *running == 1 { - "subagent" - } else { - "subagents" - } - ), - } -} - -/// `start`'s and `continue`'s refusal for a name `reserve_under` found claimed: -/// `hint` says what to do about a live session, and an interrupted one that -/// hasn't exited yet gets its own answer. -fn name_taken(state: &State, name: &str, hint: &str) -> anyhow::Error { - if state.occupancy(name) == Some(Occupancy::Stopping) { - anyhow::anyhow!( - "subagent `{name}` is stopping — it was interrupted and its process hasn't exited \ - yet; the name is free once it has (`status` says when)" - ) - } else { - anyhow::anyhow!("subagent `{name}` is already running — {hint}") - } -} - -/// `interrupt`'s refusal for a name that is claimed but has nothing to -/// signal yet. -fn still_starting(name: &str) -> anyhow::Error { - anyhow::anyhow!( - "subagent `{name}` is still starting — not yet confirmed running, try again shortly" - ) -} - -/// Push `name`'s one-shot end-of-turn todo. Best-effort: a connect/write -/// failure is logged and swallowed, matching every other in-agent-socket -/// producer in this codebase — there's no retry queue to fall back to, and -/// the caller has already moved on by the time this fires. -async fn push_turn_end_todo( - socket: &std::path::Path, - name: &str, - end: &TurnEnd, - stop: Option<&StopReason>, -) { - let req = hive_agent_sock::Request::UpsertTodo { - subsystem: "subagent".to_owned(), - key: Some(name.to_owned()), - summary: turn_end_summary(name, end, stop), - source: None, - reopen_if_acked: false, - }; - if let Err(e) = hive_sock_client::notify(socket, &req, hive_sock_client::Retry::None).await { - tracing::warn!(name, error = ?e, "subagent: end-of-turn todo push failed"); - } -} - -/// The todo text for a run that has ended. A killed turn deliberately does -/// not use the "finished" wording the other two share: this todo is the only -/// thing the owning agent is shown without asking, so it has to read as the -/// interruption it is rather than as one more completed subagent. -/// -/// A `stop` **extends** that message, it never replaces it. Both halves are -/// load-bearing and neither substitutes for the other: the turn's own end is -/// what the daemon observed, the stop reason is why the run went no further -/// — and for `GoalReached` that second half is a claim, which would read as -/// a verdict if it were allowed to stand where the observed end belongs. -/// `StopReason::Done` adds nothing, since "there was no goal" is exactly -/// what the unextended message already describes. -fn turn_end_summary(name: &str, end: &TurnEnd, stop: Option<&StopReason>) -> String { - let base = match end { - TurnEnd::Complete => format!("subagent `{name}` finished: turn complete"), - TurnEnd::Failed(e) => format!("subagent `{name}` finished: {e}"), - TurnEnd::Killed { signal } => format!( - "subagent `{name}` was KILLED mid-turn ({}) — it did not finish, and its work stopped \ - wherever it had got to. Check what it left behind before you act on it; `continue` \ - resumes the session if you want it carried on.", - describe_signal(*signal) - ), - }; - match stop { - None | Some(StopReason::Done) => base, - Some(stop) => format!("{base} — and the run stopped there: {}", stop.sentence()), - } -} - #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_subagent_run_is_killed_after_a_bash_task_and_before_the_session() { - assert_eq!(RUN_OOM_SCORE_ADJ, 900); - const { assert!(RUN_OOM_SCORE_ADJ < run_cgroup::BASH_TASK_OOM_SCORE_ADJ) }; - } - - // `Cancel` can only be constructed from a real spawned process (no test - // fixture in `hive_claude` for it), so these exercise the reservation - // half of `State` directly — the actual TOCTOU-closure logic — rather - // than the full start/spawn path. - - /// A stand-in for the signal route a real daemon would hand its - /// subagents — the *prefix*, as `State::new` takes it. Nothing in these - /// tests dials it: what `State` does with it is append a minted token and - /// carry the result into `build_config`, both asserted on directly. - fn signal_url() -> String { - "http://127.0.0.1:1/signal/mcp".to_owned() - } - - /// The token out of a minted URL — what the route would have parsed out - /// of the path before resolving it. - fn token_of(url: &str) -> String { - url.rsplit('/') - .next() - .expect("a minted URL always has a last segment") - .to_owned() - } - - /// A `StartRequest` with only the fields a test cares about set — the - /// other six are the same "nothing asked for" every time. - fn start_request(name: &str) -> StartRequest { - StartRequest { - name: name.to_owned(), - model: None, - effort: None, - prompt_file: "/tmp/prompt.md".to_owned(), - role: None, - trigger: "trigger".to_owned(), - dir: None, - goal: None, - max_turns: None, - report_file: None, - } - } - - #[test] - fn reserve_is_exclusive_for_the_same_name() { - let state = State::new(PathBuf::from("/dev/null"), signal_url()); - assert!(state.reserve("dup"), "first reservation should succeed"); - assert!( - !state.reserve("dup"), - "a second reservation for the same name must be refused — this is the exact race \ - argus found: two calls both passing a check before either commits" - ); - } - - #[test] - fn reserve_does_not_cross_block_different_names() { - let state = State::new(PathBuf::from("/dev/null"), signal_url()); - assert!(state.reserve("a")); - assert!( - state.reserve("b"), - "unrelated names must not block each other" - ); - } - - #[test] - fn release_reservation_frees_the_name_for_reuse() { - let state = State::new(PathBuf::from("/dev/null"), signal_url()); - assert!(state.reserve("n")); - state.release_reservation("n"); - assert!( - state.reserve("n"), - "releasing a still-`None` reservation must free the name again" - ); - } - - #[test] - fn occupancy_reflects_the_reserved_but_not_running_state() { - let state = State::new(PathBuf::from("/dev/null"), signal_url()); - assert_eq!(state.occupancy("never-reserved"), None); - state.reserve("n"); - assert_eq!( - state.occupancy("n"), - Some(Occupancy::Starting), - "reserved-but-not-yet-spawned must read as occupied-but-not-running" - ); - } - - // One test, not two: `subagent_otel_attrs` reads the real process-wide - // `OTEL_RESOURCE_ATTRIBUTES` env var, and cargo runs tests in parallel - // threads by default — two separate tests each mutating that global - // raced each other (and, in this container, lost to the agent's own - // real ambient value). Sequencing both assertions in one test removes - // the race instead of papering over it with a mutex. - #[test] - fn otel_attrs_append_ambient_value_or_stand_alone() { - // SAFETY: test-only env mutation; sequenced within this one test so - // no other test's concurrent read/write of the same var can race it. - unsafe { - std::env::remove_var("OTEL_RESOURCE_ATTRIBUTES"); - } - assert_eq!(subagent_otel_attrs("batch-1"), "subagent=batch-1"); - - unsafe { - std::env::set_var("OTEL_RESOURCE_ATTRIBUTES", "agent=damocles"); - } - assert_eq!( - subagent_otel_attrs("batch-1"), - "agent=damocles,subagent=batch-1" - ); - unsafe { - std::env::remove_var("OTEL_RESOURCE_ATTRIBUTES"); - } - } - - #[test] - fn build_config_only_appends_system_prompt_when_given() { - let with = build_config("n", None, None, Some("/tmp/p.md"), None, None); - assert!( - with.extra_args - .contains(&"--append-system-prompt-file".to_owned()) - ); - assert!(with.extra_args.contains(&"/tmp/p.md".to_owned())); - - let without = build_config("n", None, None, None, None, None); - assert!( - !without - .extra_args - .contains(&"--append-system-prompt-file".to_owned()) - ); - } - - /// A scratch file holding `body`, named after `tag` so parallel tests - /// never share one. - fn scratch_file(tag: &str, body: &str) -> PathBuf { - let path = std::env::temp_dir().join(format!("hive-subagent-session-test-{tag}.md")); - std::fs::write(&path, body).expect("a scratch file is writable"); - path - } - - #[test] - fn without_a_role_the_task_still_moves_out_of_the_system_prompt() { - // The principle the role fix was made on is general: a task baked - // into the system prompt re-asserts itself on every later turn, not - // just the one it was written for, whether or not the session has a - // role. So the no-role path folds the task into the trigger too — - // it must be ABSENT from whatever reaches - // `--append-system-prompt-file` and PRESENT in the trigger, the - // same shape the role-path tests below pin for the role case. - let task = scratch_file("no-role-task", "rebase the branch and report"); - let (path, trigger) = system_prompt_and_trigger("n", None, &task.to_string_lossy(), "go") - .expect("a readable task file composes even with no role"); - assert_eq!( - path, None, - "no role means no system-prompt file at all — there is no role \ - text to put in one, and the task must not go in one either" - ); - assert!( - trigger.contains("rebase the branch"), - "the task must reach the subagent as the turn's own prompt: {trigger:?}" - ); - - let system_prompt = path.map(|p| p.to_string_lossy().into_owned()); - let config = build_config("n", None, None, system_prompt.as_deref(), None, None); - assert!( - !config - .extra_args - .contains(&"--append-system-prompt-file".to_owned()), - "the task must not reach claude as a standing system prompt: {:?}", - config.extra_args - ); - } - - #[test] - fn a_role_s_system_prompt_file_holds_the_role_and_never_the_task() { - // A task rendered into the system prompt re-asserts itself as an - // instruction on every later turn of the session, not just the one - // it was written for — the system prompt is the subagent's - // standing identity, not a one-shot channel. Asserting the role is - // present is not enough to catch that regression; a merged file - // would pass that check too. The task's absence from this file is - // the assertion that actually pins the bug. - let task = scratch_file("role-only-task", "rebase the branch and report"); - let dir = std::env::temp_dir().join("hive-subagent-session-test-role-only"); - let (path, _trigger) = compose_prompt( - &dir, - "role-only-run", - Some("you are a reviewer; block on anything unsafe"), - &task.to_string_lossy(), - "go", - ) - .expect("a role and a readable task file compose"); - let path = path.expect("a role always renders a system-prompt file"); - let body = std::fs::read_to_string(&path).expect("the system-prompt file is readable"); - assert!( - body.contains("you are a reviewer"), - "the role must reach the system prompt: {body:?}" - ); - assert!( - !body.contains("rebase the branch"), - "the task must NOT reach the system-prompt file: {body:?}" - ); - } - - #[test] - fn a_role_still_delivers_the_task_as_the_turns_own_prompt() { - // The other half of the same fix: dropping the task from the - // system prompt must not drop it altogether — it goes back to - // being the turn's prompt, the same channel it reached the - // subagent by before roles existed. - let task = scratch_file("turn-prompt-task", "rebase the branch and report"); - let dir = std::env::temp_dir().join("hive-subagent-session-test-turn-prompt"); - let (_path, trigger) = compose_prompt( - &dir, - "turn-prompt-run", - Some("you are a reviewer"), - &task.to_string_lossy(), - "Carry out the task described in your instructions.", - ) - .expect("a role and a readable task file compose"); - assert!( - trigger.contains("rebase the branch"), - "the task must reach the subagent as the turn's own prompt: {trigger:?}" - ); - } - - #[test] - fn a_role_with_an_unreadable_task_file_refuses_rather_than_dropping_either() { - let dir = std::env::temp_dir().join("hive-subagent-session-test-unreadable"); - let err = compose_prompt( - &dir, - "n", - Some("a role"), - "/tmp/no-such-task-file-here.md", - "go", - ) - .expect_err("an unreadable task file cannot silently become a role-only prompt"); - assert!(err.to_string().contains("task instructions"), "{err}"); - } - - #[tokio::test] - async fn a_start_naming_an_unknown_role_errors_and_reserves_nothing() { - // The error path end to end: the refusal happens before anything is - // claimed, so an unknown role costs a message and nothing else — - // no reservation to release, no archived prior session, no spawn. - let state = Arc::new(State::new(PathBuf::from("/dev/null"), signal_url())); - let mut req = start_request("unknown-role-run"); - req.role = Some("no-such-role-ships-anywhere".to_owned()); - let err = start(&state, req) - .await - .expect_err("a role this agent lacks must refuse the start"); - assert!( - err.to_string().contains("no-such-role-ships-anywhere"), - "the refusal names the role that was asked for: {err}" - ); - assert_eq!( - state.occupancy("unknown-role-run"), - None, - "a refused start leaves the name free" - ); - } - - #[tokio::test] - async fn a_start_naming_an_unusable_role_refuses_before_touching_the_filesystem() { - let state = Arc::new(State::new(PathBuf::from("/dev/null"), signal_url())); - let mut req = start_request("bad-role-name"); - req.role = Some("../../etc/passwd".to_owned()); - let err = start(&state, req) - .await - .expect_err("a role name that is not an identifier refuses"); - assert!(err.to_string().contains("invalid role name"), "{err}"); - assert_eq!(state.occupancy("bad-role-name"), None); - } - - /// The `--tools` value as it reaches the spawned argv. - fn spawned_tools(config: &Config) -> &str { - let flag = config - .extra_args - .iter() - .position(|a| a == "--tools") - .expect("--tools is passed on every spawn"); - config - .extra_args - .get(flag + 1) - .expect("--tools carries a value") - } - - /// `--tools` reaches the argv on every caller shape, carrying a non-empty - /// value. Non-empty matters separately from "the flag is there": what an - /// empty value grants is disputed and release-dependent, so we never ship - /// one and never depend on the answer. Checked for each shape because a - /// flag that appears on only some spawn paths is no restriction at all. - /// `signal_url` stays `None` throughout — it only steers `mcp_config`, - /// which `--tools` does not govern, and passing it would make this test - /// need the container's injected `HYPERHIVE_HARNESS_DIR`. - #[test] - fn build_config_always_passes_a_non_empty_tools_list() { - for config in [ - build_config("n", None, None, None, None, None), - build_config("n", None, None, Some("/tmp/p.md"), None, None), - build_config("n", None, None, None, Some("/tmp/wt"), None), - ] { - let tools = spawned_tools(&config); - assert!(!tools.is_empty(), "--tools must never be empty"); - assert!(tools.split(',').all(|t| !t.trim().is_empty())); - } - } - - /// A subagent's built-ins are a subset of `subagent_builtin_tools_for` — - /// the parent's own resolved set, plus `Bash` iff the parent holds - /// `Execution` (see that function's doc comment). This is the property - /// that makes shipping the daemon safe: a subagent reaching a tool - /// outside that resolution is a privilege escalation dressed as a - /// convenience. Read from `hive_sh4re::permissions`, deliberately: it is - /// the parent harness's own resolver, so this compares against what the - /// parent actually licenses rather than against a restatement of it that - /// could drift. - /// - /// ⚠️ **Scope: this catches a code divergence, not a read one.** Both - /// sides resolve off one permission set here; that the parent and this - /// daemon read the same key is a deployment property. - #[test] - fn a_subagent_gets_no_builtin_its_parent_lacks() { - let allowed = hive_sh4re::permissions::subagent_builtin_tools_for( - &crate::swarm_models::permissions_now(), - ); - let config = build_config("n", None, None, None, None, None); - for tool in spawned_tools(&config).split(',') { - assert!( - allowed.contains(&tool), - "subagent got {tool}, which the parent's resolved set does not license" - ); - } - } - - /// Named individually rather than inferred from "the list is short": the - /// tools this daemon used to hand a subagent that reach outside the run - /// it was started for. They are absent because the parent has never had - /// them — this pins the consequence, not a second allow-list. - /// - /// ⚠️ **A canary, not a guarantee.** The names are hardcoded, so this - /// only fails for a tool someone thought to list here; the *guarantee* - /// is the subset property above, which holds for tools nobody has - /// imagined yet. Do not read a pass as "no escaping tool is reachable" — - /// read it as "none of these ten came back". - #[test] - fn no_spawned_tool_escapes_the_session() { - let config = build_config("n", None, None, None, None, None); - let tools: Vec<&str> = spawned_tools(&config).split(',').collect(); - for escaping in [ - "SendMessage", - "ListAgents", - "Task", - "TaskStop", - "TaskOutput", - "CronCreate", - "CronDelete", - "RemoteTrigger", - "EnterWorktree", - "ExitWorktree", - ] { - assert!( - !tools.contains(&escaping), - "{escaping} must not be in a subagent's --tools" - ); - } - } - - #[test] - fn resolve_dir_remembers_an_explicit_dir_and_falls_back_to_it_when_omitted() { - let state = State::new(PathBuf::from("/dev/null"), signal_url()); - assert_eq!( - state.resolve_dir("n", None), - None, - "nothing remembered yet — omitted dir has nothing to fall back to" - ); - assert_eq!( - state.resolve_dir("n", Some("/tmp/worktree")), - Some("/tmp/worktree".to_owned()), - "an explicit dir is returned as-is" - ); - assert_eq!( - state.resolve_dir("n", None), - Some("/tmp/worktree".to_owned()), - "a later omitted dir falls back to what was just remembered" - ); - assert_eq!( - state.resolve_dir("n", Some("/tmp/other")), - Some("/tmp/other".to_owned()), - "a later explicit dir overrides the memory, not just reads it" - ); - assert_eq!( - state.resolve_dir("n", None), - Some("/tmp/other".to_owned()), - "the fallback now reflects the override" - ); - } - - #[test] - fn resolve_dir_does_not_cross_names() { - let state = State::new(PathBuf::from("/dev/null"), signal_url()); - state.resolve_dir("a", Some("/tmp/a")); - assert_eq!( - state.resolve_dir("b", None), - None, - "an unrelated name's memory must stay empty" - ); - } - - #[test] - fn peek_dir_resolves_like_resolve_dir_but_never_writes() { - let state = State::new(PathBuf::from("/dev/null"), signal_url()); - state.resolve_dir("n", Some("/tmp/remembered")); - assert_eq!( - state.peek_dir("n", Some("/tmp/one-off")), - Some("/tmp/one-off".to_owned()), - "an explicit dir still resolves as given" - ); - assert_eq!( - state.resolve_dir("n", None), - Some("/tmp/remembered".to_owned()), - "but the one-off peek must not have overwritten the remembered value" - ); - } - - #[tokio::test] - async fn start_does_not_corrupt_the_remembered_dir_when_the_name_is_already_running() { - // The exact scenario argus caught in review: a rejected concurrent - // `start` used to commit its `dir` before the reservation check - // refused it, corrupting what a later bare `continue` would resolve - // to. Reordering `reserve_under` before `resolve_dir` in `start` closes it - // — a name that's already reserved must never reach `resolve_dir` at - // all, so `dirs` stays exactly as a caller left it. - let state = Arc::new(State::new(PathBuf::from("/dev/null"), signal_url())); - state.resolve_dir("dup", Some("/tmp/original")); - assert!( - state.reserve("dup"), - "simulate an in-flight start/continue already owning the name" - ); - let result = start( - &state, - StartRequest { - dir: Some("/tmp/rejected".to_owned()), - ..start_request("dup") - }, - ) - .await; - assert!( - result.is_err(), - "a name already reserved must be refused, not spawned" - ); - assert_eq!( - state.resolve_dir("dup", None), - Some("/tmp/original".to_owned()), - "the rejected call's dir must not have overwritten the remembered one" - ); - } - - /// The error the driver hands back for a child that died on `signal` — - /// `ExitStatus::from_raw` takes a raw `wait(2)` status, whose low seven - /// bits are the terminating signal, so this is the same value - /// `RunningClaude::wait` would have produced from a real kill. - fn signalled_exit(signal: i32) -> hive_claude::Error { - hive_claude::Error::Exit { - status: std::process::ExitStatus::from_raw(signal), - stderr_tail: String::new(), - } - } - - /// What the swarm is told when a run ends: success is 0, a signal is no - /// code at all, and any other failure is 1. - #[test] - fn a_runs_end_reports_its_exit_status_to_the_swarm() { - assert_eq!(exit_status(&TurnEnd::Complete), Some(0)); - assert_eq!(exit_status(&TurnEnd::Killed { signal: 9 }), None); - assert_eq!(exit_status(&TurnEnd::Failed("boom".to_owned())), Some(1)); - } - - #[test] - fn classify_end_separates_a_signalled_child_from_a_clean_one() { - assert_eq!(classify_end(Ok(()), None), TurnEnd::Complete); - assert_eq!( - classify_end(Err(signalled_exit(libc::SIGKILL)), None), - TurnEnd::Killed { signal: 9 }, - "a SIGKILLed child must not read as a turn that ended on its own" - ); - assert_eq!( - classify_end(Err(signalled_exit(libc::SIGTERM)), None), - TurnEnd::Killed { signal: 15 } - ); - assert!( - matches!( - classify_end(Err(hive_claude::Error::PromptTooLong), None), - TurnEnd::Failed(_) - ), - "claude exiting on its own is a failure, not a kill" - ); - } - - #[test] - fn status_reports_killed_not_idle_for_a_signalled_session() { - // Both sessions exist on disk and neither is running: the only thing - // that can tell them apart is the recorded signal. - let killed = describe_status(&StatusFacts { - killed: Some(libc::SIGKILL), - session_exists: true, - ..StatusFacts::new("n") - }) - .expect("killed status"); - let idle = describe_status(&StatusFacts { - session_exists: true, - ..StatusFacts::new("n") - }) - .expect("idle status"); - assert!( - killed.contains("killed") && killed.contains("SIGKILL (signal 9)"), - "a killed session must say so, and name the signal: {killed}" - ); - assert!( - !killed.contains("idle"), - "a killed session must not also read as idle: {killed}" - ); - assert!(idle.contains("idle"), "a finished turn still reads idle"); - assert_ne!( - killed, idle, - "collapsing the two back together is the bug this reports" - ); - } - - #[test] - fn every_status_answer_names_its_state_and_the_next_move() { - // The tool description no longer lists the states, so each answer - // has to carry its own explanation — checked one state at a time, - // which is all a caller ever gets back. - let running = describe_status(&StatusFacts { - occupancy: Some(Occupancy::Running), - ..StatusFacts::new("n") - }) - .expect("running status"); - assert!( - running.contains("running") && running.contains("`interrupt`"), - "a running answer must say the turn is in flight and how to stop it: {running}" - ); - let starting = describe_status(&StatusFacts { - occupancy: Some(Occupancy::Starting), - ..StatusFacts::new("n") - }) - .expect("starting status"); - assert!( - starting.contains("starting") && starting.contains("check again"), - "a starting answer must say the spawn isn't confirmed yet and to retry: {starting}" - ); - let idle = describe_status(&StatusFacts { - session_exists: true, - ..StatusFacts::new("n") - }) - .expect("idle status"); - assert!( - idle.contains("idle") && idle.contains("`continue`"), - "an idle answer must say the last turn ended on its own and how to give it another: \ - {idle}" - ); - let killed = describe_status(&StatusFacts { - killed: Some(libc::SIGKILL), - session_exists: true, - ..StatusFacts::new("n") - }) - .expect("killed status"); - assert!( - killed.contains("killed") && killed.contains("`continue`"), - "a killed answer must name the kill and say resuming is still possible: {killed}" - ); - let missing = describe_status(&StatusFacts::new("n")) - .expect_err("nothing tracked and nothing on disk is an error, not a state"); - assert!( - missing.to_string().contains("`start`"), - "the no-such-session answer must point at what creates one: {missing}" - ); - } - - #[test] - fn a_killed_turn_and_a_clean_one_do_not_land_in_the_same_state() { - // The whole path a real turn takes, minus the process: what the - // driver returned -> what the daemon records -> what `status` says. - let state = State::new(PathBuf::from("/dev/null"), signal_url()); - for (name, outcome) in [ - ("gone", Err(signalled_exit(libc::SIGKILL))), - ("done", Ok(())), - ] { - assert!(state.reserve(name)); - state.finish_turn(name, &classify_end(outcome, None)); - assert_eq!( - state.occupancy(name), - None, - "the turn is over either way — nothing stays tracked as running" - ); - } - assert_eq!(state.killed_by("gone"), Some(9)); - assert_eq!(state.killed_by("done"), None); - - let gone = describe_status(&StatusFacts { - killed: state.killed_by("gone"), - session_exists: true, - ..StatusFacts::new("gone") - }) - .expect("status"); - let done = describe_status(&StatusFacts { - killed: state.killed_by("done"), - session_exists: true, - ..StatusFacts::new("done") - }) - .expect("status"); - assert!(gone.contains("killed"), "{gone}"); - assert!(done.contains("idle"), "{done}"); - } - - #[test] - fn a_new_turn_clears_the_previous_turn_s_kill() { - let state = State::new(PathBuf::from("/dev/null"), signal_url()); - state.finish_turn("n", &TurnEnd::Killed { signal: 9 }); - assert_eq!(state.killed_by("n"), Some(9)); - // What `spawn_and_track` does once the next turn is confirmed - // spawned, and then what its own clean end does. - state.clear_kill("n"); - assert_eq!(state.killed_by("n"), None); - state.finish_turn("n", &TurnEnd::Complete); - assert_eq!( - state.killed_by("n"), - None, - "a turn that finished must not leave the old kill standing" - ); - } - - #[test] - fn the_killed_todo_does_not_read_like_a_completion() { - let complete = turn_end_summary("n", &TurnEnd::Complete, None); - let killed = turn_end_summary("n", &TurnEnd::Killed { signal: 9 }, None); - assert_eq!( - complete, "subagent `n` finished: turn complete", - "the ordinary completion todo is unchanged" - ); - assert!( - killed.contains("KILLED mid-turn") && killed.contains("SIGKILL (signal 9)"), - "the killed todo must state the kill and the signal: {killed}" - ); - assert!( - !killed.contains("finished"), - "the one notification pushed without being asked must not read as a finished turn: \ - {killed}" - ); - assert_ne!(complete, killed); - } - - #[test] - fn continue_tells_the_caller_it_is_resuming_a_killed_session() { - let plain = note_resumed_after_kill("subagent `n` started", None); - assert_eq!( - plain, "subagent `n` started", - "an ordinary resume is unchanged" - ); - let after_kill = note_resumed_after_kill("subagent `n` started", Some(libc::SIGKILL)); - assert!( - after_kill.contains("killed") && after_kill.contains("SIGKILL (signal 9)"), - "resuming a killed session is allowed, but the caller has to be told: {after_kill}" - ); - } - - #[test] - fn describe_signal_names_the_ones_that_end_a_subagent() { - assert_eq!(describe_signal(9), "SIGKILL (signal 9)"); - assert_eq!(describe_signal(15), "SIGTERM (signal 15)"); - assert_eq!(describe_signal(2), "SIGINT (signal 2)"); - assert_eq!(describe_signal(7), "signal 7"); - } - - #[test] - fn build_config_defaults_cwd_to_the_work_dir_when_no_dir_is_given() { - let with = build_config("n", None, None, None, Some("/tmp/some-worktree"), None); - assert_eq!(with.cwd, Some(PathBuf::from("/tmp/some-worktree"))); - - let root = std::env::temp_dir().join(format!( - "hive-subagent-mcp-test-work-dir-{}", - std::process::id() - )); - let state = root.join("state"); - let work = root.join("work"); - std::fs::create_dir_all(&state).unwrap(); - // SAFETY: test-only env mutation; the other `build_config` tests pass - // an explicit `dir` or read nothing derived from the state dir. - unsafe { - std::env::set_var("HYPERHIVE_STATE_DIR", &state); - } - - let absent = build_config("n", None, None, None, None, None); - std::fs::create_dir_all(&work).unwrap(); - let present = build_config("n", None, None, None, None, None); - - // SAFETY: see above. - unsafe { - std::env::remove_var("HYPERHIVE_STATE_DIR"); - } - let _ = std::fs::remove_dir_all(&root); - - assert_eq!( - absent.cwd, None, - "a work dir that isn't there yet must not become a spawn cwd" - ); - assert_eq!(present.cwd, Some(work)); - } - - #[test] - fn build_config_sets_effort_alongside_model() { - let config = build_config( - "n", - Some("opus".to_owned()), - Some("high".to_owned()), - None, - None, - None, - ); - assert_eq!(config.model, Some("opus".to_owned())); - assert_eq!(config.effort, Some("high".to_owned())); - } - - #[test] - fn an_event_starts_the_liveness_clock_and_the_turn_ending_stops_it() { - let state = State::new(PathBuf::from("/dev/null"), signal_url()); - assert_eq!( - state.last_event_age("n"), - None, - "a name that never spawned has no clock to read" - ); - state.note_event("n"); - assert!( - state.last_event_age("n").is_some(), - "the first event must give `status` an age to report" - ); - state.finish_turn("n", &TurnEnd::Complete); - assert_eq!( - state.last_event_age("n"), - None, - "the age describes a turn in flight — a finished turn's leftover age would read as a \ - stall that never happened" - ); - } - - #[test] - fn a_later_event_resets_the_age_rather_than_letting_it_climb() { - // The distinction the whole record exists for: a child still - // producing output must not accumulate the age of a wedged one. - let state = State::new(PathBuf::from("/dev/null"), signal_url()); - state.note_event("n"); - std::thread::sleep(Duration::from_millis(20)); - let before = state.last_event_age("n").expect("clock started"); - state.note_event("n"); - let after = state.last_event_age("n").expect("clock still running"); - assert!( - after < before, - "a fresh event must reset the age, not extend it: {after:?} vs {before:?}" - ); - } - - #[test] - fn the_liveness_clock_does_not_cross_names() { - let state = State::new(PathBuf::from("/dev/null"), signal_url()); - state.note_event("a"); - assert_eq!( - state.last_event_age("b"), - None, - "one subagent's output says nothing about another's" - ); - } - - #[test] - fn every_sink_callback_counts_as_liveness() { - // All three, deliberately: a stderr line or a non-JSON stdout line is - // proof the child is alive exactly as much as a stream-json event, - // and reporting a live subagent as wedged is the failure that costs. - use hive_claude::Sink as _; - - fn fresh() -> (Arc, LivenessSink) { - let state = Arc::new(State::new(PathBuf::from("/dev/null"), signal_url())); - let sink = LivenessSink { - state: Arc::clone(&state), - name: "n".to_owned(), - info: Arc::default(), - verdict: None, - }; - (state, sink) - } - - let (state, sink) = fresh(); - sink.on_event(&serde_json::json!({"type": "system"})); - assert!( - state.last_event_age("n").is_some(), - "a stream-json event is liveness" - ); - - let (state, sink) = fresh(); - sink.on_stdout_line("not json"); - assert!( - state.last_event_age("n").is_some(), - "so is a stdout line that didn't parse as JSON" - ); - - let (state, sink) = fresh(); - sink.on_stderr_line("some chatter"); - assert!( - state.last_event_age("n").is_some(), - "so is a stderr line — anything the child says at all counts" - ); - } - - #[test] - fn a_running_status_reports_the_age_and_an_idle_one_does_not() { - let running = describe_status(&StatusFacts { - occupancy: Some(Occupancy::Running), - last_event_age: Some(Duration::from_secs(4)), - ..StatusFacts::new("n") - }) - .expect("running status"); - assert!( - running.contains("Last event 4s ago"), - "a running answer must carry the age — the one part of it a caller can act on: \ - {running}" - ); - let wedged = describe_status(&StatusFacts { - occupancy: Some(Occupancy::Running), - last_event_age: Some(Duration::from_mins(15)), - ..StatusFacts::new("n") - }) - .expect("running status"); - assert!( - wedged.contains("Last event 900s ago"), - "the wedged case is the one this exists for: {wedged}" - ); - assert_ne!( - running, wedged, - "4s-ago and 900s-ago must not render identically — collapsing them back together is \ - the bug this reports" - ); - - let idle = describe_status(&StatusFacts { - session_exists: true, - ..StatusFacts::new("n") - }) - .expect("idle status"); - assert!( - !idle.contains("Last event"), - "an idle session has no in-flight turn whose progress an age would describe: {idle}" - ); - } - - #[test] - fn a_running_status_still_answers_when_the_turn_ended_mid_call() { - // `status` reads `running` and the clock under separate locks, so a - // turn can finish between the two. The answer drops the age rather - // than inventing one. - let raced = describe_status(&StatusFacts { - occupancy: Some(Occupancy::Running), - ..StatusFacts::new("n") - }) - .expect("running status"); - assert!( - raced.contains("is running") && !raced.contains("Last event"), - "a missing age must cost the sentence, not the answer: {raced}" - ); - } - - #[test] - fn a_missed_resume_names_the_directory_that_was_searched() { - // The failure that cost an afternoon: the session existed, just not - // where this daemon looked. claude's own message names the value it - // failed to match but never the directory, which is the fact that - // was missing. - let searched = "(searched /home/agent/.claude for cwd /home/agent/work; if it was started \ - elsewhere, pass the `dir` it was started in)"; - let end = classify_end(Err(hive_claude::Error::SessionNotFound), Some(searched)); - let TurnEnd::Failed(msg) = end else { - panic!("a missed resume is a failed turn"); - }; - assert!( - msg.contains("no session matched"), - "claude's own diagnosis must survive: {msg}" - ); - assert!( - msg.contains("/home/agent/.claude") && msg.contains("/home/agent/work"), - "and the search location must be appended to it: {msg}" - ); - assert!( - msg.contains("pass the `dir` it was started in"), - "naming the directory is only half of it — say what to do about it: {msg}" - ); - } - - #[test] - fn only_a_missed_resume_gets_the_search_location() { - // A `start` never passes one (nothing to resume), and an unrelated - // failure must not be decorated with a location that had no part in - // it. - let no_hint = classify_end(Err(hive_claude::Error::SessionNotFound), None); - assert_eq!( - no_hint, - TurnEnd::Failed( - "claude error: no session matched the requested id or title".to_owned() - ), - "with no resolvable location the underlying error still reaches the caller, plain" - ); - - let unrelated = classify_end(Err(hive_claude::Error::PromptTooLong), Some("(searched …)")); - let TurnEnd::Failed(msg) = unrelated else { - panic!("an overflowed context is a failed turn"); - }; - assert!( - !msg.contains("searched"), - "a context overflow has nothing to do with where the session lives: {msg}" - ); - } - - #[test] - fn searched_location_names_the_same_place_the_store_would_look() { - // The point of reading both halves off the `Config` rather than - // re-deriving them: the location reported must be the one actually - // searched, so it can't drift from `build_store`/the driver. - let cwd = std::env::current_dir().expect("a cwd"); - let config = build_config("n", None, None, None, Some(&cwd.to_string_lossy()), None); - let Some(located) = searched_location(&config) else { - // No `HOME` in this environment — nothing to compare against. - return; - }; - let home = config.resolved_claude_home().expect("home resolved"); - let resolved_cwd = config.resolved_cwd().expect("cwd resolved"); - assert!( - located.contains(&home.display().to_string()) - && located.contains(&resolved_cwd.display().to_string()), - "both halves must come from the config's own resolution: {located}" - ); - } - - /// The `Failed` end a real missed resume produces, message and all — - /// `classify_end`'s own output for the error the driver raises when - /// `--resume` matches nothing. - fn missed_resume() -> TurnEnd { - classify_end( - Err(hive_claude::Error::SessionNotFound), - Some( - "(searched /home/agent/.claude for cwd /home/agent/work; if it was started \ - elsewhere, pass the `dir` it was started in)", - ), - ) - } - - #[tokio::test] - async fn a_continue_whose_resume_missed_is_an_error_not_a_started_message() { - // The whole point of the bounded wait: a `continue` naming a session - // that isn't there must fail the tool call, not answer "started" and - // leave the real answer to a todo nobody is waiting on any more. - let (tx, rx) = oneshot::channel(); - tx.send(ResumeVerdict::Ended(missed_resume())) - .map_err(|_| ()) - .expect("the waiter is still listening"); - let err = await_resume(rx) - .await - .expect_err("a missed resume must reach the caller as an error"); - let msg = err.to_string(); - assert!( - msg.contains("no session matched"), - "claude's own diagnosis is the error: {msg}" - ); - assert!( - msg.contains("pass the `dir` it was started in"), - "and the searched location travels with it: {msg}" - ); - } - - #[tokio::test(start_paused = true)] - async fn a_turn_that_got_underway_answers_without_waiting_out_the_grace() { - // A successful `continue` must not pay a fixed delay — it returns on - // the first sign of the turn, not on the bound. Paused time makes - // that measurable: the clock only advances if something awaits it. - let (tx, rx) = oneshot::channel(); - tx.send(ResumeVerdict::Underway) - .map_err(|_| ()) - .expect("the waiter is still listening"); - let started = tokio::time::Instant::now(); - await_resume(rx) - .await - .expect("an underway turn is not an error"); - assert!( - started.elapsed() < RESUME_GRACE, - "a turn that spoke must settle the wait immediately, not on the bound: {:?}", - started.elapsed() - ); - } - - #[tokio::test(start_paused = true)] - async fn a_turn_that_neither_speaks_nor_exits_is_reported_as_started() { - // The bound is a floor under a child that does nothing at all. The - // sender is held open for the whole wait, so only the timeout can - // end it. - let (tx, rx) = oneshot::channel::(); - let started = tokio::time::Instant::now(); - await_resume(rx) - .await - .expect("a silent child is not a failed resume"); - assert!( - started.elapsed() >= RESUME_GRACE, - "the wait must actually run to the bound: {:?}", - started.elapsed() - ); - drop(tx); - } - - #[tokio::test] - async fn an_early_end_that_is_not_a_failure_still_reads_as_started() { - // A turn that completed, or that a concurrent `interrupt` killed, - // inside the grace: both ended a turn that genuinely began, and both - // have a todo of their own to explain themselves. - for end in [TurnEnd::Complete, TurnEnd::Killed { signal: 9 }] { - let (tx, rx) = oneshot::channel(); - tx.send(ResumeVerdict::Ended(end.clone())) - .map_err(|_| ()) - .expect("the waiter is still listening"); - assert!( - await_resume(rx).await.is_ok(), - "{end:?} ended a turn that started — only a failure is the caller's error" - ); - } - } - - #[test] - fn only_the_first_verdict_is_reported_and_only_to_a_live_caller() { - // `settle`'s two jobs: the sink and the background task race for one - // sender, and the winner's `true` is what tells the task the caller - // has already been handed the failure. - let (tx, rx) = oneshot::channel(); - let verdict: VerdictTx = Arc::new(Mutex::new(Some(tx))); - assert!( - settle(Some(&verdict), ResumeVerdict::Underway), - "the first report reaches a listening caller" - ); - assert!( - !settle(Some(&verdict), ResumeVerdict::Ended(missed_resume())), - "the loser of the race has nothing left to send on — and so must still push its todo" - ); - drop(rx); - - let (tx, rx) = oneshot::channel(); - let verdict: VerdictTx = Arc::new(Mutex::new(Some(tx))); - drop(rx); - assert!( - !settle(Some(&verdict), ResumeVerdict::Ended(missed_resume())), - "a caller whose grace already expired is not listening, so its todo must still be \ - pushed" - ); - - assert!( - !settle(None, ResumeVerdict::Underway), - "a `start` has no verdict channel and nobody waiting on one" - ); - } - - #[test] - fn a_terminal_result_event_is_liveness_but_not_proof_the_turn_began() { - // Measured, and the reason the underway signal reads the event's - // kind at all: a resume that matched nothing still emits a - // stream-json `result` event (and stderr chatter) before exiting, so - // treating any callback as "underway" would report every missed - // resume as a successful start. - use hive_claude::Sink as _; - - fn fresh() -> (oneshot::Receiver, LivenessSink) { - let (tx, rx) = oneshot::channel(); - let sink = LivenessSink { - state: Arc::new(State::new(PathBuf::from("/dev/null"), signal_url())), - name: "n".to_owned(), - info: Arc::default(), - verdict: Some(Arc::new(Mutex::new(Some(tx)))), - }; - (rx, sink) - } - - let (mut rx, sink) = fresh(); - sink.on_event(&serde_json::json!({"type": "result", "is_error": true})); - assert!( - rx.try_recv().is_err(), - "the turn's own end-of-turn marker must not settle the wait as underway" - ); - assert!( - sink.state.last_event_age("n").is_some(), - "it is still liveness — the child did say something" - ); - - let (mut rx, sink) = fresh(); - sink.on_stderr_line("Error: --resume requires a valid session ID or session title"); - assert!( - rx.try_recv().is_err(), - "nor does stderr, which a missed resume writes to before it exits" - ); - - let (mut rx, sink) = fresh(); - sink.on_event(&serde_json::json!({"type": "system", "subtype": "init"})); - assert!( - matches!(rx.try_recv(), Ok(ResumeVerdict::Underway)), - "a non-terminal event is a turn in progress, which is the signal continue waits for" - ); - } - - #[test] - fn build_config_defaults_effort_to_medium_when_omitted() { - // Unlike `model`, an omitted `effort` does not fall through to - // claude's own default (`high` on most models) — this daemon picks - // `medium` itself, a deliberate cost-conscious choice for subagent - // work. - let config = build_config("n", None, None, None, None, None); - assert_eq!(config.effort, Some("medium".to_owned())); - } - - // ---- turn continuation ------------------------------------------------- - - /// A state with `name` mid-run against `goal`, as `start` would have left - /// it: reserved, goal registered, on turn one of `max_turns`. - fn mid_run(name: &str, goal: &str, max_turns: u32) -> State { - let state = State::new(PathBuf::from("/dev/null"), signal_url()); - state.reserve(name); - state.set_goal(name, Some(goal.to_owned()), max_turns); - state - } - - #[test] - fn a_session_with_no_goal_stops_after_one_turn() { - // The pre-continuation shape, and the reason `goal` is what switches - // the loop on rather than a separate flag: nothing to continue - // toward is the same fact as nothing to continue. - let state = mid_run("n", "unused", 5); - state.set_goal("n", None, 5); - assert!( - matches!( - state.plan_after_turn("n"), - Continuation::Stop(StopReason::Done) - ), - "without a goal the first completed turn ends the run" - ); - assert_eq!( - state.turns("n"), - None, - "and there is no turn budget to report being partway through" - ); - } - - #[test] - fn a_goal_keeps_spending_turns_until_the_cap_and_then_stops() { - let state = mid_run("n", "make the gate pass", 3); - assert_eq!(state.turns("n"), Some((1, 3)), "the first turn is 1 of 3"); - - for expected in [2, 3] { - let Continuation::Continue { prompt } = state.plan_after_turn("n") else { - panic!("turn {expected} of 3 must still be spent"); - }; - assert!( - prompt.contains("make the gate pass"), - "the re-prompt continues toward the goal verbatim: {prompt}" - ); - assert!( - prompt.contains("have not reported the goal reached"), - "and says the one thing the subagent can't observe for itself: {prompt}" - ); - assert_eq!(state.turns("n"), Some((expected, 3))); - } - - assert_eq!( - state.plan_after_turn("n"), - Continuation::Stop(StopReason::TurnCap { turns: 3 }), - "the cap is the number of turns run, not one more" - ); - assert_eq!( - state.turns("n"), - Some((3, 3)), - "a capped run must not advance past its own cap" - ); - } - - #[test] - fn the_default_cap_is_five_turns() { - // The number is the feature's own, not a value tuned here — pinned so - // a later edit to `DEFAULT_MAX_TURNS` has to be deliberate. - assert_eq!(DEFAULT_MAX_TURNS, 5); - } - - #[test] - fn both_signals_stop_the_continuation_before_the_cap_is_reached() { - // The issue's own words: "both stop goal continues". Turn one of - // five, so only the signal can be what stopped it. - for stop in [ - StopReason::GoalReached(Some("wrote the fix".to_owned())), - StopReason::NeedHelp("no credential for the registry".to_owned()), - ] { - let state = mid_run("n", "a goal", 5); - state.record_stop("n", stop.clone()); - assert_eq!( - state.plan_after_turn("n"), - Continuation::Stop(stop.clone()), - "{stop:?} must end the run with turns still on the clock" - ); - assert_eq!( - state.turns("n"), - Some((1, 5)), - "and must not have spent one on the way out" - ); - } - } - - /// A stand-in for claude that reproduces the one behaviour the cancel - /// turns on: on SIGINT it exits **zero**. The real `claude --print` does - /// exactly this — it writes its terminal `result` event and shuts down - /// cleanly — which is why an interrupted turn is indistinguishable from - /// a completed one by exit status alone, and why `interrupt` cannot rely - /// on the child's death to stop the run. - /// - /// It appends a line to `log` as its very first act, so the file is a - /// count of how many turns the continuation loop actually spawned. Every - /// argument is ignored; the driver's own flags mean nothing here. - /// - /// The wait is `sleep &` + `wait` rather than a plain foreground - /// `sleep`: a POSIX shell runs a pending trap as soon as `wait` returns, - /// but defers it until a *foreground* child has finished — which for a - /// 30-second sleep is long after the test has given up. The background - /// sleep gets its own stdout/stderr for the mirror-image reason: it - /// would otherwise inherit and keep open the pipes the driver reads to - /// EOF, so `RunningClaude::wait` would not return until the orphaned - /// sleep expired, and the turn would look like it was still running. - fn fake_claude(dir: &Path, log: &Path) -> PathBuf { - let script = dir.join("fake-claude"); - write_executable( - &script, - &format!( - "#!/bin/sh\necho turn >> '{}'\ntrap 'exit 0' INT\nsleep 30 >/dev/null 2>&1 &\nwait\n", - log.display() - ), - ); - script - } - - /// How many turns the fake has been spawned for so far. - fn turns_spawned(log: &Path) -> usize { - std::fs::read_to_string(log).map_or(0, |body| body.lines().count()) - } - - #[tokio::test] - async fn an_interrupt_cancels_the_whole_goal_run_and_not_merely_its_turn() { - // The regression, end to end through the real - // continuation loop: a goal run with four turns left is interrupted, - // its child exits cleanly the way claude actually does, and the loop - // must not spawn turn two. - let dir = std::env::temp_dir().join(format!( - "hive-subagent-cancel-{}-{:?}", - std::process::id(), - std::thread::current().id() - )); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let log = dir.join("turns"); - let program = fake_claude(&dir, &log); - - let state = Arc::new(mid_run("n", "carry on indefinitely", 5)); - let config = Config { - program: Some(program), - ..Config::default() - }; - spawn_and_track( - &state, - "n", - &config, - &Attach::Create("n".to_owned()), - "turn one".to_owned(), - None, - ) - .expect("the fake claude spawns"); - - // Wait for the first turn to be genuinely under way before - // interrupting: signalling a child that hasn't run yet would prove - // nothing about the loop. - for _ in 0..100 { - if turns_spawned(&log) == 1 { - break; - } - tokio::time::sleep(Duration::from_millis(50)).await; - } - assert_eq!(turns_spawned(&log), 1, "the first turn never started"); - - interrupt(&state, "n").expect("a running turn is interruptible"); - - // Generous: the fake logs its invocation as its first act, so a - // re-prompt shows up here almost immediately once the loop decides - // to make one. - tokio::time::sleep(Duration::from_millis(1500)).await; - assert_eq!( - turns_spawned(&log), - 1, - "an interrupted goal run must not be re-prompted — that is the whole of the cancel" - ); - assert_eq!( - state.stop_reason("n"), - Some(StopReason::Cancelled), - "and the run must carry a reason saying why it stopped" - ); - std::fs::remove_dir_all(&dir).ok(); - } - - /// A stand-in for claude with a command of its own still running: an - /// inner `sh` writes its pid to `pidfile` and execs `sleep`. It runs in - /// the foreground because a non-interactive shell starts `&` jobs with - /// SIGINT ignored, and its output goes to /dev/null so it cannot hold the - /// driver's pipes open. - fn busy_claude(dir: &Path, pidfile: &Path) -> PathBuf { - let script = dir.join("busy-claude"); - write_executable( - &script, - &format!( - "#!/bin/sh\nsh -c 'echo $$ >\"$1\"; exec sleep 300' sh '{}' >/dev/null 2>&1\n", - pidfile.display() - ), - ); - script - } - - /// Poll `path` until it holds a complete, newline-terminated pid. - async fn read_pid(path: &Path) -> i32 { - for _ in 0..250 { - if let Ok(text) = std::fs::read_to_string(path) - && text.ends_with('\n') - { - return text.trim().parse().expect("pid file holds a pid"); - } - tokio::time::sleep(Duration::from_millis(20)).await; - } - unreachable!("no pid in {} within 5s", path.display()); - } - - /// Whether `pid` is still running. A zombie counts as gone: it has - /// exited, and `kill(pid, 0)` only keeps finding it until it is reaped. - fn is_running(pid: i32) -> bool { - // SAFETY: signal 0 delivers nothing; it only checks that `pid` exists. - if unsafe { libc::kill(pid, 0) } != 0 { - return false; - } - !std::fs::read_to_string(format!("/proc/{pid}/stat")).is_ok_and(|stat| { - stat.rsplit_once(") ") - .is_some_and(|(_, rest)| rest.starts_with('Z')) - }) - } - - #[tokio::test] - async fn an_interrupt_stops_the_commands_the_subagent_started() { - let dir = scratch_dir("group"); - let pidfile = dir.join("grandchild.pid"); - let state = Arc::new(mid_run("n", "carry on indefinitely", 5)); - let config = Config { - program: Some(busy_claude(&dir, &pidfile)), - ..Config::default() - }; - spawn_and_track( - &state, - "n", - &config, - &Attach::Create("n".to_owned()), - "turn one".to_owned(), - None, - ) - .expect("the fake claude spawns"); - let grandchild = read_pid(&pidfile).await; - - interrupt(&state, "n").expect("a running turn is interruptible"); - - let mut alive = is_running(grandchild); - for _ in 0..250 { - if !alive { - break; - } - tokio::time::sleep(Duration::from_millis(20)).await; - alive = is_running(grandchild); - } - if alive { - // SAFETY: `kill(2)` on a pid this test started; keeps a failed - // run from leaving a 300s `sleep` behind. - unsafe { - libc::kill(grandchild, libc::SIGKILL); - } - } - std::fs::remove_dir_all(&dir).ok(); - assert!(!alive, "grandchild {grandchild} outlived the interrupt"); - } - - /// A stand-in for claude that shuts down on SIGINT the way claude does: - /// it writes `interrupted` once the signal arrives, then exits 0 as soon - /// as `release` exists, or after 10s. It writes `ready` once its trap is - /// set. A SIGKILL leaves no `interrupted` behind. - fn graceful_claude(dir: &Path) -> PathBuf { - let script = dir.join("graceful-claude"); - write_executable( - &script, - &format!( - "#!/bin/sh\ncd '{}'\ntrap ': > interrupted; i=0; until [ -e release ] || \ - [ $i -ge 200 ]; do sleep 0.05; i=$((i+1)); done; kill $!; exit 0' INT\n\ - sleep 300 >/dev/null 2>&1 &\n: > ready\nwait\n", - dir.display() - ), - ); - script - } - - /// Spawn [`graceful_claude`] as `n`'s turn and wait until its trap is set. - async fn spawn_graceful(state: &Arc, dir: &Path) { - let config = Config { - program: Some(graceful_claude(dir)), - ..Config::default() - }; - spawn_and_track( - state, - "n", - &config, - &Attach::Create("n".to_owned()), - "turn one".to_owned(), - None, - ) - .expect("the fake claude spawns"); - until("the fake claude sets its trap", || { - dir.join("ready").exists() - }) - .await; - } - - #[tokio::test] - async fn an_interrupt_lets_claude_shut_down_on_sigint() { - let dir = scratch_dir("sigint"); - std::fs::write(dir.join("release"), "").expect("release file"); - let state = Arc::new(mid_run("n", "carry on indefinitely", 5)); - spawn_graceful(&state, &dir).await; - - interrupt(&state, "n").expect("a running turn is interruptible"); - - until("the run ends", || state.occupancy("n").is_none()).await; - let interrupted = dir.join("interrupted").exists(); - std::fs::remove_dir_all(&dir).ok(); - assert!( - interrupted, - "claude must get SIGINT, which it shuts its tool commands down on, never SIGKILL" - ); - assert_eq!(state.killed_by("n"), None, "it exited on its own"); - } - - #[tokio::test] - async fn an_interrupted_name_stays_claimed_until_claude_has_exited() { - let dir = scratch_dir("stopping"); - let state = Arc::new(mid_run("n", "carry on indefinitely", 5)); - spawn_graceful(&state, &dir).await; - - interrupt(&state, "n").expect("a running turn is interruptible"); - until("the fake claude gets the SIGINT", || { - dir.join("interrupted").exists() - }) - .await; - - assert_eq!(state.occupancy("n"), Some(Occupancy::Stopping)); - let status = status(&state, "n", None).expect("status"); - assert!(status.contains("is stopping"), "{status}"); - let refused = continue_(&state, "n", "more".to_owned(), None, None, None) - .await - .expect_err("a second claude must not start on the session"); - assert!(refused.to_string().contains("is stopping"), "{refused}"); - assert!(interrupt(&state, "n").is_err(), "it was already signalled"); - - std::fs::write(dir.join("release"), "").expect("release file"); - until("the run ends", || state.occupancy("n").is_none()).await; - std::fs::remove_dir_all(&dir).ok(); - assert!( - state.reserve("n"), - "the name is free once claude has exited" - ); - } - - #[test] - fn a_cancelled_run_stops_with_turns_still_on_its_clock() { - // The loop half of the same fact, asserted directly: `Cancelled` is - // read where the other stop signals are, ahead of the goal, so it - // stops a run that has four turns left rather than being overridden - // by them. - let state = mid_run("n", "a goal", 5); - state.record_stop("n", StopReason::Cancelled); - assert_eq!( - state.plan_after_turn("n"), - Continuation::Stop(StopReason::Cancelled) - ); - assert_eq!( - state.turns("n"), - Some((1, 5)), - "and must not spend one on the way out" - ); - } - - #[test] - fn a_continue_after_a_cancel_starts_the_run_over() { - // The deliberate other half: a cancel is not a permanent - // state. `continue` clears the reason and hands back a fresh - // allowance, which is what makes `interrupt` a pause an operator can - // undo rather than a session they have to abandon. - let state = mid_run("n", "a goal", 5); - state.record_stop("n", StopReason::Cancelled); - state.clear_stop("n"); - state.restart_turns("n"); - assert_eq!( - state.plan_after_turn("n"), - Continuation::Continue { - prompt: continuation_prompt("n", "a goal", 2, 5) - }, - "a continued session resumes toward its goal" - ); - } - - #[test] - fn a_signal_on_the_last_allowed_turn_outranks_the_cap() { - // Both are true at once, and which one is reported is the difference - // between "it says it finished" and "it ran out of road". - let state = mid_run("n", "a goal", 1); - state.record_stop("n", StopReason::GoalReached(None)); - assert_eq!( - state.plan_after_turn("n"), - Continuation::Stop(StopReason::GoalReached(None)) - ); - } - - #[test] - fn a_subagent_cannot_signal_a_different_session() { - // The requirement itself, and the reason it's a test: two siblings - // running concurrently, each holding exactly one signal URL. Half the - // answer is in `mcp.rs` — neither tool has a `name` argument to put a - // sibling's name in (`the_signal_tools_take_no_session_name` pins - // that). The other half is here: whether the only identity a subagent - // *does* hold, its token, can be made to resolve to anyone else. - let state = State::new(PathBuf::from("/dev/null"), signal_url()); - state.reserve("alpha"); - state.reserve("beta"); - let alpha = token_of(&state.mint_signal_url("alpha")); - let beta = token_of(&state.mint_signal_url("beta")); - assert_ne!(alpha, beta, "two sessions must not share a token"); - - assert_eq!( - state.session_for_signal_token(&alpha).as_deref(), - Some("alpha") - ); - assert_eq!( - state.session_for_signal_token(&beta).as_deref(), - Some("beta") - ); - - // `alpha` signals the only way it can: on its own endpoint, with the - // session resolved from the token rather than supplied by the caller. - let resolved = state - .session_for_signal_token(&alpha) - .expect("alpha's own route resolves"); - need_help(&state, &resolved, "no credential".to_owned(), None); - assert_eq!( - state.stop_reason("alpha"), - Some(StopReason::NeedHelp("no credential".to_owned())) - ); - assert_eq!( - state.stop_reason("beta"), - None, - "a sibling's run must be untouched — there is no route `alpha` holds that reaches it" - ); - - // A subagent does know its siblings' *names* (a brief can mention - // them) — and a name is not a token, which is the whole point. - assert_eq!(state.session_for_signal_token("beta"), None); - assert_eq!(state.session_for_signal_token(&format!("{alpha}0")), None); - } - - #[test] - fn a_token_stops_resolving_once_its_run_is_over() { - // The expiry half of "unknown or expired token ⇒ 404": a finished - // run's config file still names its URL, and that URL must be dead. - let state = State::new(PathBuf::from("/dev/null"), signal_url()); - state.reserve("n"); - let token = token_of(&state.mint_signal_url("n")); - state.finish_turn("n", &TurnEnd::Complete); - assert_eq!( - state.session_for_signal_token(&token), - None, - "the run ended, so the route it was issued must resolve to nothing" - ); - - // Same for a call that never reached a spawn at all. - state.reserve("n"); - let unspawned = token_of(&state.mint_signal_url("n")); - state.release_reservation("n"); - assert_eq!(state.session_for_signal_token(&unspawned), None); - } - - #[test] - fn a_re_minted_url_retires_the_previous_one() { - // A `continue` mints the resumed run its own token; the run before it - // is over, so the URL that run was handed must not still work. - let state = State::new(PathBuf::from("/dev/null"), signal_url()); - let first = token_of(&state.mint_signal_url("n")); - let second = token_of(&state.mint_signal_url("n")); - assert_eq!(state.session_for_signal_token(&first), None); - assert_eq!( - state.session_for_signal_token(&second).as_deref(), - Some("n") - ); - } - - #[test] - fn need_help_is_a_state_a_parent_can_see_without_reading_anything() { - // Requirement in full: it stops the session *and* shows up in - // `status` as its own state, distinct from idle and from killed. - let blocked = describe_status(&StatusFacts { - stop: Some(StopReason::NeedHelp( - "the brief contradicts the code".to_owned(), - )), - turns: Some((2, 5)), - ..StatusFacts::new("n") - }) - .expect("a blocked session is a state, not an error"); - assert!( - blocked.contains("BLOCKED") && blocked.contains("the brief contradicts the code"), - "the block and its reason must both be in the answer: {blocked}" - ); - assert!( - !blocked.contains("Turn 2 of 5"), - "a subagent waiting on an answer needs the answer, not a turn count competing for \ - attention: {blocked}" - ); - assert!( - !blocked.contains("idle"), - "a blocked subagent must not also read as idle: {blocked}" - ); - } - - #[test] - fn turn_cap_status_still_carries_the_turn_count() { - // The turn count is the whole point of a `TurnCap` stop — omitting - // it here (unlike `NeedHelp`) would be the regression a later - // refactor could silently reintroduce. - let capped = describe_status(&StatusFacts { - stop: Some(StopReason::TurnCap { turns: 5 }), - turns: Some((5, 5)), - ..StatusFacts::new("n") - }) - .expect("a capped session is a state, not an error"); - assert!( - capped.contains("Turn 5 of 5"), - "the turn count is the point of a TurnCap status: {capped}" - ); - } - - #[test] - fn a_reported_goal_never_reads_as_a_verified_one() { - // The failure this is built against: `goal_reached` is self-reported - // by a subagent that has just been told it hasn't reached the goal. - // Every surface that renders it has to say so. - let status = describe_status(&StatusFacts { - stop: Some(StopReason::GoalReached(Some( - "refactored the parser".to_owned(), - ))), - ..StatusFacts::new("n") - }) - .expect("status"); - assert!( - status.contains("refactored the parser") && status.contains("claim"), - "status must carry both the report and the fact it's only a report: {status}" - ); - let todo = turn_end_summary( - "n", - &TurnEnd::Complete, - Some(&StopReason::GoalReached(Some( - "refactored the parser".to_owned(), - ))), - ); - assert!( - todo.contains("self-reported, not verified"), - "and so must the todo, which is the half a parent reads unprompted: {todo}" - ); - } - - #[test] - fn a_stop_reason_extends_the_done_message_rather_than_replacing_it() { - // "Extend", not "replace": the observed end of the turn and the - // reason the run stopped are different facts, and dropping the first - // would let a self-reported claim stand where an observation was. - let plain = turn_end_summary("n", &TurnEnd::Complete, None); - for stop in [ - StopReason::GoalReached(None), - StopReason::NeedHelp("blocked".to_owned()), - StopReason::TurnCap { turns: 5 }, - StopReason::Cancelled, - ] { - let extended = turn_end_summary("n", &TurnEnd::Complete, Some(&stop)); - assert!( - extended.starts_with(&plain), - "{stop:?} must extend the done message, not rewrite it: {extended}" - ); - assert!( - extended.len() > plain.len(), - "{stop:?} must actually add something: {extended}" - ); - } - assert_eq!( - turn_end_summary("n", &TurnEnd::Complete, Some(&StopReason::Done)), - plain, - "`Done` has nothing to add — the unextended message already says exactly that" - ); - } - - #[test] - fn the_turn_cap_todo_says_the_harness_limit_was_what_stopped_it() { - // Not a silent stop: the one notification a parent gets unprompted - // has to distinguish "it finished" from "we stopped asking". - let todo = turn_end_summary( - "n", - &TurnEnd::Complete, - Some(&StopReason::TurnCap { turns: 5 }), - ); - assert!( - todo.contains("harness turn limit was reached (5 turns)"), - "the todo must name the limit as the cause: {todo}" - ); - assert!( - todo.contains("without the goal ever being reported reached"), - "and say what that means for the work: {todo}" - ); - } - - #[test] - fn status_reports_the_turn_counter_in_every_state_a_goal_run_reaches() { - for occupancy in [ - Some(Occupancy::Running), - Some(Occupancy::Starting), - Some(Occupancy::Stopping), - None, - ] { - let answer = describe_status(&StatusFacts { - occupancy, - session_exists: true, - turns: Some((3, 5)), - ..StatusFacts::new("n") - }) - .expect("status"); - assert!( - answer.contains("Turn 3 of 5"), - "progress is the point of the counter — it can't be absent from {occupancy:?}: \ - {answer}" - ); - } - let goalless = describe_status(&StatusFacts { - occupancy: Some(Occupancy::Running), - ..StatusFacts::new("n") - }) - .expect("status"); - assert!( - !goalless.contains("Turn "), - "a session with no goal has no budget to be partway through: {goalless}" - ); - } - - #[test] - fn a_running_turn_that_has_already_signalled_says_so() { - // The window a parent would otherwise misread: the subagent has said - // it is blocked, its turn hasn't ended yet, and plain "running" would - // tell the parent to leave it alone. - let answer = describe_status(&StatusFacts { - occupancy: Some(Occupancy::Running), - stop: Some(StopReason::NeedHelp("no credential".to_owned())), - ..StatusFacts::new("n") - }) - .expect("status"); - assert!( - answer.contains("is running") && answer.contains("no credential"), - "both facts are true at once and both have to be in the answer: {answer}" - ); - let quiet = describe_status(&StatusFacts { - occupancy: Some(Occupancy::Running), - stop: Some(StopReason::Done), - ..StatusFacts::new("n") - }) - .expect("status"); - assert!( - !quiet.contains("already signalled"), - "`Done` is not a signal the subagent raised — nothing to announce: {quiet}" - ); - } - - #[test] - fn a_kill_outranks_a_stop_reason_the_subagent_had_already_raised() { - // Both records can be set at once — a subagent calls `goal_reached` - // and something SIGKILLs it before the turn ends. The observed kill - // is the one that can't be a claim. - let answer = describe_status(&StatusFacts { - killed: Some(libc::SIGKILL), - stop: Some(StopReason::GoalReached(None)), - session_exists: true, - ..StatusFacts::new("n") - }) - .expect("status"); - assert!( - answer.contains("was killed"), - "the kill is what happened: {answer}" - ); - assert!( - !answer.contains("goal reached"), - "a claim made just before being killed must not be the headline: {answer}" - ); - } - - #[test] - fn a_continue_gives_a_capped_session_its_allowance_back() { - // `TurnCap` stops the loop, it doesn't retire the session — and the - // parent spending a turn on purpose is not what the cap bounds. - let state = mid_run("n", "a goal", 2); - state.record_stop("n", StopReason::TurnCap { turns: 2 }); - state.clear_stop("n"); - state.restart_turns("n"); - assert_eq!(state.turns("n"), Some((1, 2))); - assert_eq!(state.stop_reason("n"), None); - assert!( - matches!(state.plan_after_turn("n"), Continuation::Continue { .. }), - "with the allowance back, the loop has a turn to spend again" - ); - } - - #[tokio::test] - async fn a_fresh_start_inherits_nothing_from_the_run_before_it() { - // `start` archives the prior session precisely so this is a fresh - // start; a leftover stop reason or report path would make the new run - // report the old one's ending, into the old one's file. - let state = Arc::new(State::new(PathBuf::from("/dev/null"), signal_url())); - state.record_stop("n", StopReason::NeedHelp("old block".to_owned())); - state.set_report_file("n", Some("/tmp/old-report.md")); - state.reserve("n"); - let refused = start(&state, start_request("n")).await; - assert!(refused.is_err(), "the reserved name is refused as before"); - - // The same clearing `start` does once it owns the name. - state.clear_stop("n"); - state.clear_report_file("n"); - assert_eq!(state.stop_reason("n"), None); - assert_eq!(state.report_file("n"), None); - } - - #[test] - fn the_report_path_is_taken_from_the_session_and_never_guessed() { - // Both halves of where it can come from: the brief `start` carried, - // and the subagent saying where it actually wrote. A signal that - // names no path leaves the remembered one alone rather than erasing - // it. - let state = State::new(PathBuf::from("/dev/null"), signal_url()); - assert_eq!( - state.report_file("n"), - None, - "a session nobody told about a report file has none — nothing is inferred" - ); - state.set_report_file("n", Some("/tmp/brief-said.md")); - goal_reached(&state, "n", None, None); - assert_eq!( - state.report_file("n"), - Some(PathBuf::from("/tmp/brief-said.md")), - "a signal with no path must not erase what the brief named" - ); - goal_reached(&state, "n", None, Some("/tmp/actually-wrote.md")); - assert_eq!( - state.report_file("n"), - Some(PathBuf::from("/tmp/actually-wrote.md")), - "and the subagent saying where it wrote is what wins" - ); - } - - #[tokio::test] - async fn the_stop_reason_is_appended_to_the_report_file_the_session_named() { - let dir = std::env::temp_dir().join(format!("hive-subagent-report-{}", std::process::id())); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let path = dir.join("report.md"); - std::fs::write(&path, "# what the subagent wrote\n").expect("seed the report"); - - write_stop_to_report(Some(path.clone()), "n", &StopReason::TurnCap { turns: 5 }).await; - - let body = std::fs::read_to_string(&path).expect("report still readable"); - assert!( - body.starts_with("# what the subagent wrote\n"), - "appended, never rewritten — the subagent wrote that file: {body}" - ); - assert!( - body.contains("harness turn limit was reached (5 turns)"), - "and the stop reason lands in the artifact a parent already reads: {body}" - ); - std::fs::remove_dir_all(&dir).ok(); - } - - #[tokio::test] - async fn an_unwritable_report_path_costs_the_line_and_nothing_else() { - // Best-effort by design: the same sentence is in the todo, so a path - // this daemon can't write is a missing convenience, not a lost fact. - write_stop_to_report( - Some(PathBuf::from("/proc/definitely/not/writable/report.md")), - "n", - &StopReason::Done, - ) - .await; - write_stop_to_report(None, "n", &StopReason::Done).await; - } - - #[test] - fn a_goal_briefing_tells_the_subagent_what_it_cannot_otherwise_know() { - let briefing = goal_briefing("batch-1", "get the gate to pass", 5); - assert!( - briefing.contains("get the gate to pass") && briefing.contains("up to 5 turns"), - "the goal and the budget both have to reach the subagent: {briefing}" - ); - assert!( - briefing.contains("goal_reached") && briefing.contains("need_help"), - "as do the two ways it has to stop the re-prompting: {briefing}" - ); - assert!( - briefing.contains("batch-1"), - "and its own name, which is what those tools are called with: {briefing}" - ); - } - - #[test] - fn a_signal_url_reaches_the_subagent_and_a_status_check_renders_no_config() { - // `turn` actually writes an --mcp-config file (crate::mcp_config::build), - // which resolves `hive_agent_sock::paths::harness_dir` — normally the - // container's injected `HYPERHIVE_HARNESS_DIR`, unset in a plain `cargo - // test` sandbox. Point it at a scratch dir for just this test rather - // than depending on ambient environment; only this test's call path - // reads the var, so there's no cross-test race to sequence around - // (contrast `otel_attrs_append_ambient_value_or_stand_alone` above). - let dir = std::env::temp_dir().join(format!( - "hive-subagent-mcp-test-harness-dir-{}", - std::process::id() - )); - // SAFETY: test-only env mutation; no other test reads this var. - unsafe { - std::env::set_var("HYPERHIVE_HARNESS_DIR", &dir); - } - - // The signal surface is how `goal_reached` is callable at all, so a - // spawned turn's config has to carry it; `status` builds a config - // purely to resolve the store and has no subagent to hand it to. - let turn = build_config("n", None, None, None, None, Some(&signal_url())); - let checked = build_config("n", None, None, None, None, None); - - // SAFETY: see above. - unsafe { - std::env::remove_var("HYPERHIVE_HARNESS_DIR"); - } - let _ = std::fs::remove_dir_all(&dir); - - assert!( - turn.mcp_config.is_some(), - "a turn's config must carry an --mcp-config with the signal surface in it" - ); - assert!( - turn.strict_mcp_config && checked.strict_mcp_config, - "the safety property is unchanged: no ambient MCP discovery either way" - ); - } - - #[test] - fn an_unset_model_whitelist_allows_any_model() { - assert!(check_model(Some("opus"), &local(None)).is_ok()); - } - - #[test] - fn an_unset_model_whitelist_allows_an_omitted_model() { - assert!(check_model(None, &local(None)).is_ok()); - } - - #[test] - fn a_listed_model_is_allowed() { - assert!(check_model(Some("sonnet"), &local(Some("haiku,sonnet,opus"))).is_ok()); - } - - #[test] - fn an_unlisted_model_is_rejected_naming_what_is_permitted() { - let err = check_model(Some("opus"), &local(Some("haiku,sonnet"))) - .expect_err("a model outside the list must be refused") - .to_string(); - assert!( - err.contains("opus") && err.contains("haiku, sonnet"), - "the rejection is all the caller sees, so it must name the model \ - and the permitted ones: {err}" - ); - } - - #[test] - fn a_set_whitelist_still_allows_an_omitted_model() { - assert!( - check_model(None, &local(Some("haiku"))).is_ok(), - "omitting `model` lets claude pick its own default — it is not a \ - choice of model, so there is nothing to gate" - ); - } - - #[test] - fn whitespace_and_empty_entries_are_ignored() { - assert!(check_model(Some("sonnet"), &local(Some(" haiku , sonnet ,, "))).is_ok()); - assert!(check_model(Some("opus"), &local(Some(" haiku , sonnet ,, "))).is_err()); - assert!( - check_model(Some("opus"), &local(Some(" ,, "))).is_ok(), - "a var naming nothing restricts nothing — default open" - ); - } - - fn local(env: Option<&str>) -> ModelList { - ModelList::Local(env.map(str::to_owned)) - } - - fn swarm(models: &[&str]) -> crate::swarm_models::Read { - crate::swarm_models::Read::Current(AgentInference { - subagent_models: Some(models.iter().map(|m| (*m).to_owned()).collect()), - ..AgentInference::default() - }) - } - - fn unset() -> crate::swarm_models::Read { - crate::swarm_models::Read::Current(AgentInference::default()) - } - - fn capped(max: u32) -> crate::swarm_models::Read { - crate::swarm_models::Read::Current(AgentInference { - max_subagents: Some(max), - ..AgentInference::default() - }) - } - - #[test] - fn reserve_under_refuses_a_new_name_at_the_cap_and_takes_one_below_it() { - let state = State::new(PathBuf::from("/dev/null"), signal_url()); - assert_eq!(state.reserve_under("a", Some(2)), Ok(())); - assert_eq!(state.reserve_under("b", Some(2)), Ok(())); - assert_eq!( - state.reserve_under("c", Some(2)), - Err(Refusal::AtCap { running: 2, cap: 2 }) - ); - assert_eq!(state.reserve_under("c", None), Ok(()), "no cap, no limit"); - assert_eq!( - state.reserve_under("a", Some(3)), - Err(Refusal::Taken), - "a taken name at the cap is refused as taken, not as over the cap" - ); - } - - #[test] - fn a_cap_of_zero_refuses_every_start() { - let state = State::new(PathBuf::from("/dev/null"), signal_url()); - assert_eq!( - state.reserve_under("a", Some(0)), - Err(Refusal::AtCap { running: 0, cap: 0 }) - ); - let msg = refused(&state, "a", &Refusal::AtCap { running: 0, cap: 0 }, "").to_string(); - assert!(msg.contains("disabled"), "{msg}"); - } - - /// A run between turns and one winding down both still count. - #[test] - fn every_tracked_slot_counts_toward_the_cap() { - let state = State::new(PathBuf::from("/dev/null"), signal_url()); - assert!(state.reserve("a")); - state.between_turns("a"); - assert!(state.reserve("b")); - state - .running - .lock() - .unwrap() - .insert("b".to_owned(), Slot::Stopping); - assert_eq!( - state.reserve_under("c", Some(2)), - Err(Refusal::AtCap { running: 2, cap: 2 }) - ); - } - - #[test] - fn the_cap_is_the_swarm_value_and_none_otherwise() { - assert_eq!(subagent_cap(Some(&capped(3)), "a"), Some(3)); - assert_eq!(subagent_cap(Some(&unset()), "a"), None); - assert_eq!(subagent_cap(None, "a"), None); - let failed = crate::swarm_models::Read::Failed("no answer".to_owned()); - assert_eq!(subagent_cap(Some(&failed), "a"), None); - } - - #[test] - fn a_failed_cap_read_warns_naming_the_agent_and_the_error() { - let logs = CapturedLogs::default(); - let subscriber = tracing_subscriber::fmt() - .with_writer(logs.clone()) - .with_ansi(false) - .finish(); - let failed = crate::swarm_models::Read::Failed("no answer".to_owned()); - let cap = - tracing::subscriber::with_default(subscriber, || subagent_cap(Some(&failed), "iris")); - assert_eq!(cap, None); - let logged = logs.text(); - assert!( - logged.contains("WARN") && logged.contains("iris") && logged.contains("no answer"), - "{logged}" - ); - } - - /// `start` and `continue` read the cap live: the swarm's cap of 1 refuses - /// a second name, naming the count and the cap. - #[tokio::test] - async fn start_and_continue_refuse_a_new_run_at_the_swarm_cap() { - let (state, reads) = state_reading(capped(1), "busy"); - let started = start(&state, start_on("other", None)).await; - let continued = continue_on(&state, "other", None).await; - for result in [started, continued] { - let err = result.expect_err("one running, cap is 1").to_string(); - assert!( - err.contains("1 subagent running, cap is 1") && err.contains("swarm-ui"), - "{err}" - ); - } - assert_eq!(reads.load(std::sync::atomic::Ordering::Relaxed), 2); - assert_eq!(state.occupancy("other"), None, "nothing was reserved"); - } - - /// The swarm's list replaces the local one, so it can widen it as well - /// as narrow it. - #[test] - fn a_swarm_list_replaces_the_local_one() { - let env = || Some("haiku,sonnet".to_owned()); - let list = model_list(Some(swarm(&["opus"])), env()); - assert_eq!(list, ModelList::Swarm(vec!["opus".to_owned()])); - assert!(check_model(Some("opus"), &list).is_ok()); - assert!(check_model(Some("sonnet"), &list).is_err()); - } - - #[test] - fn without_a_swarm_list_the_local_one_applies() { - let env = || Some("haiku,sonnet".to_owned()); - for read in [None, Some(unset())] { - assert_eq!(model_list(read, env()), local(Some("haiku,sonnet"))); - } - assert_eq!(model_list(Some(unset()), None), local(None)); - } - - #[test] - fn a_failed_read_falls_back_to_the_local_list_and_warns() { - let logs = CapturedLogs::default(); - let subscriber = tracing_subscriber::fmt() - .with_writer(logs.clone()) - .with_ansi(false) - .finish(); - let list = tracing::subscriber::with_default(subscriber, || { - model_list( - Some(crate::swarm_models::Read::Failed("no answer".to_owned())), - Some("haiku".to_owned()), - ) - }); - assert_eq!(list, local(Some("haiku"))); - let logged = logs.text(); - assert!( - logged.contains("WARN") && logged.contains("no answer"), - "the fallback is logged as a warning with the cause: {logged}" - ); - } - - #[test] - fn a_model_outside_the_swarm_list_is_refused_naming_the_list_and_its_source() { - let list = model_list(Some(swarm(&["haiku", "sonnet"])), Some("opus".to_owned())); - let err = check_model(Some("opus"), &list) - .expect_err("a model outside the swarm's list must be refused") - .to_string(); - assert!( - err.contains("opus") - && err.contains("haiku, sonnet") - && err.contains("swarm's subagent_models"), - "{err}" - ); - assert!( - check_model(None, &list).is_ok(), - "an omitted model is not checked against the swarm's list either" - ); - } - - /// A state whose swarm read answers `read` and whose own list is `haiku`, - /// with `name` already reserved: a call that gets past the model check - /// stops at `reserve_under` and spawns nothing. Also the reader's read count. - fn state_reading( - read: crate::swarm_models::Read, - name: &str, - ) -> (Arc, Arc) { - let (reader, reads) = crate::swarm_models::Reader::fixed(read); - let mut state = - State::new(PathBuf::from("/dev/null"), signal_url()).reading_models_from(Some(reader)); - state.local_models = || Some("haiku".to_owned()); - assert!(state.reserve(name)); - (Arc::new(state), reads) - } - - fn start_on(name: &str, model: Option<&str>) -> StartRequest { - StartRequest { - model: model.map(str::to_owned), - ..start_request(name) - } - } - - async fn continue_on( - state: &Arc, - name: &str, - model: Option<&str>, - ) -> anyhow::Result { - continue_( - state, - name, - "go".to_owned(), - model.map(str::to_owned), - None, - None, - ) - .await - } - - /// The refusal comes from the model check, ahead of `reserve_under`'s. - #[tokio::test] - async fn start_and_continue_refuse_a_model_outside_the_swarm_list_before_reserving() { - let (state, reads) = state_reading(swarm(&["sonnet"]), "n"); - let started = start(&state, start_on("n", Some("opus"))).await; - let continued = continue_on(&state, "n", Some("opus")).await; - for result in [started, continued] { - let err = result - .expect_err("opus is outside the swarm's list") - .to_string(); - assert!(err.contains("swarm's subagent_models"), "{err}"); - } - assert_eq!(reads.load(std::sync::atomic::Ordering::Relaxed), 2); - } - - #[tokio::test] - async fn start_and_continue_take_a_swarm_listed_model_the_local_list_lacks() { - let (state, _) = state_reading(swarm(&["opus"]), "n"); - let started = start(&state, start_on("n", Some("opus"))).await; - let continued = continue_on(&state, "n", Some("opus")).await; - for result in [started, continued] { - let err = result.expect_err("the name is reserved").to_string(); - assert!(err.contains("already running"), "{err}"); - } - } - - /// The key is read without a model too, for the cap; no model is checked. - #[tokio::test] - async fn start_and_continue_without_a_model_skip_the_model_check() { - let (state, reads) = state_reading(swarm(&["sonnet"]), "n"); - let started = start(&state, start_on("n", None)).await; - let continued = continue_on(&state, "n", None).await; - for result in [started, continued] { - let err = result.expect_err("the name is reserved").to_string(); - assert!(err.contains("already running"), "{err}"); - } - assert_eq!(reads.load(std::sync::atomic::Ordering::Relaxed), 2); - } - - /// A `tracing` writer whose output a test can read back. - #[derive(Clone, Default)] - struct CapturedLogs(Arc>>); - - impl CapturedLogs { - fn text(&self) -> String { - String::from_utf8_lossy(&self.0.lock().unwrap()).into_owned() - } - } - - impl std::io::Write for CapturedLogs { - fn write(&mut self, buf: &[u8]) -> std::io::Result { - self.0.lock().unwrap().extend_from_slice(buf); - Ok(buf.len()) - } - fn flush(&mut self) -> std::io::Result<()> { - Ok(()) - } - } - - impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for CapturedLogs { - type Writer = Self; - fn make_writer(&'a self) -> Self::Writer { - self.clone() - } - } - - /// An ACP agent in plain `sh`, after `hive-runtime`'s own test agent. It - /// has one session, `s1`, appends every method it is sent to - /// `.methods` and every `session/prompt` line to ``, and - /// answers each prompt with `end_turn` and a token `usage` — or, in - /// `hold` mode, only once `session/cancel` arrives. The `usage` keeps a - /// plain reply from `hive_runtime::acp::AcpError::EmptyEndTurn`, the - /// same reason `hive-runtime`'s own test agent's replies carry one. - const ACP_AGENT: &str = r#" -prompt= -while IFS= read -r line; do - id=${line#*\"id\":}; id=${id%%[,\}]*} - m=${line#*\"method\":\"}; m=${m%%\"*} - printf '%s\n' "$m" >> "$1.methods" - case $m in - initialize) - printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true}}}}\n' "$id" ;; - session/new) - printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"s1"}}\n' "$id" ;; - session/load) - printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id" ;; - session/prompt) - printf '%s\n' "$line" >> "$1" - if [ "$2" = hold ]; then - prompt=$id - else - printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","usage":{"inputTokens":1,"outputTokens":1}}}\n' "$id" - fi ;; - session/cancel) - if [ -n "$prompt" ]; then - printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"cancelled"}}\n' "$prompt" - prompt= - fi ;; - esac -done -"#; - - fn scratch_dir(tag: &str) -> PathBuf { - let dir = std::env::temp_dir().join(format!( - "hive-subagent-{tag}-{}-{:?}", - std::process::id(), - std::thread::current().id() - )); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("scratch dir"); - dir - } - - /// `state` running its subagents on [`ACP_AGENT`] in `mode`, keeping - /// sessions and the agent's logs in `dir`. - fn on_acp_agent(mut state: State, dir: &Path, mode: &str) -> State { - let script = dir.join("agent.sh"); - std::fs::write(&script, ACP_AGENT).expect("write the ACP agent"); - state.runtime = SubagentRuntime::Acp { - command: AcpCommand { - command: "/bin/sh".into(), - args: vec![ - script.display().to_string(), - dir.join("prompts").display().to_string(), - mode.to_owned(), - ], - env: std::collections::BTreeMap::new(), - api_key_env: None, - }, - sessions: dir.to_path_buf(), - }; - state - } - - /// A config that would run [`fake_claude`], so a test on the ACP runtime - /// can show that claude was never spawned, with claude's session store - /// in `dir` rather than the ambient `HOME`. - fn claude_config(dir: &Path) -> Config { - Config { - program: Some(fake_claude(dir, &dir.join("claude-turns"))), - cwd: Some(dir.to_path_buf()), - claude_config_dir: Some(dir.join("claude-home")), - ..Config::default() - } - } - - fn lines(path: &Path) -> Vec { - std::fs::read_to_string(path) - .map(|body| body.lines().map(str::to_owned).collect()) - .unwrap_or_default() - } - - async fn until(what: &str, done: impl Fn() -> bool) { - for _ in 0..200 { - if done() { - return; - } - tokio::time::sleep(Duration::from_millis(50)).await; - } - panic!("timed out waiting until {what}"); - } - - #[tokio::test] - async fn a_claude_parent_runs_its_subagents_on_claude() { - let dir = scratch_dir("runtime-claude"); - let state = Arc::new(State::new(PathBuf::from("/dev/null"), signal_url())); - assert!(state.reserve("n")); - - start_on_runtime(&state, "n", claude_config(&dir), None, "go".into()) - .expect("the fake claude spawns"); - until("claude runs the turn", || { - turns_spawned(&dir.join("claude-turns")) == 1 - }) - .await; - interrupt(&state, "n").expect("a running claude turn is interruptible"); - until("the run ends", || state.occupancy("n").is_none()).await; - - // This `start` had no goal, so the fake claude's clean exit after - // SIGINT (`TurnEnd::Complete`) is exactly the case that used to - // report "finished: turn complete" with no sign it was interrupted. - // `plan_after_turn` checks `stop_reason` before it checks `goals`, so - // the recorded `Cancelled` survives even here — this is the - // non-goal case the goal-run-cancel fix left unverified. - assert_eq!( - state.stop_reason("n"), - Some(StopReason::Cancelled), - "a plain (non-goal) interrupted turn must still record why it stopped" - ); - - assert!( - !acp_session_file(&dir, "n").exists() && !dir.join("prompts.methods").exists(), - "a claude agent's subagent never touches an ACP agent" - ); - std::fs::remove_dir_all(&dir).ok(); - } - - /// A stand-in for claude's session store. `--name` writes - /// `$CLAUDE_CONFIG_DIR/projects//session-.jsonl` carrying a - /// `custom-title` event. `--resume` takes an id from the cwd's project - /// dir, or a title matched against every live session under `projects/` - /// — each project dir standing for a worktree of one repo, which is how - /// far claude 2.1.287 looks for a title — and refuses unless exactly one - /// matches. Each attach is logged to `$CLAUDE_CONFIG_DIR/attaches`. - const SESSION_CLAUDE: &str = r#"#!/bin/sh -cat >/dev/null -projects="$CLAUDE_CONFIG_DIR/projects" -here="$projects/$(pwd -P | tr '/.' '--')" -while [ $# -gt 0 ]; do - case "$1" in - --name) mode=create; arg=$2; shift ;; - --resume) mode=resume; arg=$2; shift ;; - esac - shift -done -if [ "$mode" = create ]; then - n=$(cat "$CLAUDE_CONFIG_DIR/count" 2>/dev/null || echo 0) - echo $((n + 1)) > "$CLAUDE_CONFIG_DIR/count" - id="session-$n" - mkdir -p "$here" - printf '{"type":"custom-title","customTitle":"%s"}\n' "$arg" > "$here/$id.jsonl" -elif [ -f "$here/$arg.jsonl" ]; then - id=$arg -else - matches=$(grep -l "\"customTitle\":\"$arg\"" "$projects"/*/*.jsonl 2>/dev/null) - count=$(printf '%s' "$matches" | grep -c .) - if [ "$count" -ne 1 ]; then - echo "Error: --resume \"$arg\" matches $count sessions" >&2 - exit 1 - fi - id=$(basename "$matches" .jsonl) -fi -echo "$mode $id" >> "$CLAUDE_CONFIG_DIR/attaches" -echo '{"type":"system","subtype":"init"}' -echo '{"type":"result","subtype":"success","is_error":false}' -"#; - - /// Write an executable script from a child process rather than from - /// this one: a write fd on it held here could be inherited by a child - /// another test thread forks, and exec'ing a file some process still - /// holds open for writing fails with `ETXTBSY`. - fn write_executable(path: &Path, body: &str) { - let status = std::process::Command::new("/bin/sh") - .args([ - "-c", - r#"printf '%s' "$1" > "$2" && chmod 755 "$2""#, - "sh", - body, - ]) - .arg(path) - .status() - .expect("run /bin/sh"); - assert!(status.success(), "writing {} failed", path.display()); - } - - #[tokio::test] - async fn resuming_a_name_reused_in_a_sibling_worktree_attaches_to_its_newest_session() { - // `n` started once in a sibling worktree, then twice here — the - // second archiving the first — leaves two live sessions titled `n`, - // which claude refuses to resume by title. Both a goal run's next - // turn and a `continue` must resume the session the last `start` - // here created. - let root = scratch_dir("resume-newest"); - let (here, sibling) = (root.join("here"), root.join("sibling")); - let home = root.join("claude-home"); - for dir in [&here, &sibling, &home] { - std::fs::create_dir_all(dir).expect("scratch subdir"); - } - let program = root.join("session-claude"); - write_executable(&program, SESSION_CLAUDE); - let config = |cwd: &Path| Config { - program: Some(program.clone()), - cwd: Some(cwd.to_path_buf()), - claude_config_dir: Some(home.clone()), - ..Config::default() - }; - let attaches = || lines(&home.join("attaches")); - let state = Arc::new(State::new(PathBuf::from("/dev/null"), signal_url())); - - for (cwd, goal) in [(&sibling, None), (&here, None), (&here, Some("g"))] { - assert!(state.reserve("n")); - state.clear_stop("n"); - state.set_goal("n", goal.map(str::to_owned), 2); - start_on_runtime(&state, "n", config(cwd), None, "go".into()) - .expect("the fake claude spawns"); - until("the run ends", || state.last_event_age("n").is_none()).await; - } - assert_eq!( - attaches(), - [ - "create session-0", - "create session-1", - "create session-2", - "resume session-2" - ], - "the goal run's second turn must resume its own session, not the title" - ); - - state.set_goal("n", None, 1); - state.clear_stop("n"); - assert!(state.reserve("n")); - let (tx, rx) = oneshot::channel(); - let verdict: VerdictTx = Arc::new(Mutex::new(Some(tx))); - continue_on_runtime(&state, "n", config(&here), None, "again".into(), &verdict) - .expect("the fake claude spawns"); - await_resume(rx) - .await - .expect("a title shared with a sibling worktree must not fail the continue"); - until("the continue's turn ends", || { - state.last_event_age("n").is_none() - }) - .await; - assert_eq!( - attaches(), - [ - "create session-0", - "create session-1", - "create session-2", - "resume session-2", - "resume session-2" - ], - "the continue must add its own resume of the session, not of the title" - ); - std::fs::remove_dir_all(&root).ok(); - } - - #[tokio::test] - async fn resuming_where_no_session_is_on_disk_is_refused_without_spawning() { - // `n` lives only in the sibling worktree, where claude would resolve - // the bare title; resuming from `here` must refuse instead. - let root = scratch_dir("resume-refused"); - let (here, sibling) = (root.join("here"), root.join("sibling")); - let home = root.join("claude-home"); - for dir in [&here, &sibling, &home] { - std::fs::create_dir_all(dir).expect("scratch subdir"); - } - let program = root.join("session-claude"); - write_executable(&program, SESSION_CLAUDE); - let config = |cwd: &Path| Config { - program: Some(program.clone()), - cwd: Some(cwd.to_path_buf()), - claude_config_dir: Some(home.clone()), - ..Config::default() - }; - let state = Arc::new(State::new(PathBuf::from("/dev/null"), signal_url())); - assert!(state.reserve("n")); - state.clear_stop("n"); - start_on_runtime(&state, "n", config(&sibling), None, "go".into()) - .expect("the fake claude spawns"); - until("the run ends", || state.last_event_age("n").is_none()).await; - - let searched = SessionStore::new(&home, &here).project_dir(); - assert!(state.reserve("n")); - let (tx, rx) = oneshot::channel(); - let verdict: VerdictTx = Arc::new(Mutex::new(Some(tx))); - let refused = - continue_on_runtime(&state, "n", config(&here), None, "again".into(), &verdict) - .expect_err("no session titled `n` under `here`"); - assert_eq!( - refused.to_string(), - format!( - "no session titled `n` under {}; pass the `dir` the session was started in", - searched.display() - ) - ); - drop(rx); - assert_eq!( - lines(&home.join("attaches")), - ["create session-0"], - "claude was not spawned, so nothing attached" - ); - assert!(state.last_event_age("n").is_none(), "no turn is tracked"); - - assert!( - resume_target(&config(&sibling), "n").is_ok(), - "the directory it was started in still resumes" - ); - std::fs::remove_dir_all(&root).ok(); - } - - #[test] - fn a_refused_continue_leaves_the_sessions_records_as_they_were() { - // A capped goal session on its last turn, stopped on a signal, with a - // remembered `dir`; the `continue` names a dir holding no session. - let root = scratch_dir("refused-keeps-records"); - let state = Arc::new(State::new(PathBuf::from("/dev/null"), signal_url())); - state.set_goal("n", Some("g".into()), 3); - state.plan_after_turn("n"); - state.plan_after_turn("n"); - state.record_stop("n", StopReason::NeedHelp("blocked on X".into())); - state.resolve_dir("n", Some("/remembered")); - assert_eq!(state.turns("n"), Some((3, 3))); - - assert!(state.reserve("n")); - let (tx, _rx) = oneshot::channel(); - let verdict: VerdictTx = Arc::new(Mutex::new(Some(tx))); - continue_on_runtime( - &state, - "n", - claude_config(&root), - root.to_str(), - "again".into(), - &verdict, - ) - .expect_err("no session under the scratch dir"); - - assert_eq!( - state.stop_reason("n"), - Some(StopReason::NeedHelp("blocked on X".into())), - "`status` still says why the session stopped" - ); - assert_eq!(state.turns("n"), Some((3, 3)), "the budget is not reset"); - assert_eq!( - state.peek_dir("n", None), - Some("/remembered".to_owned()), - "the refused call's dir is not remembered" - ); - std::fs::remove_dir_all(&root).ok(); - } - - #[tokio::test] - async fn an_acp_parent_runs_its_subagents_on_its_acp_agent() { - let dir = scratch_dir("runtime-acp"); - let state = State::new(PathBuf::from("/dev/null"), signal_url()); - let state = Arc::new(on_acp_agent(state, &dir, "answer")); - let role = dir.join("role.md"); - std::fs::write(&role, "ROLE-TEXT").expect("write the role"); - - assert!(state.reserve("n")); - start_on_runtime( - &state, - "n", - claude_config(&dir), - Some(role), - "TRIGGER-ONE".into(), - ) - .expect("the ACP run starts"); - until("the start's run ends", || state.occupancy("n").is_none()).await; - - let prompts = lines(&dir.join("prompts")); - assert_eq!(prompts.len(), 1, "{prompts:?}"); - assert!( - prompts[0].contains("ROLE-TEXT") && prompts[0].contains("TRIGGER-ONE"), - "the first prompt carries the role, since ACP has no system prompt: {prompts:?}" - ); - assert_eq!( - std::fs::read_to_string(acp_session_file(&dir, "n")).unwrap(), - "s1" - ); - - assert!(state.reserve("n")); - let (tx, rx) = oneshot::channel(); - let verdict: VerdictTx = Arc::new(Mutex::new(Some(tx))); - continue_on_runtime( - &state, - "n", - claude_config(&dir), - None, - "TRIGGER-TWO".into(), - &verdict, - ) - .expect("the ACP continue starts"); - await_resume(rx).await.expect("the resumed turn lands"); - until("the continue's run ends", || state.occupancy("n").is_none()).await; - - let prompts = lines(&dir.join("prompts")); - assert_eq!(prompts.len(), 2, "{prompts:?}"); - assert!( - prompts[1].contains("TRIGGER-TWO") && !prompts[1].contains("ROLE-TEXT"), - "the continue resumes the session rather than starting one: {prompts:?}" - ); - assert!( - lines(&dir.join("prompts.methods")).contains(&"session/load".to_owned()), - "the continue's agent process loads the recorded session" - ); - assert_eq!( - turns_spawned(&dir.join("claude-turns")), - 0, - "an ACP agent's subagent never runs claude" - ); - std::fs::remove_dir_all(&dir).ok(); - } - - #[tokio::test] - async fn an_acp_continue_with_no_recorded_session_is_refused() { - let dir = scratch_dir("runtime-acp-missing"); - let state = State::new(PathBuf::from("/dev/null"), signal_url()); - let state = Arc::new(on_acp_agent(state, &dir, "answer")); - let (tx, _rx) = oneshot::channel(); - let verdict: VerdictTx = Arc::new(Mutex::new(Some(tx))); - - let err = continue_on_runtime( - &state, - "n", - claude_config(&dir), - None, - "go".into(), - &verdict, - ) - .expect_err("nothing to resume"); - assert!(err.to_string().contains("no ACP session"), "{err}"); - assert!( - !dir.join("prompts.methods").exists(), - "the agent is never started" - ); - std::fs::remove_dir_all(&dir).ok(); - } - - #[tokio::test] - async fn an_interrupt_cancels_an_acp_goal_run() { - let dir = scratch_dir("runtime-acp-cancel"); - let state = Arc::new(on_acp_agent( - mid_run("n", "carry on indefinitely", 5), - &dir, - "hold", - )); - start_on_runtime(&state, "n", claude_config(&dir), None, "go".into()) - .expect("the ACP run starts"); - until("the first prompt reaches the agent", || { - dir.join("prompts").exists() - }) - .await; - - interrupt(&state, "n").expect("a running ACP turn is interruptible"); - assert_eq!( - state.occupancy("n"), - None, - "an interrupted ACP turn frees its name at once; only claude's stays claimed" - ); - until("the run ends", || state.last_event_age("n").is_none()).await; - - assert_eq!(lines(&dir.join("prompts")).len(), 1, "no second goal turn"); - assert!( - lines(&dir.join("prompts.methods")).contains(&"session/cancel".to_owned()), - "the turn was stopped with `session/cancel`" - ); - assert_eq!(state.stop_reason("n"), Some(StopReason::Cancelled)); - std::fs::remove_dir_all(&dir).ok(); - } - - #[tokio::test] - async fn an_interrupt_before_the_acp_turn_is_live_is_refused() { - let dir = scratch_dir("runtime-acp-early-cancel"); - let state = State::new(PathBuf::from("/dev/null"), signal_url()); - let state = Arc::new(on_acp_agent(state, &dir, "answer")); - assert!(state.reserve("n")); - start_on_runtime(&state, "n", claude_config(&dir), None, "go".into()) - .expect("the ACP run starts"); - - // The test runtime is single-threaded, so the run's task has not - // been polled yet: no turn is in flight. - let err = interrupt(&state, "n").expect_err("nothing to cancel yet"); - assert!(err.to_string().contains("still starting"), "{err}"); - assert_eq!(state.stop_reason("n"), None); - - until("the run ends", || state.occupancy("n").is_none()).await; - assert_eq!(lines(&dir.join("prompts")).len(), 1); - assert_eq!( - state.stop_reason("n"), - Some(StopReason::Done), - "the run was never marked cancelled" - ); - std::fs::remove_dir_all(&dir).ok(); - } - - #[test] - fn an_acp_subagent_gets_the_tools_a_claude_subagent_would() { - let ask = |kind| PermissionAsk { - kind, - mcp_server: None, - }; - let none: &[Permission] = &[]; - let both = &[Permission::WebTools, Permission::Execution]; - for kind in ["read", "edit", "search"] { - assert!(acp_permits(&ask(kind), none), "{kind}"); - } - for kind in ["fetch", "execute"] { - assert!(!acp_permits(&ask(kind), none), "{kind} needs its group"); - assert!(acp_permits(&ask(kind), both), "{kind} with its group"); - } - assert!( - !acp_permits(&ask("delete"), both), - "an unnamed kind is refused" - ); - assert!( - !acp_permits(&ask("other"), both), - "other outside the MCP servers" - ); - let mcp = PermissionAsk { - kind: "other", - mcp_server: Some("subagent_control"), - }; - assert!(acp_permits(&mcp, none)); - } - - fn env_of<'a>(env: &'a [(String, String)], name: &str) -> Option<&'a str> { - env.iter().find(|(n, _)| n == name).map(|(_, v)| v.as_str()) - } - - #[test] - fn a_run_without_a_cgroup_still_starts_at_the_subagent_score() { - let state = State::new(PathBuf::from("/dev/null"), signal_url()).entering_runs(None); - let config = state.entered_config(&Config::default(), None); - assert_eq!(config.program.as_deref(), Some(Path::new("/proc/self/exe"))); - assert_eq!( - env_of(&config.env, "HIVE_RUN_ENTRY_PROGRAM"), - Some("claude") - ); - assert_eq!( - env_of(&config.env, "HIVE_RUN_ENTRY_OOM_SCORE_ADJ"), - Some("900") - ); - assert_eq!(env_of(&config.env, "HIVE_RUN_ENTRY_CGROUP"), None); - - let command = AcpCommand { - command: "agent".to_owned(), - args: Vec::new(), - env: std::collections::BTreeMap::new(), - api_key_env: None, - }; - let command = state.entered_command(command, None); - assert_eq!(command.command, "/proc/self/exe"); - assert_eq!( - command - .env - .get("HIVE_RUN_ENTRY_PROGRAM") - .map(String::as_str), - Some("agent") - ); - assert_eq!( - command - .env - .get("HIVE_RUN_ENTRY_OOM_SCORE_ADJ") - .map(String::as_str), - Some("900") - ); - } - - #[test] - fn runs_are_started_plain_unless_the_daemon_enters_them() { - let state = State::new(PathBuf::from("/dev/null"), signal_url()); - let config = state.entered_config(&Config::default(), None); - assert_eq!(config.program, None); - assert!(config.env.is_empty()); - } -} +mod tests; diff --git a/hive-subagent-mcp/src/session/config.rs b/hive-subagent-mcp/src/session/config.rs new file mode 100644 index 000000000..edc20487d --- /dev/null +++ b/hive-subagent-mcp/src/session/config.rs @@ -0,0 +1,323 @@ +//! What a run is started with: the model list and the swarm's cap, the claude +//! config, the prompts, the session store and the session to resume. + +use super::{AgentInference, Config, Path, PathBuf, SessionStore}; + +/// Env var carrying the nix-configured `services.hyperhive.agent.availableModels` as a +/// comma-separated list, forwarded onto this daemon's unit by +/// `nix/agent-modules/mcp.nix` from the harness unit. +const AVAILABLE_MODELS_ENV: &str = "HIVE_AVAILABLE_MODELS"; + +/// The models this daemon may spawn a subagent on, from +/// [`AVAILABLE_MODELS_ENV`]. `None` when the var is absent. +pub(super) fn available_models() -> Option { + std::env::var(AVAILABLE_MODELS_ENV).ok() +} + +/// The list a named `model` is checked against. +#[derive(Debug, PartialEq, Eq)] +pub(super) enum ModelList { + /// The swarm's `subagent_models` for this agent. + Swarm(Vec), + /// [`AVAILABLE_MODELS_ENV`]; `None` when the var is absent. + Local(Option), +} + +/// The swarm's list when it sets one, else `local`. `read` is `None` when +/// this daemon has no swarm queue to read from; a failed read is logged and +/// falls back to `local`. +pub(super) fn model_list( + read: Option, + local: Option, +) -> ModelList { + use crate::swarm_models::Read; + match read { + Some(Read::Current(AgentInference { + subagent_models: Some(models), + .. + })) => ModelList::Swarm(models), + Some(Read::Failed(error)) => { + tracing::warn!( + %error, + "reading this agent's subagent_models from the swarm failed; checking against \ + {AVAILABLE_MODELS_ENV}" + ); + ModelList::Local(local) + } + Some(Read::Current(_)) | None => ModelList::Local(local), + } +} + +/// The swarm's `max_subagents` for this agent, or `None`, no cap: when it +/// sets none, when `read` is `None` because this daemon has no swarm queue, +/// or when the read failed, which is logged as a warning naming the agent and the error. +pub(super) fn subagent_cap(read: Option<&crate::swarm_models::Read>, agent: &str) -> Option { + use crate::swarm_models::Read; + match read? { + Read::Current(settings) => settings.max_subagents, + Read::Failed(error) => { + tracing::warn!( + agent, + %error, + "reading this agent's subagent settings from the swarm failed; applying no \ + subagent cap" + ); + None + } + } +} + +/// Refuse a `model` the operator hasn't made available to this agent. +/// +/// Default-open on purpose: this is a safety rail, not a security boundary, +/// so an absent list (or one naming nothing) restricts nothing and an +/// agent deployed before this gate existed keeps working unchanged. A `None` +/// model isn't a choice of model either — it lets claude fall back to its own +/// default — so there is nothing to check. +/// +/// # Errors +/// +/// A named model absent from `list`; the message names it, every permitted +/// one and where the list came from, since it is all the caller sees. +pub(super) fn check_model(model: Option<&str>, list: &ModelList) -> anyhow::Result<()> { + let Some(model) = model else { + return Ok(()); + }; + let (allowed, source): (Vec<&str>, &str) = match list { + ModelList::Swarm(models) => ( + models + .iter() + .map(|m| m.trim()) + .filter(|m| !m.is_empty()) + .collect(), + "the swarm's subagent_models for this agent", + ), + ModelList::Local(None) => return Ok(()), + // Split, trim, skip empty tokens. + ModelList::Local(Some(env)) => ( + env.split(',') + .map(str::trim) + .filter(|token| !token.is_empty()) + .collect(), + AVAILABLE_MODELS_ENV, + ), + }; + if allowed.is_empty() + || allowed + .iter() + .any(|entry| entry.eq_ignore_ascii_case(model.trim())) + { + return Ok(()); + } + anyhow::bail!( + "model `{model}` is not available to this agent — {source} permits: {}", + allowed.join(", ") + ); +} + +/// Extend the ambient `OTEL_RESOURCE_ATTRIBUTES` with a `subagent=` +/// attribute, so every token/cost/tool-call data point this subagent's own +/// claude process emits carries it alongside the parent's `agent=` +/// label. `Config.env` applies after the inherited environment, so this one +/// entry overriding the ambient value is the intended shape, not a +/// wholesale replacement. +pub(super) fn subagent_otel_attrs(name: &str) -> String { + match std::env::var("OTEL_RESOURCE_ATTRIBUTES") { + Ok(existing) if !existing.is_empty() => format!("{existing},subagent={name}"), + _ => format!("subagent={name}"), + } +} + +/// Build the `Config` one subagent turn runs against. `model` maps straight +/// onto `Config::model` — `--model`, omitted when `None` so claude falls +/// back to its own default. `effort` does not: an omitted `effort` defaults +/// to `"medium"` here rather than falling through to claude's own default +/// (`high` on most models) — a deliberate hive policy for subagent work +/// specifically, not a reflection of Anthropic's own recommendation, on the +/// same "cheaper than you" cost-consciousness the `base:claude-subagents` +/// skill already asks of `model`. `prompt_file`, when given, becomes +/// `--append-system-prompt-file` — the subagent's task instructions. +/// `dir`, when given, becomes `Config::cwd` (e.g. a prepared worktree); `None` +/// is [`crate::paths::default_cwd`]. +/// Always `--dangerously-skip-permissions --strict-mcp-config --tools` — two +/// gates covering one half each, neither substituting for the other: +/// `strict_mcp_config` over **MCP** tools (no ambient discovery, so exactly +/// what [`crate::mcp_config::build`] renders), `--tools` over **built-in** +/// ones, via [`hive_sh4re::permissions::subagent_builtin_tools_for`] over the +/// agent's permissions ([`crate::swarm_models::permissions_now`]), which +/// documents its one `Bash` exception. `--tools` does not filter `mcp__*`, +/// so the signal tools are unnamed in it (`docs/4-implementation/agent-tools/subagent.md`). +/// +/// `signal_url` is what makes `goal_reached`/`need_help` callable at all: a +/// subagent reaches them over the same streamable-http listener its parent +/// uses, on a route that serves those two tools and nothing else, so being +/// able to say "I'm done" never carries the ability to spawn a subagent of +/// its own. It is also *this* session's own URL — minted per run by +/// [`super::State::mint_signal_url`] and written only into this session's config +/// file — which is where the signal tools get the identity they no longer +/// ask the caller for. `None` — which only `status` passes, building a +/// config purely to resolve the session store — leaves the surface out +/// entirely. +pub(super) fn build_config( + name: &str, + model: Option, + effort: Option, + prompt_file: Option<&str>, + dir: Option<&str>, + signal_url: Option<&str>, +) -> Config { + let tools = hive_sh4re::permissions::subagent_builtin_tools_for( + &crate::swarm_models::permissions_now(), + ) + .join(","); + // Refuse to spawn on an empty `--tools` rather than reason about what it + // would do: what an empty value means is disputed and depends on the + // installed claude release (see `builtin_tools_for`). Nothing here wants + // "a subagent with no built-ins" anyway, so an empty resolution is a bug + // either way, and failing on it is safe under every reading. + assert!( + !tools.is_empty(), + "resolved an empty --tools value — a subagent is never spawned on one, \ + since what an empty value grants is release-dependent" + ); + let mut extra_args = vec![ + "--dangerously-skip-permissions".to_owned(), + "--tools".to_owned(), + tools, + ]; + if let Some(path) = prompt_file { + extra_args.push("--append-system-prompt-file".to_owned()); + extra_args.push(path.to_owned()); + } + Config { + model, + effort: Some(effort.unwrap_or_else(|| "medium".to_owned())), + cwd: dir.map(PathBuf::from).or_else(crate::paths::default_cwd), + mcp_config: crate::mcp_config::build(name, signal_url), + strict_mcp_config: true, + extra_args, + env: vec![( + "OTEL_RESOURCE_ATTRIBUTES".to_owned(), + subagent_otel_attrs(name), + )], + ..Default::default() + } +} + +/// Which file `--append-system-prompt-file` is pointed at, if any, and the +/// prompt this turn actually opens with, for one spawn. +/// +/// **The task is always the turn, never a standing system prompt — with or +/// without a role.** A task baked into the system prompt re-asserts itself +/// as an instruction on every later turn of the session (`continue`, +/// `goal`), not just the one the caller wrote it for; the system prompt is +/// the subagent's standing identity, not a one-shot channel. So the task +/// instructions (`prompt_file`) are always read and folded ahead of +/// `trigger` instead, the one channel that has always carried them. +/// +/// No role: that folded trigger is the whole story — `None` comes back for +/// the system-prompt file, since there is no role text to put there. +/// A role: its text, alone, becomes the system-prompt file under +/// [`crate::paths::harness_dir`] — nothing about the task reaches it. +/// Per session, like the generated `--mcp-config` beside it, so two +/// concurrent `start`s never share a system-prompt file. +/// +/// # Errors +/// +/// Unreadable task instructions, or (with a role) a harness dir that +/// cannot be written. Both refuse the spawn rather than dropping either +/// half — see `docs/4-implementation/agent-tools/subagent.md`. +pub(super) fn system_prompt_and_trigger( + name: &str, + role: Option<&str>, + prompt_file: &str, + trigger: &str, +) -> anyhow::Result<(Option, String)> { + // `harness_dir` panics outside a container (`HYPERHIVE_HARNESS_DIR` + // unset) — read lazily, only when a role means a system-prompt file + // actually needs somewhere to land. `compose_prompt` only touches `dir` + // inside its `Some(role)` branch, so a no-role call never forces this, + // in tests or otherwise. + let dir = role.map_or_else(PathBuf::new, |_| crate::paths::harness_dir()); + compose_prompt(&dir, name, role, prompt_file, trigger) +} + +/// [`system_prompt_and_trigger`] with the harness dir as an argument rather +/// than an ambient container-only environment read — the split a test uses +/// to control where the role-only file lands. +/// +/// # Errors +/// +/// See [`system_prompt_and_trigger`]. +pub(super) fn compose_prompt( + dir: &Path, + name: &str, + role: Option<&str>, + prompt_file: &str, + trigger: &str, +) -> anyhow::Result<(Option, String)> { + let task = std::fs::read_to_string(prompt_file).map_err(|e| { + anyhow::anyhow!("reading the task instructions at {prompt_file} failed: {e}") + })?; + let trigger = format!("{}\n\n{trigger}", task.trim_end()); + let Some(role) = role else { + return Ok((None, trigger)); + }; + let path = render_role_prompt(dir, name, role)?; + Ok((Some(path), trigger)) +} + +/// Write `name`'s system-prompt file — `role`'s text, alone — into `dir`, +/// returning the file's path. Split from [`compose_prompt`] so the +/// directory is an argument rather than an ambient container-only +/// environment read. +/// +/// # Errors +/// +/// A `dir` that cannot be created or written. +fn render_role_prompt(dir: &Path, name: &str, role: &str) -> anyhow::Result { + std::fs::create_dir_all(dir) + .map_err(|e| anyhow::anyhow!("creating {} failed: {e}", dir.display()))?; + let path = dir.join(format!("subagent-system-prompt-{name}.md")); + std::fs::write(&path, role) + .map_err(|e| anyhow::anyhow!("writing {} failed: {e}", path.display()))?; + Ok(path) +} + +/// The [`SessionStore`] a subagent's turn actually runs against — same +/// resolution `hive_claude::Claude` itself uses, so a lookup here can't +/// disagree with what the driver does a moment later. +pub(super) fn build_store(config: &Config) -> std::io::Result { + Ok(SessionStore::new( + config.resolved_claude_home()?, + config.resolved_cwd()?, + )) +} + +/// The session id a resume of `name` hands `--resume`: the live session +/// titled `name` in `config`'s own project dir. +/// +/// claude resolves a *title* across the project dirs of every git worktree +/// of the repo, and refuses when more than one matches; `start` archives only +/// in its own cwd, so a name reused under a sibling worktree's `dir` stays +/// live there. An id names one file, and a name is never handed over in its +/// place: a session that is not in this dir is refused, not looked for +/// elsewhere. +/// +/// # Errors +/// +/// A store that cannot be resolved, or a project dir with no session titled +/// `name`; either message names what was searched. +pub(super) fn resume_target(config: &Config, name: &str) -> anyhow::Result { + let store = build_store(config) + .map_err(|e| anyhow::anyhow!("no session titled `{name}` can be looked for: {e}"))?; + store + .find_by_title(name) + .and_then(|path| path.file_stem().map(|id| id.to_string_lossy().into_owned())) + .ok_or_else(|| { + anyhow::anyhow!( + "no session titled `{name}` under {}; pass the `dir` the session was started in", + store.project_dir().display() + ) + }) +} diff --git a/hive-subagent-mcp/src/session/goal.rs b/hive-subagent-mcp/src/session/goal.rs new file mode 100644 index 000000000..6704d58ad --- /dev/null +++ b/hive-subagent-mcp/src/session/goal.rs @@ -0,0 +1,141 @@ +//! A goal run's side: the briefing and continuation prompts, `goal_reached`, +//! `need_help` and the report file. + +use super::{PathBuf, State, StopReason}; + +/// Append the stop reason to the session's own report file, so the artifact +/// a parent already reads is where the run's ending is recorded too — rather +/// than the parent having to correlate a todo against a file. +/// +/// Best-effort and appended, never rewritten: the subagent wrote that file, +/// and this adds a line under what it wrote instead of taking a position on +/// the rest of it. A path this daemon can't write to is logged and dropped — +/// the todo still carries the same sentence, so nothing is only here. +pub(super) async fn write_stop_to_report(path: Option, name: &str, stop: &StopReason) { + let Some(path) = path else { return }; + let line = format!("\n**Subagent `{name}` stopped:** {}\n", stop.sentence()); + let appended = tokio::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&path) + .await; + let result = match appended { + Ok(mut file) => { + use tokio::io::AsyncWriteExt as _; + // `flush`, not just `write_all`: a `tokio::fs::File` buffers, and + // dropping one discards whatever hasn't been handed to the + // blocking pool — so without this the line is written to nothing + // and the failure is silent. A unit test caught exactly that. + match file.write_all(line.as_bytes()).await { + Ok(()) => file.flush().await, + Err(e) => Err(e), + } + } + Err(e) => Err(e), + }; + if let Err(e) = result { + tracing::warn!( + name, + path = %path.display(), + error = ?e, + "subagent: could not record the stop reason in the session's report file", + ); + } +} + +/// The goal contract appended to a `start`'s first prompt when a goal was +/// given. Spelled out to the subagent rather than left implicit: it is about +/// to be re-prompted by something it can't see, and the two tools that stop +/// that are the only way it has to say "done" or "stuck". +pub(super) fn goal_briefing(name: &str, goal: &str, max_turns: u32) -> String { + format!( + "\n\nYou are the subagent session `{name}`.\n\nYour goal for this session: {goal}\n\nYou \ + have up to {max_turns} turns to reach it. When a turn of yours ends and you haven't \ + reported the goal reached, the harness starts another turn re-prompting you toward it. \ + Call the `goal_reached` tool once you've genuinely reached it, or `need_help` with what \ + is blocking you if you can't proceed — either one stops the re-prompting. Neither takes \ + a session name: the endpoint you call them on is yours alone, so they always apply to \ + this session and can't be aimed at another one. Running out of turns stops it too, with \ + the work left wherever it had got to." + ) +} + +/// The prompt a continuation turn opens with. It states the one fact the +/// subagent can't observe for itself — that its last turn ended without the +/// goal being reported reached — and says plainly that claiming the goal +/// isn't the same as reaching it, since being re-prompted is precisely the +/// pressure to claim it. +pub(super) fn continuation_prompt(name: &str, goal: &str, turn: u32, max_turns: u32) -> String { + format!( + "Your previous turn ended and you have not reported the goal reached.\n\nYou are the \ + subagent session `{name}`.\n\nGoal: {goal}\n\nThis is turn {turn} of {max_turns}. Carry \ + on toward the goal. If you have in fact reached it, call `goal_reached`; if you are \ + blocked, call `need_help` with what is blocking you. Neither is a substitute for \ + the work: whoever spawned you reads what you actually changed, not what you claim about \ + it." + ) +} + +/// Record the subagent's own "I have reached the goal" signal and stop its +/// turn continuation. Called by the subagent, from inside its own turn, over +/// the signal route this daemon hands it (see `build_config`). +/// +/// **`name` is not a parameter of the tool.** It is whatever the route's +/// token resolved to (`State::session_for_signal_token`), so a subagent +/// records a stop against its own session because that is the only session +/// its URL can reach — not because it addressed the right one. +/// +/// **This verifies nothing**, and the answer it returns says so to the +/// subagent's face. It stops the loop and extends the done message; whether +/// the goal was actually reached is a question about the diff and the gate +/// output, which the parent reads for itself. +/// +/// `report_file` is the subagent saying where it wrote its report, which is +/// the only reason this daemon ever knows that path — see +/// `State::set_report_file`. +pub fn goal_reached( + state: &State, + name: &str, + msg: Option, + report_file: Option<&str>, +) -> String { + signal_stop(state, name, StopReason::GoalReached(msg), report_file); + format!( + "noted — `{name}`'s goal is recorded as reported reached, so this turn finishes and no \ + further goal turn is started. It is recorded as your claim, not as verification: whoever \ + spawned you still reads what you changed." + ) +} + +/// Record that the subagent can't proceed, and stop its turn continuation. +/// The blocking signal the run has otherwise no way to raise: without it a +/// stuck subagent would be re-prompted toward a goal it has already told +/// nobody it can't reach, until the turn cap. +/// +/// `msg` is required, unlike `goal_reached`'s — "I'm stuck" with no reason +/// gives the parent nothing to act on, and acting on it is the entire point. +/// +/// `name` comes from the route's token, exactly as in [`goal_reached`]. +pub fn need_help(state: &State, name: &str, msg: String, report_file: Option<&str>) -> String { + signal_stop(state, name, StopReason::NeedHelp(msg), report_file); + format!( + "noted — `{name}` is recorded as blocked, so this turn finishes and no further goal turn \ + is started. Write down what you have done so far where your brief told you to; whoever \ + spawned you sees the block in `status` and in this run's todo." + ) +} + +/// The half [`goal_reached`] and [`need_help`] share: remember where the +/// subagent says it wrote, and record the stop. +/// +/// It checks nothing, and has nothing left to check. `name` reached it by +/// being resolved from the route's own token, so "is this signal about the +/// session it claims" is answered before the request is dispatched at all — +/// a token that names no live session never reaches this function, it gets a +/// 404. What used to stand here was an `occupancy()` liveness check standing +/// in for identity, which two concurrently-running siblings could each +/// satisfy for the other's name. +fn signal_stop(state: &State, name: &str, stop: StopReason, report_file: Option<&str>) { + state.set_report_file(name, report_file); + state.record_stop(name, stop); +} diff --git a/hive-subagent-mcp/src/session/run.rs b/hive-subagent-mcp/src/session/run.rs new file mode 100644 index 000000000..16ef6678a --- /dev/null +++ b/hive-subagent-mcp/src/session/run.rs @@ -0,0 +1,780 @@ +//! Starting and continuing a run: `start`, `continue_`, the spawns on either +//! runtime and the loop that follows a run's turns. + +use super::*; + +/// Everything a `start` needs, as one struct rather than a parameter list: +/// the call already carried six mostly-optional values before goals were +/// added, and nine positional arguments is both unreadable at the call site +/// and a lint. +pub struct StartRequest { + /// Session name — the tracking key and claude's own session title. + pub name: String, + pub model: Option, + pub effort: Option, + /// File holding the subagent's task instructions. + pub prompt_file: String, + /// Which named role this subagent runs as — a file in this agent's own + /// role directory, named without its extension. `None` is the + /// pre-role shape: the task instructions alone. A name with no file + /// refuses the whole `start` (see [`crate::role`]). + pub role: Option, + /// The first turn's prompt. A goal, when given, is appended to it. + pub trigger: String, + /// Working directory for the session; `None` means the agent's work dir when it + /// exists, else the daemon's cwd. + pub dir: Option, + /// What this session is being continued *toward*. `None` keeps the + /// pre-continuation shape: one turn, one todo, no re-prompting. + pub goal: Option, + /// Turn cap for the continuation, defaulting to `DEFAULT_MAX_TURNS`. + /// Ignored without a `goal`, which is what continuation continues + /// toward — there is nothing to re-prompt against otherwise. + pub max_turns: Option, + /// Where this session's brief told it to write its report, so the stop + /// reason can be appended to that artifact. Never inferred — see + /// `State::set_report_file`. + pub report_file: Option, +} + +/// Start a fresh subagent under `name`. A prior *finished* session under +/// the same name is archived first (so this is a real fresh start, not a +/// silent resume of old history) — a *currently running* one is refused +/// outright, since `hive_claude::InfiniteSession`'s own docs warn that two +/// concurrent runs against the same name corrupt both. +/// +/// With a `goal` set this starts a whole *run*, not a single turn: see +/// `spawn_and_track` for the continuation loop. The return is unchanged +/// either way — it reports the first turn's spawn, not the run's outcome. +/// +/// # Errors +/// +/// A name already running, an invalid name, a `model` the operator hasn't +/// made available (see `check_model`), this agent at its subagent cap (see +/// `subagent_cap`), an archive failure, or the +/// underlying `Claude::spawn` failing (binary missing, etc.) — the last +/// case is the only one that can happen *after* commit-to-run, and it's +/// exactly why nothing is registered in `running` until spawn actually +/// succeeds. +pub async fn start(state: &Arc, req: StartRequest) -> anyhow::Result { + let name = req.name.as_str(); + validate_name(name)?; + let cap = state.swarm_limits(req.model.as_deref()).await?; + // Before `reserve_under`, so a role this agent does not have costs the caller + // an error and nothing else: no name claimed, no session archived, no + // process spawned. + let role = req.role.as_deref().map(crate::role::load).transpose()?; + if let Err(refusal) = state.reserve_under(name, cap) { + return Err(refused( + state, + name, + &refusal, + "use `continue` or `interrupt`", + )); + } + // Only commit the remembered `dir` now that `reserve_under` has actually + // claimed `name` — see `resolve_dir`'s doc for why the order matters, + // and the same reasoning governs the three records below it. + let dir = state.resolve_dir(name, req.dir.as_deref()); + // A fresh start owns none of the previous run's records: its goal, its + // turn budget, why it stopped and where it wrote are all about work this + // call is deliberately replacing. + state.clear_stop(name); + state.clear_report_file(name); + state.set_report_file(name, req.report_file.as_deref()); + let max_turns = req.max_turns.unwrap_or(DEFAULT_MAX_TURNS).max(1); + state.set_goal(name, req.goal.clone(), max_turns); + let trigger = match req.goal.as_deref() { + None => req.trigger, + Some(goal) => format!("{}{}", req.trigger, goal_briefing(name, goal, max_turns)), + }; + let result = start_reserved( + state, + name, + SpawnSpec { + model: req.model, + effort: req.effort, + prompt_file: req.prompt_file, + role, + }, + &trigger, + dir.as_deref(), + ); + if result.is_err() { + state.release_reservation(name); + } + result +} + +/// How one spawn is shaped, as against which session it is for: the four +/// values `start` has already resolved by the time it commits to running. +/// A struct rather than four more parameters — the role made +/// `start_reserved`'s list long enough to be both unreadable and a lint, +/// the same reason [`StartRequest`] exists. +struct SpawnSpec { + model: Option, + effort: Option, + /// The caller's task-instruction file, as given. + prompt_file: String, + /// The named role's *text*, already loaded — `start` reads it before + /// reserving the name, so an unknown role never gets this far. + role: Option, +} + +/// The slow, fallible part of `start`, run only after `reserve_under` has +/// already closed the TOCTOU window — split out so `start` can release the +/// reservation on any error path here without duplicating that logic per +/// failure site. +fn start_reserved( + state: &Arc, + name: &str, + spec: SpawnSpec, + trigger: &str, + dir: Option<&str>, +) -> anyhow::Result { + let signal_url = state.mint_signal_url(name); + let (system_prompt, trigger) = + system_prompt_and_trigger(name, spec.role.as_deref(), &spec.prompt_file, trigger)?; + let system_prompt = system_prompt.map(|p| p.to_string_lossy().into_owned()); + let config = build_config( + name, + spec.model, + spec.effort, + system_prompt.as_deref(), + dir, + Some(&signal_url), + ); + start_on_runtime( + state, + name, + config, + system_prompt.map(PathBuf::from), + trigger, + ) +} + +/// Archive any prior session under `name` and spawn a fresh run on the +/// daemon's runtime. `system_prompt` is the role file `config` already +/// hands claude; ACP has no system prompt, so it goes to the ACP runtime, +/// which puts it in front of the session's first prompt. +pub(super) fn start_on_runtime( + state: &Arc, + name: &str, + config: Config, + system_prompt: Option, + trigger: String, +) -> anyhow::Result { + if let SubagentRuntime::Acp { command, sessions } = &state.runtime { + let cgroup = state.run_cgroup(name); + let runtime = acp_runtime( + state.entered_command(command.clone(), cgroup.as_ref()), + sessions, + name, + ); + if let Some(archived) = runtime + .archive() + .map_err(|e| anyhow::anyhow!("archiving the prior `{name}` session failed: {e}"))? + { + tracing::info!( + name, + archived = %archived.display(), + "start: archived a finished prior session for a fresh start" + ); + } + let config = Config { + system_prompt_file: system_prompt, + ..config + }; + return spawn_and_track_acp(state, name, runtime, cgroup, config, trigger, None); + } + let store = build_store(&config)?; + if store.find_by_title(name).is_some() { + tracing::info!( + name, + "start: archiving a finished prior session for a fresh start" + ); + store + .archive_by_title(name) + .map_err(|e| anyhow::anyhow!("archiving the prior `{name}` session failed: {e}"))?; + } + // No verdict channel: a `start` creates its session, so there is no + // resume to miss and nothing for the caller to wait on past the spawn — + // see `spawn_and_track`'s doc. + spawn_and_track( + state, + name, + &config, + &Attach::Create(name.to_owned()), + trigger, + None, + ) +} + +/// Give an existing named session a new turn — resuming it whether that +/// means "the previous turn finished, here's the next instruction" or "the +/// daemon restarted, reattaching." Refuses a name already running. +/// +/// A name with no session titled it in the project dir of the `dir` in +/// effect is refused before anything spawns, naming the directory searched +/// (`resume_target`): the session is only ever resumed by its id, from that +/// dir. A turn that still misses — the session vanished between the lookup +/// and the spawn — comes back as this call's own `Err` too, because +/// `continue` waits for the driver's answer instead of returning ahead of it +/// (`classify_end`). A `continue` that reports "started" therefore means the +/// turn started. See `await_resume` for the bound, and `spawn_and_track`'s +/// doc for why `start` keeps the older, unconditional contract. +/// +/// Resuming a session whose last turn was *killed* is allowed — that is +/// often exactly what the caller wants — but never silent: the reply says +/// so, since a caller that never ran `status` and missed the todo would +/// otherwise carry on from cut-off work believing it was finished work. +/// +/// A goal session re-enters its continuation loop here with a fresh turn +/// budget — the cap bounds *unattended* re-prompting, not the parent's own. +/// +/// # Errors +/// +/// An invalid name, one already running, a `model` the operator hasn't made +/// available (see `check_model`), this agent at its subagent cap (see +/// `subagent_cap`), no session titled `name` in the project +/// dir searched, `Claude::spawn` failing, or the resumed turn failing within +/// `RESUME_GRACE`. +pub async fn continue_( + state: &Arc, + name: &str, + prompt: String, + model: Option, + effort: Option, + dir: Option<&str>, +) -> anyhow::Result { + validate_name(name)?; + let cap = state.swarm_limits(model.as_deref()).await?; + if let Err(refusal) = state.reserve_under(name, cap) { + return Err(refused( + state, + name, + &refusal, + "use `interrupt` first if you meant to redirect it", + )); + } + // Read before the spawn, which clears the record as soon as the new turn + // is confirmed — this reply is the last chance to mention it. + let killed = state.killed_by(name); + let (tx, rx) = oneshot::channel(); + let verdict: VerdictTx = Arc::new(Mutex::new(Some(tx))); + let started = match continue_reserved(state, name, prompt, model, effort, dir, &verdict) { + Ok(spawned) => spawned, + Err(e) => { + state.release_reservation(name); + return Err(e); + } + }; + // Nothing to release on this path either way: a turn that ended inside + // the grace has already been through `finish_turn`, which clears the + // tracking the spawn put there, and one that a goal carried into another + // turn still owns the name via `between_turns`. + await_resume(rx).await?; + Ok(note_resumed_after_kill(&started, killed)) +} + +/// Hold a `continue` open until its resume is known to have landed — or +/// until [`RESUME_GRACE`] says that waiting any longer costs more than the +/// answer is worth. +/// +/// Returns as soon as *either* side of the race reports, so a successful +/// `continue` pays no fixed delay: its first stream event settles the wait +/// at roughly the same moment a miss's exit would have. The timeout is the +/// floor under a child that does neither, and a turn that reaches it is +/// reported as started — which it is, with the end-of-turn todo left to say +/// how it goes. +/// +/// The third case is the channel closing with nothing ever sent — both the +/// sink and the background task dropping their `Arc` without calling +/// `settle`, which only a panic in the task can produce. That reads here as +/// "started", the same as `Underway`, and the fail-open is deliberate: the +/// one thing already known is that `Claude::spawn` returned a live pid, so +/// answering "the resume missed" would be a claim about the session that +/// nothing observed. The turn's real end still reaches the caller as a todo. +/// +/// # Errors +/// +/// The turn's own failure message, verbatim: the caller asked claude to +/// resume a session and claude said why it couldn't, which is a better +/// answer than anything this daemon could paraphrase it into. +pub(super) async fn await_resume(rx: oneshot::Receiver) -> anyhow::Result<()> { + match tokio::time::timeout(RESUME_GRACE, rx).await { + Ok(Ok(ResumeVerdict::Ended(TurnEnd::Failed(e)))) => anyhow::bail!("{e}"), + // Everything else is a turn that started: it spoke (`Underway`), or + // it ended on its own terms within the grace — `Complete`, or a + // `Killed` that some concurrent `interrupt` asked for and whose todo + // says so — or it is still going when the grace runs out, or nobody + // ever sent at all, which only a panicked task produces and which + // this deliberately fails open on. See the doc above. + _ => Ok(()), + } +} + +/// Append the "you are resuming a killed session" note to `continue`'s reply +/// when its previous turn was signalled; pass the reply through unchanged +/// otherwise. +pub(super) fn note_resumed_after_kill(msg: &str, killed: Option) -> String { + match killed { + None => msg.to_owned(), + Some(signal) => format!( + "{msg} — note: its previous turn was killed ({}) rather than finishing, so this turn \ + resumes from work that was cut off mid-way", + describe_signal(signal) + ), + } +} + +/// The slow, fallible part of `continue_`, run only after `reserve_under` has +/// already closed the TOCTOU window — same split rationale as +/// `start_reserved`. `dir` is the caller's own, not yet resolved against the +/// remembered one. +fn continue_reserved( + state: &Arc, + name: &str, + prompt: String, + model: Option, + effort: Option, + dir: Option<&str>, + verdict: &VerdictTx, +) -> anyhow::Result { + // A fresh URL for the resumed run, not the one the last run was handed: + // a token is per run, and this is a new one. + let signal_url = state.mint_signal_url(name); + let resolved = state.peek_dir(name, dir); + let config = build_config( + name, + model, + effort, + None, + resolved.as_deref(), + Some(&signal_url), + ); + continue_on_runtime(state, name, config, dir, prompt, verdict) +} + +/// Resume `name`'s session on the daemon's runtime for one more run. +/// +/// The session is looked up before any of `name`'s records change, so a +/// refused call leaves `status` and the remembered `dir` as they were; only +/// a session that is there gets `State::begin_continue`. +/// +/// # Errors +/// +/// On claude, a name with no session in `config`'s project dir (see +/// `resume_target`). On ACP, a name with no recorded session: the ACP +/// runtime would start a new one rather than fail, so the check has to +/// happen here. +pub(super) fn continue_on_runtime( + state: &Arc, + name: &str, + config: Config, + dir: Option<&str>, + prompt: String, + verdict: &VerdictTx, +) -> anyhow::Result { + if let SubagentRuntime::Acp { command, sessions } = &state.runtime { + let session = acp_session_file(sessions, name); + if !session.exists() { + anyhow::bail!( + "no ACP session is recorded for subagent `{name}` (looked for {}) — `start` \ + creates one", + session.display() + ); + } + state.begin_continue(name, dir); + let cgroup = state.run_cgroup(name); + let runtime = acp_runtime( + state.entered_command(command.clone(), cgroup.as_ref()), + sessions, + name, + ); + return spawn_and_track_acp( + state, + name, + runtime, + cgroup, + config, + prompt, + Some(Arc::clone(verdict)), + ); + } + // The lookup in `resume_target` refuses before anything spawns. `verdict` + // still carries claude's own answer back in time to be the call's error, + // for a session that vanishes between the lookup and the spawn. See this + // module's doc. + let id = resume_target(&config, name)?; + state.begin_continue(name, dir); + spawn_and_track( + state, + name, + &config, + &Attach::Resume(id), + prompt, + Some(Arc::clone(verdict)), + ) +} + +/// Bumps `name`'s liveness clock on every line of the turn's output, and +/// offers the line to the swarm terminal publisher when this agent has one +/// ([`crate::swarm_term`]). +/// +/// **All three callbacks, deliberately.** A stderr line or a stdout line +/// that didn't parse as JSON is proof the child is alive every bit as much +/// as a stream-json event is, and the failure that matters here is reporting +/// a live subagent as wedged — so anything the child says counts. Liveness +/// never reads what it said: classifying *what* the subagent is doing is the +/// publisher's job and a separate question from whether it's doing anything. +/// +/// Sink methods are called synchronously from the driver's stream readers as +/// lines arrive, so the body has to stay cheap — one uncontended map write +/// is, and forwarding to a channel to do the same write elsewhere would cost +/// more than it saved. `settle` adds a second uncontended lock on a +/// `resume`d turn only, and finds an already-emptied slot after the first +/// event — strictly less work than the map write next to it. The publisher's +/// `offer` copies the line into a bounded channel and never waits. +/// +/// **Liveness counts every callback; "the turn is underway" does not.** A +/// resume that matched nothing is not silent: claude writes the reason to +/// stderr *and* emits a terminal stream-json `result` event before exiting, +/// so treating any callback at all as proof the turn began would report +/// every missed resume as a successful start. The narrowest fact that +/// separates the two is the event's own kind — a `result` is stream-json's +/// end-of-turn marker, so an event that isn't one is a turn still in +/// progress. That's the envelope, not the content. +pub(super) struct LivenessSink { + pub(super) state: Arc, + pub(super) name: String, + /// The model and effort this run was started with, stamped on every row + /// it publishes. + pub(super) info: Arc, + /// Where to report the first non-terminal event, on a `resume` whose + /// caller is still waiting to hear whether it landed. `None` on a + /// `start`, which has nobody waiting. + pub(super) verdict: Option, +} + +impl hive_claude::Sink for LivenessSink { + fn on_event(&self, event: &serde_json::Value) { + self.state.note_event(&self.name); + if event.get("type").and_then(serde_json::Value::as_str) != Some("result") { + settle(self.verdict.as_ref(), ResumeVerdict::Underway); + } + self.publish(|| Output::Event(event.clone())); + } + + fn on_stdout_line(&self, line: &str) { + self.state.note_event(&self.name); + self.publish(|| Output::Stdout(line.to_owned())); + } + + fn on_stderr_line(&self, line: &str) { + self.state.note_event(&self.name); + self.publish(|| Output::Stderr(line.to_owned())); + } +} + +impl LivenessSink { + /// Offer a line to the publisher, building the copy only when there is + /// one to take it. + fn publish(&self, line: impl FnOnce() -> Output) { + if let Some(term) = &self.state.term { + term.offer(&self.name, &self.info, line()); + } + } +} + +/// The exit status a run's end reports to the swarm: `0` when it completed, +/// nothing when a signal killed it, and `1` for any other failure. A failed +/// turn's own exit code is not kept on [`TurnEnd`] (it carries the message +/// shown to the caller), and an ACP failure has no process status at all, so +/// the swarm sees "failed" and the end todo has the detail. +pub(super) fn exit_status(end: &TurnEnd) -> Option { + match end { + TurnEnd::Complete => Some(0), + TurnEnd::Killed { .. } => None, + TurnEnd::Failed(_) => Some(1), + } +} + +/// What a run's rows say about how it was started: its `config`'s model and +/// effort, which the swarm shows beside the subagent's name. +fn run_info(config: &Config) -> Arc { + Arc::new(crate::swarm_term::RunInfo { + model: config.model.clone(), + effort: config.effort.clone(), + }) +} + +/// Spawn the child (synchronous — `Claude::spawn` returns with a real pid +/// the instant the process exists), track it in `running`, and hand the +/// actual turn off to a background task so nobody blocks on the whole turn. +/// +/// **A pid is "confirmed running" for a `start`, and only for a `start`.** +/// A `start` creates its session, so the only thing that can go wrong at +/// attach time is the spawn itself, which has already either succeeded or +/// returned here as an error — there is no stronger signal to wait for, and +/// waiting would slow every call down for no reason. A `resume` breaks that +/// reasoning: the session it names may not be there, and claude only says so +/// a fraction of a second *after* the process exists, so for a `continue` a +/// pid is not proof the turn began. That's what `verdict` is for — `Some` +/// only on the resume path, carrying the first real answer back to a caller +/// that is waiting for it (`await_resume`); `None` on a `start`, which keeps +/// the immediate-return contract unchanged. +/// +/// **The turn *continuation* loop lives in that background task, and only +/// there.** A session `start`ed with a goal runs turn after turn until +/// something stops it, and every one of those turns is a fresh +/// `Claude::spawn` against `Attach::Resume` — the driver's `wait` consumes +/// its child, so there is no other shape it could take. Keeping the loop +/// behind the same `tokio::spawn` is what leaves both tool-call contracts +/// untouched: `start` still returns at the first spawn, `continue` still +/// returns when its own turn is underway, and neither waits on turns two +/// through five. +/// +/// Not `async` itself — `tokio::spawn` needs an active runtime to spawn +/// *onto*, not an `async` caller to spawn *from*. +pub(super) fn spawn_and_track( + state: &Arc, + name: &str, + config: &Config, + attach: &Attach, + prompt: String, + verdict: Option, +) -> anyhow::Result { + // Every turn of the run, and all they start, share one cgroup, released + // when the background task below ends. + let cgroup = state.run_cgroup(name); + let config = &state.entered_config(config, cgroup.as_ref()); + let running = Claude::spawn(config, attach) + .map_err(|e| anyhow::anyhow!("starting the subagent process failed: {e}"))?; + state.track(name, running.cancel_handle().into()); + // This turn supersedes whatever the previous one did, including having + // been killed — the record is about the turn before this one. + state.clear_kill(name); + // Start the liveness clock at the spawn, so the age is already an answer + // before the child's first line — see `note_event`. + state.note_event(name); + + // Resolved here, on the calling thread, while the config is still to + // hand: only a resume can miss, and only `classify_end` finding a + // `SessionNotFound` ever uses it. Every continuation turn is a resume, + // so this is worth having even when the *first* attach is a `Create`. + let resume_searched = searched_location(config); + let mut searched = if matches!(attach, Attach::Resume(_)) { + resume_searched.clone() + } else { + None + }; + + let info = run_info(config); + state.announce_running(name, &info); + let config = config.clone(); + let state = Arc::clone(state); + let task_name = name.to_owned(); + tokio::spawn(async move { + let _cgroup = cgroup; + let mut running = running; + let mut prompt = prompt; + loop { + let sink = LivenessSink { + state: Arc::clone(&state), + name: task_name.clone(), + info: Arc::clone(&info), + verdict: verdict.clone(), + }; + let end = classify_end(running.wait(&prompt, &sink).await, searched.as_deref()); + let Some(next) = after_turn(&state, &task_name, end, verdict.as_ref()).await else { + return; + }; + match resume_target(&config, &task_name) + .and_then(|id| Ok(Claude::spawn(&config, &Attach::Resume(id))?)) + { + Ok(next_running) => { + state.track(&task_name, next_running.cancel_handle().into()); + state.note_event(&task_name); + running = next_running; + prompt = next; + searched = resume_searched.clone(); + } + Err(e) => { + let end = TurnEnd::Failed(format!( + "claude error: starting the next goal turn failed: {e}" + )); + log_turn_end(&task_name, &end); + state.finish_turn(&task_name, &end); + push_turn_end_todo(&state.socket, &task_name, &end, None).await; + return; + } + } + } + }); + + Ok(format!("subagent `{name}` started")) +} + +/// Everything a run does once one of its turns has ended, on either +/// runtime: report it, and either stop the run or claim the name for the +/// next goal turn. Returns that turn's prompt, or `None` once the run is +/// over. +async fn after_turn( + state: &State, + name: &str, + end: TurnEnd, + verdict: Option<&VerdictTx>, +) -> Option { + log_turn_end(name, &end); + // The todo is how a turn's end reaches an agent that is no + // longer looking — so it is pushed for every end *except* the + // one the caller is being handed as a tool-call error right now. + // `settle` saying the verdict was delivered is what makes that + // certain: a `continue` whose grace had already run out gets + // `false` here and its todo, same as before. Only the first turn + // can ever win this — the sender is consumed — which is right, + // since only the first turn is one a caller is still waiting on. + let reported = settle(verdict, ResumeVerdict::Ended(end.clone())); + + if !matches!(end, TurnEnd::Complete) { + // A killed or failed turn ends the run, goal or not: there is + // nothing to re-prompt a child that isn't there any more, and + // these two ends already have records of their own. + state.finish_turn(name, &end); + if !(matches!(end, TurnEnd::Failed(_)) && reported) { + push_turn_end_todo(&state.socket, name, &end, None).await; + } + return None; + } + + match state.plan_after_turn(name) { + Continuation::Stop(stop) => { + state.record_stop(name, stop.clone()); + state.finish_turn(name, &end); + write_stop_to_report(state.report_file(name), name, &stop).await; + push_turn_end_todo(&state.socket, name, &end, Some(&stop)).await; + None + } + Continuation::Continue { prompt } => { + // The name stays claimed across the gap — see + // `between_turns` for what a concurrent `start` would + // otherwise be able to do with it. + state.between_turns(name); + Some(prompt) + } + } +} + +/// [`spawn_and_track`] on ACP: every turn of the run goes through +/// `runtime`, whose agent process is spawned by the first turn and killed +/// when the run ends and the runtime is dropped. Returns before the agent +/// exists, so a spawn failure is the first turn's `Failed` end rather than +/// this call's error. The run's `cgroup` is released after the runtime. +fn spawn_and_track_acp( + state: &Arc, + name: &str, + runtime: AcpRuntime, + cgroup: Option, + config: Config, + prompt: String, + verdict: Option, +) -> anyhow::Result { + let canceller = runtime + .canceller() + .ok_or_else(|| anyhow::anyhow!("the ACP runtime offers no cancel handle"))?; + state.track(name, canceller.clone().into()); + state.clear_kill(name); + state.note_event(name); + + let info = run_info(&config); + state.announce_running(name, &info); + let state = Arc::clone(state); + let task_name = name.to_owned(); + tokio::spawn(async move { + let mut prompt = prompt; + loop { + let sink = LivenessSink { + state: Arc::clone(&state), + name: task_name.clone(), + info: Arc::clone(&info), + verdict: verdict.clone(), + }; + let end = match runtime.run(&config, &prompt, &sink).await { + Ok(_) => TurnEnd::Complete, + Err(e) => TurnEnd::Failed(format!("ACP error: {e}")), + }; + let Some(next) = after_turn(&state, &task_name, end, verdict.as_ref()).await else { + break; + }; + state.track(&task_name, canceller.clone().into()); + state.note_event(&task_name); + prompt = next; + } + drop(runtime); + drop(cgroup); + }); + + Ok(format!("subagent `{name}` started")) +} + +/// The file `name`'s ACP session id is kept in, under `sessions`. Named +/// like the per-session MCP config and system-prompt files beside it. +pub(super) fn acp_session_file(sessions: &Path, name: &str) -> PathBuf { + sessions.join(format!("subagent-acp-session-{name}")) +} + +/// The ACP runtime `name`'s run drives, keeping its session id in +/// [`acp_session_file`] and answering permission requests per +/// [`acp_permits`]. +fn acp_runtime( + command: AcpCommand, + sessions: &Path, + name: &str, +) -> AcpRuntime { + let perms = crate::swarm_models::permissions_now(); + let permit: PermissionPolicy = + Arc::new(move |ask: &PermissionAsk<'_>| acp_permits(ask, &perms)); + AcpRuntime::new( + command, + acp_session_file(sessions, name), + permit, + hive_claude::NeverCompact, + ) +} + +/// Whether an ACP subagent may run the tool call it asks about. +/// Default-deny, allowing what a claude subagent gets from `build_config`: +/// +/// - `other`-kind calls to tools of the MCP servers the session was handed; +/// - the file tools: `read`, `edit`, `search`; +/// - `fetch` with the `web_tools` permission; +/// - `execute` with the `execution` permission, as a claude subagent gets `Bash` +/// ([`hive_sh4re::permissions::subagent_builtin_tools_for`]). +pub(super) fn acp_permits(ask: &PermissionAsk<'_>, perms: &[Permission]) -> bool { + match ask.kind { + "other" => ask.mcp_server.is_some(), + "read" | "edit" | "search" => true, + "fetch" => perms.contains(&Permission::WebTools), + "execute" => perms.contains(&Permission::Execution), + _ => false, + } +} + +/// Log a turn's end at the level its severity deserves: a completion is +/// unremarkable, the other two are not. +fn log_turn_end(name: &str, end: &TurnEnd) { + match end { + TurnEnd::Complete => {} + TurnEnd::Killed { signal } => { + tracing::warn!( + name = %name, + signal, + "subagent: turn killed — the child died on a signal, it did not finish" + ); + } + TurnEnd::Failed(e) => { + tracing::warn!(name = %name, error = %e, "subagent: turn failed"); + } + } +} diff --git a/hive-subagent-mcp/src/session/state.rs b/hive-subagent-mcp/src/session/state.rs new file mode 100644 index 000000000..42591a9bd --- /dev/null +++ b/hive-subagent-mcp/src/session/state.rs @@ -0,0 +1,716 @@ +//! The daemon's per-name bookkeeping: who is running, under which claim, with +//! which goal, stop reason and signal token. + +use super::{ + AcpCommand, Arc, AtomicU64, Config, Continuation, Duration, HashMap, Instant, Mutex, Occupancy, + Ordering, Path, PathBuf, PoisonError, RUN_OOM_SCORE_ADJ, Refusal, RunCgroup, RunCgroups, + RuntimeSpec, Slot, StopReason, SubagentRuntime, TurnEnd, TurnStop, available_models, + check_model, continuation_prompt, exit_status, model_list, run_cgroup, subagent_cap, +}; + +/// This daemon's whole state: which names have a live process or a +/// reservation in flight, what each is working toward and how it stopped, +/// and where to push the completion todo. `Arc`-wrapped so the background +/// task driving a run outlives the tool call that started it. +/// +/// The map value is a `Slot`: `Starting` means `name` is reserved for an +/// in-flight `start`/`continue` that hasn't reached a confirmed spawn yet; +/// `Running` means a real turn is tracked and interruptible; `Stopping` +/// means it was interrupted and its process is still winding down. Each +/// claims the name. `Starting` closes a TOCTOU window: checking "is `name` +/// free" and committing to it are two different lock acquisitions unless +/// the check *is* the reservation — see `reserve_under`. +/// +/// `killed` is the other half of that map's story: `running` says what is in +/// flight *now*, `killed` remembers the names whose last turn ended on a +/// signal rather than on its own, keyed to the signal number. Without it a +/// killed session is indistinguishable from a finished one the moment its +/// entry leaves `running` — the whole point of this record. +/// +/// `last_event` splits `running` a second way — *in flight* against +/// *making progress*, since a wedged child is tracked exactly like a busy +/// one (`note_event` / `last_event_age`). +/// +/// ⚠️ This concurrency guard is keyed by `name` alone — a `start`/`continue` +/// for `name` with a *different* `dir` than one already in flight under +/// that name is refused as "already running," even though the two would +/// resolve to entirely separate on-disk sessions. Deliberate: `name` is the +/// caller's one chosen identity for a subagent, not `(name, dir)` — reuse a +/// name across directories at your own risk, the tool doesn't disambiguate +/// it (flagged in review when `dir` was added). +pub struct State { + pub(super) running: Mutex>, + dirs: Mutex>, + killed: Mutex>, + last_event: Mutex>, + /// Turn continuation's three records. Unlike the four maps above they + /// deliberately **outlive the turn** — a stop reason that vanished with + /// the process it described would be unreadable by the time anyone + /// asked — so they're cleared by the next `start` under the same name, + /// not by a turn ending. + goals: Mutex>, + pub(super) stops: Mutex>, + reports: Mutex>, + pub(super) socket: PathBuf, + /// The prefix of every subagent's signal URL — this daemon's own `--http` + /// address with [`crate::mcp::SIGNAL_PATH`] on the end, and *not* a + /// reachable route by itself. It lives here because the daemon can only + /// learn it from its own `--http` argument — deriving it from a + /// convention would be the same inference the report path is careful not + /// to make. + signal_base: String, + signal_tokens: Mutex, + /// What a subagent's turns run on: claude unless [`State::on_runtime`] + /// says otherwise. + pub(super) runtime: SubagentRuntime, + /// Where every subagent's output lines go up to the swarm, when this + /// agent can publish there ([`State::publishing_to`]). + pub(super) term: Option, + /// Where the swarm's `subagent_models` and `max_subagents` for this agent + /// are read from, when this agent can read them + /// ([`State::reading_models_from`]). + models: Option, + /// The agent's own model list, checked when the swarm sets none: + /// [`available_models`] outside tests. + pub(super) local_models: fn() -> Option, + /// Whether runs start through this binary's entry wrapper + /// ([`State::entering_runs`]). + runs_entered: bool, + /// Where each run gets its own cgroup, when this daemon was delegated + /// one. + run_cgroups: Option, + /// The `` of the next run cgroup `-`. + run_seq: AtomicU64, +} + +/// Which opaque URL segment belongs to which session — the whole of a +/// subagent's identity, as far as `goal_reached`/`need_help` are concerned. +/// +/// A subagent is told one URL, in its own `--mcp-config`, and that URL is +/// what says who it is: it has no field to name a session in and no second +/// session's URL to reach for. Both directions live under one lock because a +/// half-updated pair is exactly the state in which a token could resolve to +/// a session that has since minted another one. +#[derive(Default)] +struct SignalTokens { + /// The token currently minted for a session, so a re-mint can retire it. + by_name: HashMap, + /// The resolution the route does: token -> the session it speaks for. + by_token: HashMap, +} + +/// What a session is being continued toward, and how far through its turn +/// budget it is. Present only for a session `start`ed with a `goal`; its +/// absence is what makes a session single-turn. +struct GoalState { + /// Verbatim from `start` — re-prompted at the subagent each turn rather + /// than paraphrased, since the caller wrote it for the subagent to read. + goal: String, + /// The cap this session runs under (`start`'s `max_turns`). + max_turns: u32, + /// Turns started so far, counting the first — so the very first turn is + /// `1 of max_turns`, not `0`. + turn: u32, +} + +impl State { + /// `signal_base` is where the streamable-http endpoint a subagent's own + /// claude reaches `goal_reached`/`need_help` on *starts* — this daemon's + /// `--http` address with the signal route appended (see + /// `crate::mcp::serve_http`). Each session's actual URL is that plus its + /// own token; see `State::mint_signal_url`. + #[must_use] + pub fn new(socket: PathBuf, signal_base: String) -> Self { + Self { + running: Mutex::new(HashMap::new()), + dirs: Mutex::new(HashMap::new()), + killed: Mutex::new(HashMap::new()), + last_event: Mutex::new(HashMap::new()), + goals: Mutex::new(HashMap::new()), + stops: Mutex::new(HashMap::new()), + reports: Mutex::new(HashMap::new()), + socket, + signal_base, + signal_tokens: Mutex::new(SignalTokens::default()), + runtime: SubagentRuntime::Claude, + term: None, + models: None, + local_models: available_models, + runs_entered: false, + run_cgroups: None, + run_seq: AtomicU64::new(0), + } + } + + /// Hand every subagent's output lines to `term` as they arrive. + #[must_use] + pub fn publishing_to(mut self, term: Option) -> Self { + self.term = term; + self + } + + /// Check every named `model` against the swarm's `subagent_models`, and + /// every new run against its `max_subagents`, as `models` reads them, + /// where the swarm sets them. + #[must_use] + pub fn reading_models_from(mut self, models: Option) -> Self { + self.models = models; + self + } + + /// Start every subagent run through this binary's entry wrapper, whose + /// `main` calls `run_cgroup::exec_entry` first: at `oom_score_adj` +900 + /// always, and in its own cgroup under `cgroups` when there are any. + #[must_use] + pub fn entering_runs(mut self, cgroups: Option) -> Self { + self.runs_entered = true; + self.run_cgroups = cgroups; + self + } + + /// A new cgroup for one run of `name`; `None` without run cgroups, or + /// (logged) when creating it failed, and the run then stays in the + /// daemon's cgroup. Whatever a run left running in it (a tool child that + /// left claude's process group, which `interrupt`'s SIGINT never + /// reaches) is killed once the run has ended. + pub(super) fn run_cgroup(&self, name: &str) -> Option { + let cgroups = self.run_cgroups.as_ref()?; + let n = self.run_seq.fetch_add(1, Ordering::Relaxed); + cgroups + .create(&format!("{name}-{n}")) + .inspect_err(|e| tracing::warn!(name, error = %e, "subagent: run cgroup unavailable")) + .ok() + .map(RunCgroup::killing_leftovers) + } + + /// `config` with its program started through the entry wrapper, at + /// [`RUN_OOM_SCORE_ADJ`] and inside `cgroup` if there is one; unchanged + /// without [`State::entering_runs`]. `hive-claude` builds the `Command` + /// itself and offers no `pre_exec`, hence the wrapper. + pub(super) fn entered_config(&self, config: &Config, cgroup: Option<&RunCgroup>) -> Config { + let mut config = config.clone(); + if self.runs_entered { + // `hive-claude`'s own default program. + let program = config.program.take().unwrap_or_else(|| "claude".into()); + let (entry, env) = run_cgroup::entry(&program, RUN_OOM_SCORE_ADJ, cgroup); + config.program = Some(entry); + config.env.extend(env); + } + config + } + + /// [`State::entered_config`] for an ACP agent's command. + pub(super) fn entered_command( + &self, + mut command: AcpCommand, + cgroup: Option<&RunCgroup>, + ) -> AcpCommand { + if self.runs_entered { + let (entry, env) = + run_cgroup::entry(Path::new(&command.command), RUN_OOM_SCORE_ADJ, cgroup); + command.command = entry.to_string_lossy().into_owned(); + command.env.extend(env); + } + command + } + + /// Read the swarm's keys once: refresh this agent's permissions (the + /// tools the subagent about to run gets), refuse a `model` outside the list + /// in effect for this agent (see `check_model`), and return the subagent + /// cap in effect (see `subagent_cap`). + pub(super) async fn swarm_limits(&self, model: Option<&str>) -> anyhow::Result> { + let read = match &self.models { + Some(reader) => { + reader.refresh_permissions().await; + Some(reader.read().await) + } + None => None, + }; + let agent = self + .models + .as_ref() + .map_or("", crate::swarm_models::Reader::agent); + let cap = subagent_cap(read.as_ref(), agent); + if model.is_some() { + check_model(model, &model_list(read, (self.local_models)()))?; + } + Ok(cap) + } + + /// Run every subagent on `runtime` — the daemon passes the parent + /// agent's, read from its environment at startup. On ACP this resolves + /// the harness dir, which only exists inside a container. + #[must_use] + pub fn on_runtime(mut self, runtime: RuntimeSpec) -> Self { + self.runtime = match runtime { + RuntimeSpec::Claude => SubagentRuntime::Claude, + RuntimeSpec::Acp(command) => SubagentRuntime::Acp { + command, + sessions: crate::paths::harness_dir(), + }, + }; + self + } + + /// Mint `name` a fresh signal URL: an unguessable token appended to + /// [`State::signal_base`], resolvable back to this one session and to no + /// other. Called once per spawned run, and the result goes into exactly + /// one place — that subagent's own `--mcp-config` (`crate::mcp_config`). + /// + /// A v4 UUID's 122 bits come from the OS CSPRNG, so the segment is not + /// derived from the name, the port or anything else a sibling subagent + /// could compute; a subagent that wants to signal as somebody else has + /// nothing to guess *from*. Minting replaces any token the name held + /// before, which is what stops a name's old URL surviving the run it was + /// issued for. + pub(crate) fn mint_signal_url(&self, name: &str) -> String { + let token = uuid::Uuid::new_v4().simple().to_string(); + let mut tokens = self + .signal_tokens + .lock() + .unwrap_or_else(PoisonError::into_inner); + if let Some(previous) = tokens.by_name.insert(name.to_owned(), token.clone()) { + tokens.by_token.remove(&previous); + } + tokens.by_token.insert(token.clone(), name.to_owned()); + drop(tokens); + format!("{}/{token}", self.signal_base) + } + + /// Which session an incoming signal request speaks for, or `None` for a + /// token this daemon never minted or has since revoked — which the route + /// answers with a bare 404 (see `crate::mcp::serve_http`). `None` is the + /// only failure shape there is: nothing about the answer distinguishes + /// "never existed" from "that run is over", so a caller holding a wrong + /// token learns nothing from being refused. + pub(crate) fn session_for_signal_token(&self, token: &str) -> Option { + self.signal_tokens + .lock() + .unwrap_or_else(PoisonError::into_inner) + .by_token + .get(token) + .cloned() + } + + /// Retire `name`'s signal URL — its run is over (or never started), so + /// the route it was handed stops resolving and answers 404 from here on. + /// This is the expiry half of "unknown or expired token ⇒ 404": without + /// it a finished subagent's config file would still name a live route. + fn revoke_signal_token(&self, name: &str) { + let mut tokens = self + .signal_tokens + .lock() + .unwrap_or_else(PoisonError::into_inner); + if let Some(token) = tokens.by_name.remove(name) { + tokens.by_token.remove(&token); + } + } + + /// Which [`Slot`] `name` is in; `None` with nothing tracked under it. + pub(super) fn occupancy(&self, name: &str) -> Option { + self.running + .lock() + .unwrap_or_else(PoisonError::into_inner) + .get(name) + .map(|slot| match slot { + Slot::Starting => Occupancy::Starting, + Slot::Running(_) => Occupancy::Running, + Slot::Stopping => Occupancy::Stopping, + }) + } + + /// Atomically claim `name` for an in-flight start/continue: check + /// "is anything tracked under this name" and "commit to this call + /// owning it" in the *same* lock acquisition, so two calls racing the + /// same name can't both pass a check before either commits (the exact + /// same-name concurrent-run hazard this module's doc warns about). + /// Refuses (reserving nothing) a `name` already tracked, or any name + /// once `cap` names are tracked. The count is checked under the same + /// lock, so two racing calls can't both take the last place. + /// + /// Every tracked name counts toward `cap`, a goal run between turns + /// and an interrupted one still winding down included: each holds a + /// process or is about to. A goal's next turn never comes through here, + /// so a run already counted is never refused its re-prompt. + pub(super) fn reserve_under(&self, name: &str, cap: Option) -> Result<(), Refusal> { + let mut running = self.running.lock().unwrap_or_else(PoisonError::into_inner); + if running.contains_key(name) { + return Err(Refusal::Taken); + } + if let Some(cap) = cap + && running.len() >= usize::try_from(cap).unwrap_or(usize::MAX) + { + return Err(Refusal::AtCap { + running: running.len(), + cap, + }); + } + running.insert(name.to_owned(), Slot::Starting); + tracing::info!(name, "subagent name reserved"); + Ok(()) + } + + /// [`State::reserve_under`] with no cap: `false` if `name` is taken. + #[cfg(test)] + pub(super) fn reserve(&self, name: &str) -> bool { + self.reserve_under(name, None).is_ok() + } + + /// Release a reservation that never made it to a real spawn (an error + /// on the slow path between `reserve_under` and `Claude::spawn` succeeding). + /// A no-op if the entry was already upgraded to `Running` — this only + /// ever clears a still-`Starting` placeholder, never a live process. + /// + /// The signal token the failed call minted goes with it: no process ever + /// read that URL, and a token outliving the call that minted it is the + /// one way a route could resolve to a session that isn't there. + pub(super) fn release_reservation(&self, name: &str) { + let mut running = self.running.lock().unwrap_or_else(PoisonError::into_inner); + let released = matches!(running.get(name), Some(Slot::Starting)); + if released { + running.remove(name); + tracing::info!(name, "subagent reservation released: the spawn failed"); + } + drop(running); + // Only alongside a reservation this actually released: a call that + // found a live process left it running, and revoking that run's URL + // would cut off a subagent which is still using it. + if released { + self.revoke_signal_token(name); + } + } + + /// Retire the finished turn's tracking for `name` and remember how it + /// ended: a `Killed` end is recorded so `status`, the end-of-turn todo + /// and a later `continue` can all say so; any other end clears a stale + /// record from an earlier turn. + /// + /// The kill is recorded *before* the `running` entry goes away, so there + /// is no instant in which `name` is neither running nor known-killed — + /// a `status` landing between the two would otherwise read the session + /// as plainly idle, which is the exact confusion this record exists to + /// remove. + /// + /// The liveness clock goes with the `running` entry, for the same reason + /// it's kept at all: it answers "is this turn still making progress", + /// and a turn that has ended has no progress left to make. + /// + /// So does the session's signal token. Every caller of this is a point + /// where the *run* stops — a continued run's own turn boundary goes + /// through `between_turns` instead, and keeps its URL because the next + /// turn is the same subagent against the same rendered config. Revoking + /// here is what makes a signal for a session that already ended a 404 + /// rather than a late stop reason recorded against it. + pub(super) fn finish_turn(&self, name: &str, end: &TurnEnd) { + if let Some(term) = &self.term { + term.finished(name, exit_status(end)); + } + self.revoke_signal_token(name); + let mut killed = self.killed.lock().unwrap_or_else(PoisonError::into_inner); + match end { + TurnEnd::Killed { signal } => killed.insert(name.to_owned(), *signal), + TurnEnd::Complete | TurnEnd::Failed(_) => killed.remove(name), + }; + drop(killed); + self.running + .lock() + .unwrap_or_else(PoisonError::into_inner) + .remove(name); + self.last_event + .lock() + .unwrap_or_else(PoisonError::into_inner) + .remove(name); + tracing::info!(name, "subagent name freed: the run ended"); + } + + /// Tell the swarm `name`'s run began, with the model and effort `info` + /// names. The end is reported by `finish_turn`, which every run's end goes + /// through; the gaps between a goal run's turns are not an end. + pub(super) fn announce_running(&self, name: &str, info: &Arc) { + if let Some(term) = &self.term { + term.running(name, info); + } + } + + /// The signal `name`'s last turn died on, if it died on one. + pub(super) fn killed_by(&self, name: &str) -> Option { + self.killed + .lock() + .unwrap_or_else(PoisonError::into_inner) + .get(name) + .copied() + } + + /// Forget that `name`'s last turn was killed — called once a new turn is + /// confirmed spawned, since the record describes the turn before it and + /// would otherwise keep flagging a session that has since run again. + pub(super) fn clear_kill(&self, name: &str) { + self.killed + .lock() + .unwrap_or_else(PoisonError::into_inner) + .remove(name); + } + + /// `name`'s turn just produced output — record *when*, and nothing else. + /// Called from `LivenessSink` for every line of every stream, so it runs + /// far more often than anything else in this type and stays a single + /// map write for that reason. + /// + /// A monotonic [`Instant`], not a wall clock: what's ever read back out + /// is an elapsed age, which a clock adjustment must not be able to + /// distort into a stall that never happened. + /// + /// Also called by `spawn_and_track` the moment each turn's child exists, + /// so the clock starts at the spawn rather than at the first line. + /// Without that seed a subagent that wedged before emitting anything at + /// all would report no age forever — the one case where an age is most + /// worth having. The value therefore reads as "how long since the daemon + /// last heard anything from this child", counting the spawn itself as + /// the first thing it heard. A continued run re-seeds it per turn, for + /// the same reason: the age describes the turn in flight, not the run. + pub(super) fn note_event(&self, name: &str) { + self.last_event + .lock() + .unwrap_or_else(PoisonError::into_inner) + .insert(name.to_owned(), Instant::now()); + } + + /// How long since `name`'s turn last produced output. `None` once the + /// turn is over (`finish_turn` drops the entry) or for a name that never + /// reached a spawn — in both cases there's no *running* turn whose + /// progress the age would describe, and a leftover age from a turn that + /// has already ended would read as a stall that isn't one. + pub(super) fn last_event_age(&self, name: &str) -> Option { + self.last_event + .lock() + .unwrap_or_else(PoisonError::into_inner) + .get(name) + .map(Instant::elapsed) + } + + /// An explicit `dir` is remembered against `name` and returned as-is; an + /// omitted one (`None`) falls back to whatever was last remembered for + /// `name`, so a `start` that gave a `dir` doesn't force every later + /// `continue`/`status` against the same name to repeat it. Explicit + /// always wins and updates the memory — there's no way to say "forget + /// it, use the default" once something's been remembered short of + /// giving a genuinely different `dir`, a deliberate simplicity trade, + /// not an oversight. In-memory only, same durability envelope as + /// `running`: a daemon restart forgets it same as it forgets everything + /// else here — the caller re-supplies `dir` once, same as it always + /// could. + /// + /// ⚠️ **Callers must only call this once the call is known to proceed** + /// — after `reserve_under` in `start`, after the session lookup in a + /// `continue` (`begin_continue`) — so a refused call never changes what + /// a later bare `continue` resolves to. `peek_dir` is the non-committing + /// variant for a call that might still be refused, or that shouldn't + /// persist its `dir` at all, like `status`. + pub(super) fn resolve_dir(&self, name: &str, dir: Option<&str>) -> Option { + let mut dirs = self.dirs.lock().unwrap_or_else(PoisonError::into_inner); + match dir { + Some(d) => { + dirs.insert(name.to_owned(), d.to_owned()); + Some(d.to_owned()) + } + None => dirs.get(name).cloned(), + } + } + + /// Same resolution as `resolve_dir` (explicit wins, omitted falls back + /// to the remembered value) but never writes — for a call that must not + /// change what a later bare `continue`/`status` resolves to. `status`'s + /// own doc offers `dir` as a one-off "check a different directory" + /// knob; if that call committed the same way `start`/`continue_` do, the + /// one-off peek would silently become the new remembered default (the + /// second bug argus flagged in the same review). + pub(super) fn peek_dir(&self, name: &str, dir: Option<&str>) -> Option { + match dir { + Some(d) => Some(d.to_owned()), + None => self + .dirs + .lock() + .unwrap_or_else(PoisonError::into_inner) + .get(name) + .cloned(), + } + } + + /// Upgrade `name`'s `Starting` reservation to a real, interruptible + /// process. Same key as the reservation, so there is no window in which + /// `name` reads as unoccupied between the two. + pub(super) fn track(&self, name: &str, stop: TurnStop) { + self.running + .lock() + .unwrap_or_else(PoisonError::into_inner) + .insert(name.to_owned(), Slot::Running(stop)); + tracing::info!(name, "subagent process tracked"); + } + + /// Drop `name`'s cancel handle but keep the name claimed — the moment + /// between a continued turn's child exiting and its successor being + /// spawned. Without it the name would read as free mid-loop and a + /// concurrent `start` could take it out from under the continuation; + /// with it, `status` says "starting" and `interrupt` says "still + /// starting, retry shortly", both of which are true of the sub-second + /// gap it covers. + pub(super) fn between_turns(&self, name: &str) { + self.running + .lock() + .unwrap_or_else(PoisonError::into_inner) + .insert(name.to_owned(), Slot::Starting); + tracing::info!(name, "subagent name held between goal turns"); + } + + /// Set (or clear) `name`'s goal and start its turn budget over at turn + /// one. Called by `start` only: the goal is a property of the session + /// being created, and a later `continue` re-prompts toward whatever + /// `start` set rather than redefining it. + pub(super) fn set_goal(&self, name: &str, goal: Option, max_turns: u32) { + let mut goals = self.goals.lock().unwrap_or_else(PoisonError::into_inner); + match goal { + Some(goal) => { + goals.insert( + name.to_owned(), + GoalState { + goal, + max_turns, + turn: 1, + }, + ); + } + None => { + goals.remove(name); + } + } + } + + /// Put `name` back at turn one, keeping whatever goal `start` set. A + /// `continue` is the parent's own deliberate turn, and the cap exists to + /// bound *unattended* continuation — so its allowance starts over rather + /// than a capped session being permanently un-continuable. The parent + /// was always the authority on whether more turns are worth spending. + pub(super) fn restart_turns(&self, name: &str) { + if let Some(goal) = self + .goals + .lock() + .unwrap_or_else(PoisonError::into_inner) + .get_mut(name) + { + goal.turn = 1; + } + } + + /// Commit a `continue` whose session has been found: remember its `dir` + /// (see `resolve_dir`), drop the stop reason that described the run + /// before it, and give a goal session its allowance back (see + /// `restart_turns`). + pub(super) fn begin_continue(&self, name: &str, dir: Option<&str>) { + self.resolve_dir(name, dir); + self.clear_stop(name); + self.restart_turns(name); + } + + /// `(turn, max_turns)` for `name`. `None` for a session with no goal, + /// which has no turn budget to be partway through — reporting `1 of 1` + /// there would invent a cap that isn't enforced. + pub(super) fn turns(&self, name: &str) -> Option<(u32, u32)> { + self.goals + .lock() + .unwrap_or_else(PoisonError::into_inner) + .get(name) + .map(|g| (g.turn, g.max_turns)) + } + + /// Record why `name` stopped. Idempotent by design: the subagent's own + /// signal lands here mid-turn and the loop re-records the same reason at + /// the turn's end, so both paths can write without checking. + pub(super) fn record_stop(&self, name: &str, stop: StopReason) { + self.stops + .lock() + .unwrap_or_else(PoisonError::into_inner) + .insert(name.to_owned(), stop); + } + + pub(super) fn stop_reason(&self, name: &str) -> Option { + self.stops + .lock() + .unwrap_or_else(PoisonError::into_inner) + .get(name) + .cloned() + } + + /// Forget why `name` last stopped — called when a new turn is starting, + /// since the record describes the run before it and would otherwise make + /// a session that has since been given another turn still read as + /// blocked or out of turns. + pub(super) fn clear_stop(&self, name: &str) { + self.stops + .lock() + .unwrap_or_else(PoisonError::into_inner) + .remove(name); + } + + /// Remember where `name` writes its report, so a stop reason can be + /// appended to the artifact a parent already reads rather than living + /// only in a todo. `None` leaves whatever was remembered alone, so a + /// signal tool that doesn't name a path doesn't erase the one `start` + /// gave. + /// + /// Never inferred: `start` carries what the brief named, and the signal + /// tools carry where the subagent says it actually wrote. A daemon that + /// derived this from a path convention would be guessing about someone + /// else's layout. + pub(super) fn set_report_file(&self, name: &str, path: Option<&str>) { + if let Some(path) = path { + self.reports + .lock() + .unwrap_or_else(PoisonError::into_inner) + .insert(name.to_owned(), PathBuf::from(path)); + } + } + + /// Forget `name`'s report path — a fresh `start` under the same name is + /// a different piece of work, and inheriting the last one's artifact + /// path would append its stop reason to a file this run never wrote. + pub(super) fn clear_report_file(&self, name: &str) { + self.reports + .lock() + .unwrap_or_else(PoisonError::into_inner) + .remove(name); + } + + pub(super) fn report_file(&self, name: &str) -> Option { + self.reports + .lock() + .unwrap_or_else(PoisonError::into_inner) + .get(name) + .cloned() + } + + /// What the continuation loop does after a turn that ran to completion: + /// stop with a reason, or spend another turn re-prompting toward the + /// goal. Advances the turn counter itself, since deciding to continue + /// and consuming a turn are the same act. + /// + /// A signal the subagent raised mid-turn is already in `stops` and wins + /// outright — that is what "both stop goal continues" means, and it's + /// checked before the goal so a `goal_reached` on the last allowed turn + /// reads as reached rather than as capped. + pub(super) fn plan_after_turn(&self, name: &str) -> Continuation { + if let Some(stop) = self.stop_reason(name) { + return Continuation::Stop(stop); + } + let mut goals = self.goals.lock().unwrap_or_else(PoisonError::into_inner); + let Some(state) = goals.get_mut(name) else { + return Continuation::Stop(StopReason::Done); + }; + if state.turn >= state.max_turns { + return Continuation::Stop(StopReason::TurnCap { turns: state.turn }); + } + state.turn += 1; + Continuation::Continue { + prompt: continuation_prompt(name, &state.goal, state.turn, state.max_turns), + } + } +} diff --git a/hive-subagent-mcp/src/session/status.rs b/hive-subagent-mcp/src/session/status.rs new file mode 100644 index 000000000..a9b819a83 --- /dev/null +++ b/hive-subagent-mcp/src/session/status.rs @@ -0,0 +1,432 @@ +//! What a caller asks about a run: `status`, `interrupt`, their wording, and the +//! todo a turn's end pushes. + +use super::{ + Duration, Occupancy, PoisonError, Refusal, Slot, State, StopReason, SubagentRuntime, TurnEnd, + acp_session_file, build_config, build_store, describe_signal, validate_name, +}; + +/// Report whether `name` is currently running — a zero-cost check that +/// never launches a process, unlike `continue`. Distinguishes running, +/// starting (reserved, not yet a confirmed spawn — see `State`'s doc), +/// killed (its last turn died on a signal), each of the four ways a goal +/// run stops, idle (a session exists, its last turn finished, nothing is in +/// flight), and no such session at all. +/// +/// A *running* answer also carries how long since that turn last produced +/// output, which is the part of this answer a caller can act on: "running" +/// describes a wedged child and a busy one identically, and the age +/// separates them (see `State`'s `last_event` doc). +/// +/// A goal-continued session carries `turn N of M` alongside that, in every +/// state. With the age, it is what lets a caller tell *working* from +/// *wedged* from *out of turns* off one answer, without reaching for `ps` +/// or reading any file. +/// +/// # Errors +/// +/// An invalid name, or no session — running, killed, stopped or on disk — +/// under `name`. +pub fn status(state: &State, name: &str, dir: Option<&str>) -> anyhow::Result { + validate_name(name)?; + // Read-only: an explicit `dir` here is a one-off "check this other + // directory's session" per this fn's own doc, not a new remembered + // default — `peek_dir` resolves the same way but never writes. + let dir = state.peek_dir(name, dir); + let facts = StatusFacts { + occupancy: state.occupancy(name), + killed: state.killed_by(name), + last_event_age: state.last_event_age(name), + turns: state.turns(name), + stop: state.stop_reason(name), + ..StatusFacts::new(name) + }; + // Nothing on disk to look for while something is tracked in memory — + // those states answer on their own, and the store read is the only + // expensive part of this call. A recorded stop reason counts: it is + // proof this daemon ran the session, which is what the lookup asks. + let session_exists = + if facts.occupancy.is_none() && facts.killed.is_none() && facts.stop.is_none() { + if let SubagentRuntime::Acp { sessions, .. } = &state.runtime { + acp_session_file(sessions, name).exists() + } else { + // No signal surface in this config: it exists only to resolve + // the session store, and rendering a subagent's MCP config for + // a read-only status check would be writing a file for nobody. + let config = build_config(name, None, None, None, dir.as_deref(), None); + build_store(&config)?.find_by_title(name).is_some() + } + } else { + false + }; + describe_status(&StatusFacts { + session_exists, + ..facts + }) +} + +/// The liveness clause appended to a *running* answer, and the whole point +/// of recording the timestamp: an age in seconds a caller can read a verdict +/// off directly, rather than one it has to go and measure itself with `ps` +/// and CPU-time deltas. +/// +/// Deliberately just the number now — the full "seconds means working, +/// minutes means wedged, resets each turn" explanation used to repeat here +/// on every single call. It already lives in the `status` tool description +/// and in `docs/4-implementation/agent-tools/subagent.md`'s "Telling working from wedged" +/// section, so restating it in a line meant to be skimmed, possibly several +/// times a minute, was pure repetition. +/// +/// Empty when there's no age to report — a turn that ended between `status` +/// reading `running` and reading the clock. Saying nothing is right there: +/// the alternative is an age that describes a turn which has already +/// finished, which reads as a stall that never happened. +fn describe_liveness(age: Option) -> String { + match age { + None => String::new(), + Some(age) => format!(" Last event {}s ago.", age.as_secs()), + } +} + +/// The progress sentence a goal-continued session carries in every state: +/// which turn of its budget it is on. Empty for a session with no goal, +/// which has no budget to be partway through. +/// +/// On a *running* answer this is the turn in flight; on a stopped one it is +/// the turn it stopped on — the same number either way, since the counter +/// only advances when the loop decides to spend another turn. +fn describe_turns(turns: Option<(u32, u32)>) -> String { + match turns { + None => String::new(), + Some((turn, max_turns)) => format!(" Turn {turn} of {max_turns}."), + } +} + +/// Everything `status` gathers, as one value — seven separate parameters +/// read as noise at both the call site and the test sites, and every one of +/// them is a fact about the same session. +pub(super) struct StatusFacts<'a> { + pub(super) name: &'a str, + pub(super) occupancy: Option, + pub(super) killed: Option, + pub(super) session_exists: bool, + pub(super) last_event_age: Option, + pub(super) turns: Option<(u32, u32)>, + pub(super) stop: Option, +} + +impl<'a> StatusFacts<'a> { + /// The nothing-known baseline for `name`: no process, no records, no + /// session. Both the real gathering in `status` and the tests build on + /// it, so neither has to spell out the fields it isn't exercising. + pub(super) fn new(name: &'a str) -> Self { + Self { + name, + occupancy: None, + killed: None, + session_exists: false, + last_event_age: None, + turns: None, + stop: None, + } + } +} + +/// Render `status`'s answer from the facts it gathers. Split out from the +/// gathering so the killed-versus-idle distinction — and the liveness age, +/// the turn counter and each stop reason — are exercisable without a real +/// spawn, a real signal, a real stream of events and a real on-disk claude +/// session. +/// +/// A recorded kill outranks both the stop reason and the on-disk session: +/// the session file exists either way and a stop reason may be left over +/// from the signal a subagent raised just before something killed it, so +/// neither can tell a killed turn from a finished one. The kill can. +/// +/// Every answer is self-contained — it names the one state the caller got +/// and what to do next — because the tool description deliberately doesn't +/// enumerate the state space (the operator's ruling on this surface: +/// describe the tool, explain the state when returning it). Keep the split: +/// a terser answer here has nowhere left to be explained from. +pub(super) fn describe_status(facts: &StatusFacts<'_>) -> anyhow::Result { + let name = facts.name; + let turns = describe_turns(facts.turns); + match facts.occupancy { + Some(Occupancy::Running) => { + return Ok(format!( + "subagent `{name}` is running — its turn is still in flight, so there's nothing \ + to do but let it work: the daemon pushes a todo when the run ends, or \ + `interrupt` it if you want it stopped early.{turns}{}{}", + describe_liveness(facts.last_event_age), + describe_pending_signal(facts.stop.as_ref()), + )); + } + Some(Occupancy::Starting) => { + return Ok(format!( + "subagent `{name}` is starting — the name is claimed but no process is confirmed \ + under it yet, either because a `start`/`continue` hasn't spawned one or because \ + a goal run is between turns. Normally over in well under a second: check again \ + shortly rather than starting anything else under this name.{turns}" + )); + } + Some(Occupancy::Stopping) => { + return Ok(format!( + "subagent `{name}` is stopping — `interrupt` sent it SIGINT and its process \ + hasn't exited yet. The name stays claimed until it does, so `start` and \ + `continue` are refused meanwhile. Nothing escalates past that SIGINT: one that \ + never exits needs killing by hand.{turns}{}", + describe_liveness(facts.last_event_age), + )); + } + None => {} + } + if let Some(signal) = facts.killed { + return Ok(format!( + "subagent `{name}` was killed — its last turn died on {}, so its work stopped \ + wherever it had got to rather than finishing. `continue` still resumes it, but \ + whatever it was told to do is unfinished: check what it actually left behind before \ + trusting it.{turns}", + describe_signal(signal) + )); + } + if let Some(stop) = &facts.stop { + return Ok(describe_stopped(name, stop, &turns)); + } + if facts.session_exists { + Ok(format!( + "subagent `{name}` is idle — its session exists, its last turn ended on its own \ + rather than being cut off, and nothing is in flight: that turn's own todo says how \ + it went, and `continue` gives it another.{turns}" + )) + } else { + anyhow::bail!( + "no subagent named `{name}` exists — nothing is running under that name and there's \ + no session on disk to resume, so `start` is what creates one (check the name if you \ + expected something here)." + ) + } +} + +/// The note a *running* answer carries when the subagent has already raised +/// a stop signal for the turn still in flight. Without it a parent polling +/// `status` would read plain "running" for the whole stretch between the +/// subagent saying it is blocked and its turn actually ending — the one +/// stretch where "it's working, leave it alone" is the wrong conclusion. +fn describe_pending_signal(stop: Option<&StopReason>) -> String { + match stop { + None | Some(StopReason::Done | StopReason::TurnCap { .. }) => String::new(), + Some(stop) => format!( + " It has already signalled how this run ends — {} — so this is its last turn.", + stop.sentence() + ), + } +} + +/// The answer for a session whose run has stopped, one per [`StopReason`]. +/// Each names the state, why the continuation stopped, and what `continue` +/// would do about it — and the `GoalReached` one is deliberately the least +/// reassuring of them, because it is the one a caller is most likely to +/// read as "finished successfully" when it means "said so". +fn describe_stopped(name: &str, stop: &StopReason, turns: &str) -> String { + match stop { + StopReason::Done => format!( + "subagent `{name}` is idle — its session exists, its last turn ended on its own \ + rather than being cut off, and nothing is in flight: that turn's own todo says how \ + it went, and `continue` gives it another.{turns}" + ), + StopReason::GoalReached(msg) => format!( + "subagent `{name}` stopped: it reported its goal reached{}. Nothing is in flight and \ + no further goal turn will start.{turns} That report is the subagent's own claim, not \ + a verification of anything — read the diff and whatever gate the work was supposed \ + to pass before you treat the goal as met, exactly as you would a build report saying \ + the tests passed.", + msg.as_deref() + .map_or_else(String::new, |m| format!(": {m}")) + ), + StopReason::NeedHelp(msg) => format!( + "subagent `{name}` is BLOCKED and needs help: {msg}. It called `need_help`, which \ + stopped its goal continuation, and nothing is in flight — it stays blocked until you \ + answer it. `continue` is how you answer: give it what it asked for as the next \ + turn's prompt." + ), + StopReason::TurnCap { turns: spent } => format!( + "subagent `{name}` ran out of turns — the harness limit of {spent} was reached and it \ + never reported its goal reached, so the work stopped wherever it had got to rather \ + than finishing.{turns} Check what it actually left behind; `continue` gives it a \ + fresh allowance if carrying on is worth it." + ), + StopReason::Cancelled => format!( + "subagent `{name}` was CANCELLED — someone called `interrupt` on it, which stopped \ + the run and not merely the turn that was in flight, so nothing further will start \ + on its own.{turns} Its work stopped wherever it had got to: check what it left \ + behind before acting on it. `continue` restarts it, with a fresh turn allowance." + ), + } +} + +/// Stop `name`'s running turn: SIGINT to claude's process group (see +/// `hive_claude::Cancel::cancel`), or `session/cancel` on ACP. Nothing +/// escalates to SIGKILL: each command claude's Bash tool starts leads its +/// own session, and only claude shutting down on SIGINT stops it. +/// +/// Returns without waiting. A claude turn's name stays claimed as +/// `Slot::Stopping` until the turn's own `finish_turn` clears it, so no +/// second claude starts on the session while the first is winding down. +/// +/// It stops the goal run, not just the turn, by **recording +/// `StopReason::Cancelled`**: claude answers SIGINT by emitting its +/// terminal `result` event and exiting 0, which is `TurnEnd::Complete`, so +/// only the recorded reason, which `plan_after_turn` checks before the +/// goal, keeps the loop from re-prompting. It is written while the +/// `running` lock is held, so a turn that ends on its own in between still +/// finds it. +/// +/// # Errors +/// +/// An invalid name, nothing tracked under `name`, nothing to signal right +/// now (a spawn or ACP turn not yet live, or a goal run between turns; the +/// reservation is put back, so a concurrent `start`/`continue` is still +/// refused), or a claude already signalled and not yet exited. +pub fn interrupt(state: &State, name: &str) -> anyhow::Result { + validate_name(name)?; + let mut running = state.running.lock().unwrap_or_else(PoisonError::into_inner); + let mut claimed = ""; + match running.remove(name) { + None => anyhow::bail!("no subagent named `{name}` is currently running"), + Some(Slot::Starting) => { + running.insert(name.to_owned(), Slot::Starting); + tracing::info!(name, "interrupt refused: no process is tracked yet"); + return Err(still_starting(name)); + } + Some(Slot::Stopping) => { + running.insert(name.to_owned(), Slot::Stopping); + anyhow::bail!( + "subagent `{name}` was already interrupted and its process hasn't exited yet — \ + `status` says when it has" + ); + } + // `stop()` is `false` when no turn is in flight (an ACP agent not + // prompted yet, or a turn just ended), and then nothing was stopped. + // The stop goes in before the signal and comes out under the same + // `stops` lock, so `plan_after_turn` never reads a cancel that + // didn't happen. + Some(Slot::Running(stop)) => { + let mut stops = state.stops.lock().unwrap_or_else(PoisonError::into_inner); + let prior = stops.insert(name.to_owned(), StopReason::Cancelled); + if !stop.stop() { + match prior { + Some(prior) => stops.insert(name.to_owned(), prior), + None => stops.remove(name), + }; + drop(stops); + running.insert(name.to_owned(), Slot::Running(stop)); + return Err(still_starting(name)); + } + drop(stops); + if matches!(state.runtime, SubagentRuntime::Claude) { + running.insert(name.to_owned(), Slot::Stopping); + claimed = " The name stays claimed until claude has exited; `status` says \ + `stopping` until then."; + } + } + } + Ok(format!( + "interrupt sent to subagent `{name}` — the run is cancelled, not just the turn that was \ + in flight, so no further goal turn will start. `continue` is what restarts it, with a \ + fresh turn allowance.{claimed}" + )) +} + +/// `start`'s and `continue`'s refusal for a name `reserve_under` would not +/// claim. +pub(super) fn refused(state: &State, name: &str, refusal: &Refusal, hint: &str) -> anyhow::Error { + match refusal { + Refusal::Taken => name_taken(state, name, hint), + Refusal::AtCap { cap: 0, .. } => anyhow::anyhow!( + "subagents are disabled for this agent: the cap is 0 (set in swarm-ui → this \ + agent → inference)" + ), + Refusal::AtCap { running, cap } => anyhow::anyhow!( + "{running} {} running, cap is {cap} (set in swarm-ui → this agent → \ + inference) — wait for one to finish, or `interrupt` one", + if *running == 1 { + "subagent" + } else { + "subagents" + } + ), + } +} + +/// `start`'s and `continue`'s refusal for a name `reserve_under` found claimed: +/// `hint` says what to do about a live session, and an interrupted one that +/// hasn't exited yet gets its own answer. +fn name_taken(state: &State, name: &str, hint: &str) -> anyhow::Error { + if state.occupancy(name) == Some(Occupancy::Stopping) { + anyhow::anyhow!( + "subagent `{name}` is stopping — it was interrupted and its process hasn't exited \ + yet; the name is free once it has (`status` says when)" + ) + } else { + anyhow::anyhow!("subagent `{name}` is already running — {hint}") + } +} + +/// `interrupt`'s refusal for a name that is claimed but has nothing to +/// signal yet. +fn still_starting(name: &str) -> anyhow::Error { + anyhow::anyhow!( + "subagent `{name}` is still starting — not yet confirmed running, try again shortly" + ) +} + +/// Push `name`'s one-shot end-of-turn todo. Best-effort: a connect/write +/// failure is logged and swallowed, matching every other in-agent-socket +/// producer in this codebase — there's no retry queue to fall back to, and +/// the caller has already moved on by the time this fires. +pub(super) async fn push_turn_end_todo( + socket: &std::path::Path, + name: &str, + end: &TurnEnd, + stop: Option<&StopReason>, +) { + let req = hive_agent_sock::Request::UpsertTodo { + subsystem: "subagent".to_owned(), + key: Some(name.to_owned()), + summary: turn_end_summary(name, end, stop), + source: None, + reopen_if_acked: false, + }; + if let Err(e) = hive_sock_client::notify(socket, &req, hive_sock_client::Retry::None).await { + tracing::warn!(name, error = ?e, "subagent: end-of-turn todo push failed"); + } +} + +/// The todo text for a run that has ended. A killed turn deliberately does +/// not use the "finished" wording the other two share: this todo is the only +/// thing the owning agent is shown without asking, so it has to read as the +/// interruption it is rather than as one more completed subagent. +/// +/// A `stop` **extends** that message, it never replaces it. Both halves are +/// load-bearing and neither substitutes for the other: the turn's own end is +/// what the daemon observed, the stop reason is why the run went no further +/// — and for `GoalReached` that second half is a claim, which would read as +/// a verdict if it were allowed to stand where the observed end belongs. +/// `StopReason::Done` adds nothing, since "there was no goal" is exactly +/// what the unextended message already describes. +pub(super) fn turn_end_summary(name: &str, end: &TurnEnd, stop: Option<&StopReason>) -> String { + let base = match end { + TurnEnd::Complete => format!("subagent `{name}` finished: turn complete"), + TurnEnd::Failed(e) => format!("subagent `{name}` finished: {e}"), + TurnEnd::Killed { signal } => format!( + "subagent `{name}` was KILLED mid-turn ({}) — it did not finish, and its work stopped \ + wherever it had got to. Check what it left behind before you act on it; `continue` \ + resumes the session if you want it carried on.", + describe_signal(*signal) + ), + }; + match stop { + None | Some(StopReason::Done) => base, + Some(stop) => format!("{base} — and the run stopped there: {}", stop.sentence()), + } +} diff --git a/hive-subagent-mcp/src/session/tests.rs b/hive-subagent-mcp/src/session/tests.rs new file mode 100644 index 000000000..00e20cd1d --- /dev/null +++ b/hive-subagent-mcp/src/session/tests.rs @@ -0,0 +1,462 @@ +// Tests of `session`, split by what they test. The helpers they share are in this file, and +// each topic is a submodule that reaches them through `super::*`. + +use super::*; +use super::{config::*, run::*, status::*}; + +mod config; +mod goal; +mod run; +mod state; +mod status; + +/// A stand-in for the signal route a real daemon would hand its +/// subagents — the *prefix*, as `State::new` takes it. Nothing in these +/// tests dials it: what `State` does with it is append a minted token and +/// carry the result into `build_config`, both asserted on directly. +fn signal_url() -> String { + "http://127.0.0.1:1/signal/mcp".to_owned() +} + +/// The token out of a minted URL — what the route would have parsed out +/// of the path before resolving it. +fn token_of(url: &str) -> String { + url.rsplit('/') + .next() + .expect("a minted URL always has a last segment") + .to_owned() +} + +/// A `StartRequest` with only the fields a test cares about set — the +/// other six are the same "nothing asked for" every time. +fn start_request(name: &str) -> StartRequest { + StartRequest { + name: name.to_owned(), + model: None, + effort: None, + prompt_file: "/tmp/prompt.md".to_owned(), + role: None, + trigger: "trigger".to_owned(), + dir: None, + goal: None, + max_turns: None, + report_file: None, + } +} + +/// A scratch file holding `body`, named after `tag` so parallel tests +/// never share one. +fn scratch_file(tag: &str, body: &str) -> PathBuf { + let path = std::env::temp_dir().join(format!("hive-subagent-session-test-{tag}.md")); + std::fs::write(&path, body).expect("a scratch file is writable"); + path +} + +/// The `--tools` value as it reaches the spawned argv. +fn spawned_tools(config: &Config) -> &str { + let flag = config + .extra_args + .iter() + .position(|a| a == "--tools") + .expect("--tools is passed on every spawn"); + config + .extra_args + .get(flag + 1) + .expect("--tools carries a value") +} + +/// The error the driver hands back for a child that died on `signal` — +/// `ExitStatus::from_raw` takes a raw `wait(2)` status, whose low seven +/// bits are the terminating signal, so this is the same value +/// `RunningClaude::wait` would have produced from a real kill. +fn signalled_exit(signal: i32) -> hive_claude::Error { + hive_claude::Error::Exit { + status: std::process::ExitStatus::from_raw(signal), + stderr_tail: String::new(), + } +} + +/// The `Failed` end a real missed resume produces, message and all — +/// `classify_end`'s own output for the error the driver raises when +/// `--resume` matches nothing. +fn missed_resume() -> TurnEnd { + classify_end( + Err(hive_claude::Error::SessionNotFound), + Some( + "(searched /home/agent/.claude for cwd /home/agent/work; if it was started \ + elsewhere, pass the `dir` it was started in)", + ), + ) +} + +/// A state with `name` mid-run against `goal`, as `start` would have left +/// it: reserved, goal registered, on turn one of `max_turns`. +fn mid_run(name: &str, goal: &str, max_turns: u32) -> State { + let state = State::new(PathBuf::from("/dev/null"), signal_url()); + state.reserve(name); + state.set_goal(name, Some(goal.to_owned()), max_turns); + state +} + +/// A stand-in for claude that reproduces the one behaviour the cancel +/// turns on: on SIGINT it exits **zero**. The real `claude --print` does +/// exactly this — it writes its terminal `result` event and shuts down +/// cleanly — which is why an interrupted turn is indistinguishable from +/// a completed one by exit status alone, and why `interrupt` cannot rely +/// on the child's death to stop the run. +/// +/// It appends a line to `log` as its very first act, so the file is a +/// count of how many turns the continuation loop actually spawned. Every +/// argument is ignored; the driver's own flags mean nothing here. +/// +/// The wait is `sleep &` + `wait` rather than a plain foreground +/// `sleep`: a POSIX shell runs a pending trap as soon as `wait` returns, +/// but defers it until a *foreground* child has finished — which for a +/// 30-second sleep is long after the test has given up. The background +/// sleep gets its own stdout/stderr for the mirror-image reason: it +/// would otherwise inherit and keep open the pipes the driver reads to +/// EOF, so `RunningClaude::wait` would not return until the orphaned +/// sleep expired, and the turn would look like it was still running. +fn fake_claude(dir: &Path, log: &Path) -> PathBuf { + let script = dir.join("fake-claude"); + write_executable( + &script, + &format!( + "#!/bin/sh\necho turn >> '{}'\ntrap 'exit 0' INT\nsleep 30 >/dev/null 2>&1 &\nwait\n", + log.display() + ), + ); + script +} + +/// How many turns the fake has been spawned for so far. +fn turns_spawned(log: &Path) -> usize { + std::fs::read_to_string(log).map_or(0, |body| body.lines().count()) +} + +/// A stand-in for claude with a command of its own still running: an +/// inner `sh` writes its pid to `pidfile` and execs `sleep`. It runs in +/// the foreground because a non-interactive shell starts `&` jobs with +/// SIGINT ignored, and its output goes to /dev/null so it cannot hold the +/// driver's pipes open. +fn busy_claude(dir: &Path, pidfile: &Path) -> PathBuf { + let script = dir.join("busy-claude"); + write_executable( + &script, + &format!( + "#!/bin/sh\nsh -c 'echo $$ >\"$1\"; exec sleep 300' sh '{}' >/dev/null 2>&1\n", + pidfile.display() + ), + ); + script +} + +/// Poll `path` until it holds a complete, newline-terminated pid. +async fn read_pid(path: &Path) -> i32 { + for _ in 0..250 { + if let Ok(text) = std::fs::read_to_string(path) + && text.ends_with('\n') + { + return text.trim().parse().expect("pid file holds a pid"); + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + unreachable!("no pid in {} within 5s", path.display()); +} + +/// Whether `pid` is still running. A zombie counts as gone: it has +/// exited, and `kill(pid, 0)` only keeps finding it until it is reaped. +fn is_running(pid: i32) -> bool { + // SAFETY: signal 0 delivers nothing; it only checks that `pid` exists. + if unsafe { libc::kill(pid, 0) } != 0 { + return false; + } + !std::fs::read_to_string(format!("/proc/{pid}/stat")).is_ok_and(|stat| { + stat.rsplit_once(") ") + .is_some_and(|(_, rest)| rest.starts_with('Z')) + }) +} + +/// A stand-in for claude that shuts down on SIGINT the way claude does: +/// it writes `interrupted` once the signal arrives, then exits 0 as soon +/// as `release` exists, or after 10s. It writes `ready` once its trap is +/// set. A SIGKILL leaves no `interrupted` behind. +fn graceful_claude(dir: &Path) -> PathBuf { + let script = dir.join("graceful-claude"); + write_executable( + &script, + &format!( + "#!/bin/sh\ncd '{}'\ntrap ': > interrupted; i=0; until [ -e release ] || \ + [ $i -ge 200 ]; do sleep 0.05; i=$((i+1)); done; kill $!; exit 0' INT\n\ + sleep 300 >/dev/null 2>&1 &\n: > ready\nwait\n", + dir.display() + ), + ); + script +} + +/// Spawn [`graceful_claude`] as `n`'s turn and wait until its trap is set. +async fn spawn_graceful(state: &Arc, dir: &Path) { + let config = Config { + program: Some(graceful_claude(dir)), + ..Config::default() + }; + spawn_and_track( + state, + "n", + &config, + &Attach::Create("n".to_owned()), + "turn one".to_owned(), + None, + ) + .expect("the fake claude spawns"); + until("the fake claude sets its trap", || { + dir.join("ready").exists() + }) + .await; +} + +fn local(env: Option<&str>) -> ModelList { + ModelList::Local(env.map(str::to_owned)) +} + +fn swarm(models: &[&str]) -> crate::swarm_models::Read { + crate::swarm_models::Read::Current(AgentInference { + subagent_models: Some(models.iter().map(|m| (*m).to_owned()).collect()), + ..AgentInference::default() + }) +} + +fn unset() -> crate::swarm_models::Read { + crate::swarm_models::Read::Current(AgentInference::default()) +} + +fn capped(max: u32) -> crate::swarm_models::Read { + crate::swarm_models::Read::Current(AgentInference { + max_subagents: Some(max), + ..AgentInference::default() + }) +} + +/// A state whose swarm read answers `read` and whose own list is `haiku`, +/// with `name` already reserved: a call that gets past the model check +/// stops at `reserve_under` and spawns nothing. Also the reader's read count. +fn state_reading( + read: crate::swarm_models::Read, + name: &str, +) -> (Arc, Arc) { + let (reader, reads) = crate::swarm_models::Reader::fixed(read); + let mut state = + State::new(PathBuf::from("/dev/null"), signal_url()).reading_models_from(Some(reader)); + state.local_models = || Some("haiku".to_owned()); + assert!(state.reserve(name)); + (Arc::new(state), reads) +} + +fn start_on(name: &str, model: Option<&str>) -> StartRequest { + StartRequest { + model: model.map(str::to_owned), + ..start_request(name) + } +} + +async fn continue_on( + state: &Arc, + name: &str, + model: Option<&str>, +) -> anyhow::Result { + continue_( + state, + name, + "go".to_owned(), + model.map(str::to_owned), + None, + None, + ) + .await +} + +/// A `tracing` writer whose output a test can read back. +#[derive(Clone, Default)] +struct CapturedLogs(Arc>>); + +impl CapturedLogs { + fn text(&self) -> String { + String::from_utf8_lossy(&self.0.lock().unwrap()).into_owned() + } +} + +impl std::io::Write for CapturedLogs { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for CapturedLogs { + type Writer = Self; + fn make_writer(&'a self) -> Self::Writer { + self.clone() + } +} + +/// An ACP agent in plain `sh`, after `hive-runtime`'s own test agent. It +/// has one session, `s1`, appends every method it is sent to +/// `.methods` and every `session/prompt` line to ``, and +/// answers each prompt with `end_turn` and a token `usage` — or, in +/// `hold` mode, only once `session/cancel` arrives. The `usage` keeps a +/// plain reply from `hive_runtime::acp::AcpError::EmptyEndTurn`, the +/// same reason `hive-runtime`'s own test agent's replies carry one. +const ACP_AGENT: &str = r#" +prompt= +while IFS= read -r line; do + id=${line#*\"id\":}; id=${id%%[,\}]*} + m=${line#*\"method\":\"}; m=${m%%\"*} + printf '%s\n' "$m" >> "$1.methods" + case $m in +initialize) + printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true}}}}\n' "$id" ;; +session/new) + printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"s1"}}\n' "$id" ;; +session/load) + printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id" ;; +session/prompt) + printf '%s\n' "$line" >> "$1" + if [ "$2" = hold ]; then + prompt=$id + else + printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","usage":{"inputTokens":1,"outputTokens":1}}}\n' "$id" + fi ;; +session/cancel) + if [ -n "$prompt" ]; then + printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"cancelled"}}\n' "$prompt" + prompt= + fi ;; + esac +done +"#; + +fn scratch_dir(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "hive-subagent-{tag}-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("scratch dir"); + dir +} + +/// `state` running its subagents on [`ACP_AGENT`] in `mode`, keeping +/// sessions and the agent's logs in `dir`. +fn on_acp_agent(mut state: State, dir: &Path, mode: &str) -> State { + let script = dir.join("agent.sh"); + std::fs::write(&script, ACP_AGENT).expect("write the ACP agent"); + state.runtime = SubagentRuntime::Acp { + command: AcpCommand { + command: "/bin/sh".into(), + args: vec![ + script.display().to_string(), + dir.join("prompts").display().to_string(), + mode.to_owned(), + ], + env: std::collections::BTreeMap::new(), + api_key_env: None, + }, + sessions: dir.to_path_buf(), + }; + state +} + +/// A config that would run [`fake_claude`], so a test on the ACP runtime +/// can show that claude was never spawned, with claude's session store +/// in `dir` rather than the ambient `HOME`. +fn claude_config(dir: &Path) -> Config { + Config { + program: Some(fake_claude(dir, &dir.join("claude-turns"))), + cwd: Some(dir.to_path_buf()), + claude_config_dir: Some(dir.join("claude-home")), + ..Config::default() + } +} + +fn lines(path: &Path) -> Vec { + std::fs::read_to_string(path) + .map(|body| body.lines().map(str::to_owned).collect()) + .unwrap_or_default() +} + +async fn until(what: &str, done: impl Fn() -> bool) { + for _ in 0..200 { + if done() { + return; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + panic!("timed out waiting until {what}"); +} + +/// A stand-in for claude's session store. `--name` writes +/// `$CLAUDE_CONFIG_DIR/projects//session-.jsonl` carrying a +/// `custom-title` event. `--resume` takes an id from the cwd's project +/// dir, or a title matched against every live session under `projects/` +/// — each project dir standing for a worktree of one repo, which is how +/// far claude 2.1.287 looks for a title — and refuses unless exactly one +/// matches. Each attach is logged to `$CLAUDE_CONFIG_DIR/attaches`. +const SESSION_CLAUDE: &str = r#"#!/bin/sh +cat >/dev/null +projects="$CLAUDE_CONFIG_DIR/projects" +here="$projects/$(pwd -P | tr '/.' '--')" +while [ $# -gt 0 ]; do + case "$1" in +--name) mode=create; arg=$2; shift ;; +--resume) mode=resume; arg=$2; shift ;; + esac + shift +done +if [ "$mode" = create ]; then + n=$(cat "$CLAUDE_CONFIG_DIR/count" 2>/dev/null || echo 0) + echo $((n + 1)) > "$CLAUDE_CONFIG_DIR/count" + id="session-$n" + mkdir -p "$here" + printf '{"type":"custom-title","customTitle":"%s"}\n' "$arg" > "$here/$id.jsonl" +elif [ -f "$here/$arg.jsonl" ]; then + id=$arg +else + matches=$(grep -l "\"customTitle\":\"$arg\"" "$projects"/*/*.jsonl 2>/dev/null) + count=$(printf '%s' "$matches" | grep -c .) + if [ "$count" -ne 1 ]; then +echo "Error: --resume \"$arg\" matches $count sessions" >&2 +exit 1 + fi + id=$(basename "$matches" .jsonl) +fi +echo "$mode $id" >> "$CLAUDE_CONFIG_DIR/attaches" +echo '{"type":"system","subtype":"init"}' +echo '{"type":"result","subtype":"success","is_error":false}' +"#; + +/// Write an executable script from a child process rather than from +/// this one: a write fd on it held here could be inherited by a child +/// another test thread forks, and exec'ing a file some process still +/// holds open for writing fails with `ETXTBSY`. +fn write_executable(path: &Path, body: &str) { + let status = std::process::Command::new("/bin/sh") + .args([ + "-c", + r#"printf '%s' "$1" > "$2" && chmod 755 "$2""#, + "sh", + body, + ]) + .arg(path) + .status() + .expect("run /bin/sh"); + assert!(status.success(), "writing {} failed", path.display()); +} + +fn env_of<'a>(env: &'a [(String, String)], name: &str) -> Option<&'a str> { + env.iter().find(|(n, _)| n == name).map(|(_, v)| v.as_str()) +} diff --git a/hive-subagent-mcp/src/session/tests/config.rs b/hive-subagent-mcp/src/session/tests/config.rs new file mode 100644 index 000000000..3fc22645c --- /dev/null +++ b/hive-subagent-mcp/src/session/tests/config.rs @@ -0,0 +1,334 @@ +//! The model list, the swarm's cap and what a run is started with. + +use super::*; + +// One test, not two: `subagent_otel_attrs` reads the real process-wide +// `OTEL_RESOURCE_ATTRIBUTES` env var, and cargo runs tests in parallel +// threads by default — two separate tests each mutating that global +// raced each other (and, in this container, lost to the agent's own +// real ambient value). Sequencing both assertions in one test removes +// the race instead of papering over it with a mutex. +#[test] +fn otel_attrs_append_ambient_value_or_stand_alone() { + // SAFETY: test-only env mutation; sequenced within this one test so + // no other test's concurrent read/write of the same var can race it. + unsafe { + std::env::remove_var("OTEL_RESOURCE_ATTRIBUTES"); + } + assert_eq!(subagent_otel_attrs("batch-1"), "subagent=batch-1"); + + unsafe { + std::env::set_var("OTEL_RESOURCE_ATTRIBUTES", "agent=damocles"); + } + assert_eq!( + subagent_otel_attrs("batch-1"), + "agent=damocles,subagent=batch-1" + ); + unsafe { + std::env::remove_var("OTEL_RESOURCE_ATTRIBUTES"); + } +} + +#[test] +fn build_config_only_appends_system_prompt_when_given() { + let with = build_config("n", None, None, Some("/tmp/p.md"), None, None); + assert!( + with.extra_args + .contains(&"--append-system-prompt-file".to_owned()) + ); + assert!(with.extra_args.contains(&"/tmp/p.md".to_owned())); + + let without = build_config("n", None, None, None, None, None); + assert!( + !without + .extra_args + .contains(&"--append-system-prompt-file".to_owned()) + ); +} + +#[test] +fn a_role_with_an_unreadable_task_file_refuses_rather_than_dropping_either() { + let dir = std::env::temp_dir().join("hive-subagent-session-test-unreadable"); + let err = compose_prompt( + &dir, + "n", + Some("a role"), + "/tmp/no-such-task-file-here.md", + "go", + ) + .expect_err("an unreadable task file cannot silently become a role-only prompt"); + assert!(err.to_string().contains("task instructions"), "{err}"); +} + +/// `--tools` reaches the argv on every caller shape, carrying a non-empty +/// value. Non-empty matters separately from "the flag is there": what an +/// empty value grants is disputed and release-dependent, so we never ship +/// one and never depend on the answer. Checked for each shape because a +/// flag that appears on only some spawn paths is no restriction at all. +/// `signal_url` stays `None` throughout — it only steers `mcp_config`, +/// which `--tools` does not govern, and passing it would make this test +/// need the container's injected `HYPERHIVE_HARNESS_DIR`. +#[test] +fn build_config_always_passes_a_non_empty_tools_list() { + for config in [ + build_config("n", None, None, None, None, None), + build_config("n", None, None, Some("/tmp/p.md"), None, None), + build_config("n", None, None, None, Some("/tmp/wt"), None), + ] { + let tools = spawned_tools(&config); + assert!(!tools.is_empty(), "--tools must never be empty"); + assert!(tools.split(',').all(|t| !t.trim().is_empty())); + } +} + +/// A subagent's built-ins are a subset of `subagent_builtin_tools_for` — +/// the parent's own resolved set, plus `Bash` iff the parent holds +/// `Execution` (see that function's doc comment). This is the property +/// that makes shipping the daemon safe: a subagent reaching a tool +/// outside that resolution is a privilege escalation dressed as a +/// convenience. Read from `hive_sh4re::permissions`, deliberately: it is +/// the parent harness's own resolver, so this compares against what the +/// parent actually licenses rather than against a restatement of it that +/// could drift. +/// +/// ⚠️ **Scope: this catches a code divergence, not a read one.** Both +/// sides resolve off one permission set here; that the parent and this +/// daemon read the same key is a deployment property. +#[test] +fn a_subagent_gets_no_builtin_its_parent_lacks() { + let allowed = hive_sh4re::permissions::subagent_builtin_tools_for( + &crate::swarm_models::permissions_now(), + ); + let config = build_config("n", None, None, None, None, None); + for tool in spawned_tools(&config).split(',') { + assert!( + allowed.contains(&tool), + "subagent got {tool}, which the parent's resolved set does not license" + ); + } +} + +/// Named individually rather than inferred from "the list is short": the +/// tools this daemon used to hand a subagent that reach outside the run +/// it was started for. They are absent because the parent has never had +/// them — this pins the consequence, not a second allow-list. +/// +/// ⚠️ **A canary, not a guarantee.** The names are hardcoded, so this +/// only fails for a tool someone thought to list here; the *guarantee* +/// is the subset property above, which holds for tools nobody has +/// imagined yet. Do not read a pass as "no escaping tool is reachable" — +/// read it as "none of these ten came back". +#[test] +fn no_spawned_tool_escapes_the_session() { + let config = build_config("n", None, None, None, None, None); + let tools: Vec<&str> = spawned_tools(&config).split(',').collect(); + for escaping in [ + "SendMessage", + "ListAgents", + "Task", + "TaskStop", + "TaskOutput", + "CronCreate", + "CronDelete", + "RemoteTrigger", + "EnterWorktree", + "ExitWorktree", + ] { + assert!( + !tools.contains(&escaping), + "{escaping} must not be in a subagent's --tools" + ); + } +} + +#[test] +fn build_config_defaults_cwd_to_the_work_dir_when_no_dir_is_given() { + let with = build_config("n", None, None, None, Some("/tmp/some-worktree"), None); + assert_eq!(with.cwd, Some(PathBuf::from("/tmp/some-worktree"))); + + let root = std::env::temp_dir().join(format!( + "hive-subagent-mcp-test-work-dir-{}", + std::process::id() + )); + let state = root.join("state"); + let work = root.join("work"); + std::fs::create_dir_all(&state).unwrap(); + // SAFETY: test-only env mutation; the other `build_config` tests pass + // an explicit `dir` or read nothing derived from the state dir. + unsafe { + std::env::set_var("HYPERHIVE_STATE_DIR", &state); + } + + let absent = build_config("n", None, None, None, None, None); + std::fs::create_dir_all(&work).unwrap(); + let present = build_config("n", None, None, None, None, None); + + // SAFETY: see above. + unsafe { + std::env::remove_var("HYPERHIVE_STATE_DIR"); + } + let _ = std::fs::remove_dir_all(&root); + + assert_eq!( + absent.cwd, None, + "a work dir that isn't there yet must not become a spawn cwd" + ); + assert_eq!(present.cwd, Some(work)); +} + +#[test] +fn build_config_sets_effort_alongside_model() { + let config = build_config( + "n", + Some("opus".to_owned()), + Some("high".to_owned()), + None, + None, + None, + ); + assert_eq!(config.model, Some("opus".to_owned())); + assert_eq!(config.effort, Some("high".to_owned())); +} + +#[test] +fn build_config_defaults_effort_to_medium_when_omitted() { + // Unlike `model`, an omitted `effort` does not fall through to + // claude's own default (`high` on most models) — this daemon picks + // `medium` itself, a deliberate cost-conscious choice for subagent + // work. + let config = build_config("n", None, None, None, None, None); + assert_eq!(config.effort, Some("medium".to_owned())); +} + +// ---- turn continuation ------------------------------------------------- + +#[test] +fn an_unset_model_whitelist_allows_any_model() { + assert!(check_model(Some("opus"), &local(None)).is_ok()); +} + +#[test] +fn an_unset_model_whitelist_allows_an_omitted_model() { + assert!(check_model(None, &local(None)).is_ok()); +} + +#[test] +fn a_listed_model_is_allowed() { + assert!(check_model(Some("sonnet"), &local(Some("haiku,sonnet,opus"))).is_ok()); +} + +#[test] +fn an_unlisted_model_is_rejected_naming_what_is_permitted() { + let err = check_model(Some("opus"), &local(Some("haiku,sonnet"))) + .expect_err("a model outside the list must be refused") + .to_string(); + assert!( + err.contains("opus") && err.contains("haiku, sonnet"), + "the rejection is all the caller sees, so it must name the model \ + and the permitted ones: {err}" + ); +} + +#[test] +fn a_set_whitelist_still_allows_an_omitted_model() { + assert!( + check_model(None, &local(Some("haiku"))).is_ok(), + "omitting `model` lets claude pick its own default — it is not a \ + choice of model, so there is nothing to gate" + ); +} + +#[test] +fn whitespace_and_empty_entries_are_ignored() { + assert!(check_model(Some("sonnet"), &local(Some(" haiku , sonnet ,, "))).is_ok()); + assert!(check_model(Some("opus"), &local(Some(" haiku , sonnet ,, "))).is_err()); + assert!( + check_model(Some("opus"), &local(Some(" ,, "))).is_ok(), + "a var naming nothing restricts nothing — default open" + ); +} + +#[test] +fn the_cap_is_the_swarm_value_and_none_otherwise() { + assert_eq!(subagent_cap(Some(&capped(3)), "a"), Some(3)); + assert_eq!(subagent_cap(Some(&unset()), "a"), None); + assert_eq!(subagent_cap(None, "a"), None); + let failed = crate::swarm_models::Read::Failed("no answer".to_owned()); + assert_eq!(subagent_cap(Some(&failed), "a"), None); +} + +#[test] +fn a_failed_cap_read_warns_naming_the_agent_and_the_error() { + let logs = CapturedLogs::default(); + let subscriber = tracing_subscriber::fmt() + .with_writer(logs.clone()) + .with_ansi(false) + .finish(); + let failed = crate::swarm_models::Read::Failed("no answer".to_owned()); + let cap = tracing::subscriber::with_default(subscriber, || subagent_cap(Some(&failed), "iris")); + assert_eq!(cap, None); + let logged = logs.text(); + assert!( + logged.contains("WARN") && logged.contains("iris") && logged.contains("no answer"), + "{logged}" + ); +} + +/// The swarm's list replaces the local one, so it can widen it as well +/// as narrow it. +#[test] +fn a_swarm_list_replaces_the_local_one() { + let env = || Some("haiku,sonnet".to_owned()); + let list = model_list(Some(swarm(&["opus"])), env()); + assert_eq!(list, ModelList::Swarm(vec!["opus".to_owned()])); + assert!(check_model(Some("opus"), &list).is_ok()); + assert!(check_model(Some("sonnet"), &list).is_err()); +} + +#[test] +fn without_a_swarm_list_the_local_one_applies() { + let env = || Some("haiku,sonnet".to_owned()); + for read in [None, Some(unset())] { + assert_eq!(model_list(read, env()), local(Some("haiku,sonnet"))); + } + assert_eq!(model_list(Some(unset()), None), local(None)); +} + +#[test] +fn a_failed_read_falls_back_to_the_local_list_and_warns() { + let logs = CapturedLogs::default(); + let subscriber = tracing_subscriber::fmt() + .with_writer(logs.clone()) + .with_ansi(false) + .finish(); + let list = tracing::subscriber::with_default(subscriber, || { + model_list( + Some(crate::swarm_models::Read::Failed("no answer".to_owned())), + Some("haiku".to_owned()), + ) + }); + assert_eq!(list, local(Some("haiku"))); + let logged = logs.text(); + assert!( + logged.contains("WARN") && logged.contains("no answer"), + "the fallback is logged as a warning with the cause: {logged}" + ); +} + +#[test] +fn a_model_outside_the_swarm_list_is_refused_naming_the_list_and_its_source() { + let list = model_list(Some(swarm(&["haiku", "sonnet"])), Some("opus".to_owned())); + let err = check_model(Some("opus"), &list) + .expect_err("a model outside the swarm's list must be refused") + .to_string(); + assert!( + err.contains("opus") + && err.contains("haiku, sonnet") + && err.contains("swarm's subagent_models"), + "{err}" + ); + assert!( + check_model(None, &list).is_ok(), + "an omitted model is not checked against the swarm's list either" + ); +} diff --git a/hive-subagent-mcp/src/session/tests/goal.rs b/hive-subagent-mcp/src/session/tests/goal.rs new file mode 100644 index 000000000..c2653785e --- /dev/null +++ b/hive-subagent-mcp/src/session/tests/goal.rs @@ -0,0 +1,670 @@ +//! Goal runs: briefings, continuation, stop reasons and the report file. + +use super::*; + +#[test] +fn without_a_role_the_task_still_moves_out_of_the_system_prompt() { + // The principle the role fix was made on is general: a task baked + // into the system prompt re-asserts itself on every later turn, not + // just the one it was written for, whether or not the session has a + // role. So the no-role path folds the task into the trigger too — + // it must be ABSENT from whatever reaches + // `--append-system-prompt-file` and PRESENT in the trigger, the + // same shape the role-path tests below pin for the role case. + let task = scratch_file("no-role-task", "rebase the branch and report"); + let (path, trigger) = system_prompt_and_trigger("n", None, &task.to_string_lossy(), "go") + .expect("a readable task file composes even with no role"); + assert_eq!( + path, None, + "no role means no system-prompt file at all — there is no role \ + text to put in one, and the task must not go in one either" + ); + assert!( + trigger.contains("rebase the branch"), + "the task must reach the subagent as the turn's own prompt: {trigger:?}" + ); + + let system_prompt = path.map(|p| p.to_string_lossy().into_owned()); + let config = build_config("n", None, None, system_prompt.as_deref(), None, None); + assert!( + !config + .extra_args + .contains(&"--append-system-prompt-file".to_owned()), + "the task must not reach claude as a standing system prompt: {:?}", + config.extra_args + ); +} + +#[test] +fn a_role_s_system_prompt_file_holds_the_role_and_never_the_task() { + // A task rendered into the system prompt re-asserts itself as an + // instruction on every later turn of the session, not just the one + // it was written for — the system prompt is the subagent's + // standing identity, not a one-shot channel. Asserting the role is + // present is not enough to catch that regression; a merged file + // would pass that check too. The task's absence from this file is + // the assertion that actually pins the bug. + let task = scratch_file("role-only-task", "rebase the branch and report"); + let dir = std::env::temp_dir().join("hive-subagent-session-test-role-only"); + let (path, _trigger) = compose_prompt( + &dir, + "role-only-run", + Some("you are a reviewer; block on anything unsafe"), + &task.to_string_lossy(), + "go", + ) + .expect("a role and a readable task file compose"); + let path = path.expect("a role always renders a system-prompt file"); + let body = std::fs::read_to_string(&path).expect("the system-prompt file is readable"); + assert!( + body.contains("you are a reviewer"), + "the role must reach the system prompt: {body:?}" + ); + assert!( + !body.contains("rebase the branch"), + "the task must NOT reach the system-prompt file: {body:?}" + ); +} + +#[test] +fn a_role_still_delivers_the_task_as_the_turns_own_prompt() { + // The other half of the same fix: dropping the task from the + // system prompt must not drop it altogether — it goes back to + // being the turn's prompt, the same channel it reached the + // subagent by before roles existed. + let task = scratch_file("turn-prompt-task", "rebase the branch and report"); + let dir = std::env::temp_dir().join("hive-subagent-session-test-turn-prompt"); + let (_path, trigger) = compose_prompt( + &dir, + "turn-prompt-run", + Some("you are a reviewer"), + &task.to_string_lossy(), + "Carry out the task described in your instructions.", + ) + .expect("a role and a readable task file compose"); + assert!( + trigger.contains("rebase the branch"), + "the task must reach the subagent as the turn's own prompt: {trigger:?}" + ); +} + +/// What the swarm is told when a run ends: success is 0, a signal is no +/// code at all, and any other failure is 1. +#[test] +fn a_runs_end_reports_its_exit_status_to_the_swarm() { + assert_eq!(exit_status(&TurnEnd::Complete), Some(0)); + assert_eq!(exit_status(&TurnEnd::Killed { signal: 9 }), None); + assert_eq!(exit_status(&TurnEnd::Failed("boom".to_owned())), Some(1)); +} + +#[test] +fn an_event_starts_the_liveness_clock_and_the_turn_ending_stops_it() { + let state = State::new(PathBuf::from("/dev/null"), signal_url()); + assert_eq!( + state.last_event_age("n"), + None, + "a name that never spawned has no clock to read" + ); + state.note_event("n"); + assert!( + state.last_event_age("n").is_some(), + "the first event must give `status` an age to report" + ); + state.finish_turn("n", &TurnEnd::Complete); + assert_eq!( + state.last_event_age("n"), + None, + "the age describes a turn in flight — a finished turn's leftover age would read as a \ + stall that never happened" + ); +} + +#[test] +fn every_sink_callback_counts_as_liveness() { + // All three, deliberately: a stderr line or a non-JSON stdout line is + // proof the child is alive exactly as much as a stream-json event, + // and reporting a live subagent as wedged is the failure that costs. + use hive_claude::Sink as _; + + fn fresh() -> (Arc, LivenessSink) { + let state = Arc::new(State::new(PathBuf::from("/dev/null"), signal_url())); + let sink = LivenessSink { + state: Arc::clone(&state), + name: "n".to_owned(), + info: Arc::default(), + verdict: None, + }; + (state, sink) + } + + let (state, sink) = fresh(); + sink.on_event(&serde_json::json!({"type": "system"})); + assert!( + state.last_event_age("n").is_some(), + "a stream-json event is liveness" + ); + + let (state, sink) = fresh(); + sink.on_stdout_line("not json"); + assert!( + state.last_event_age("n").is_some(), + "so is a stdout line that didn't parse as JSON" + ); + + let (state, sink) = fresh(); + sink.on_stderr_line("some chatter"); + assert!( + state.last_event_age("n").is_some(), + "so is a stderr line — anything the child says at all counts" + ); +} + +#[test] +fn searched_location_names_the_same_place_the_store_would_look() { + // The point of reading both halves off the `Config` rather than + // re-deriving them: the location reported must be the one actually + // searched, so it can't drift from `build_store`/the driver. + let cwd = std::env::current_dir().expect("a cwd"); + let config = build_config("n", None, None, None, Some(&cwd.to_string_lossy()), None); + let Some(located) = searched_location(&config) else { + // No `HOME` in this environment — nothing to compare against. + return; + }; + let home = config.resolved_claude_home().expect("home resolved"); + let resolved_cwd = config.resolved_cwd().expect("cwd resolved"); + assert!( + located.contains(&home.display().to_string()) + && located.contains(&resolved_cwd.display().to_string()), + "both halves must come from the config's own resolution: {located}" + ); +} + +#[tokio::test(start_paused = true)] +async fn a_turn_that_neither_speaks_nor_exits_is_reported_as_started() { + // The bound is a floor under a child that does nothing at all. The + // sender is held open for the whole wait, so only the timeout can + // end it. + let (tx, rx) = oneshot::channel::(); + let started = tokio::time::Instant::now(); + await_resume(rx) + .await + .expect("a silent child is not a failed resume"); + assert!( + started.elapsed() >= RESUME_GRACE, + "the wait must actually run to the bound: {:?}", + started.elapsed() + ); + drop(tx); +} + +#[test] +fn only_the_first_verdict_is_reported_and_only_to_a_live_caller() { + // `settle`'s two jobs: the sink and the background task race for one + // sender, and the winner's `true` is what tells the task the caller + // has already been handed the failure. + let (tx, rx) = oneshot::channel(); + let verdict: VerdictTx = Arc::new(Mutex::new(Some(tx))); + assert!( + settle(Some(&verdict), ResumeVerdict::Underway), + "the first report reaches a listening caller" + ); + assert!( + !settle(Some(&verdict), ResumeVerdict::Ended(missed_resume())), + "the loser of the race has nothing left to send on — and so must still push its todo" + ); + drop(rx); + + let (tx, rx) = oneshot::channel(); + let verdict: VerdictTx = Arc::new(Mutex::new(Some(tx))); + drop(rx); + assert!( + !settle(Some(&verdict), ResumeVerdict::Ended(missed_resume())), + "a caller whose grace already expired is not listening, so its todo must still be \ + pushed" + ); + + assert!( + !settle(None, ResumeVerdict::Underway), + "a `start` has no verdict channel and nobody waiting on one" + ); +} + +#[test] +fn a_terminal_result_event_is_liveness_but_not_proof_the_turn_began() { + // Measured, and the reason the underway signal reads the event's + // kind at all: a resume that matched nothing still emits a + // stream-json `result` event (and stderr chatter) before exiting, so + // treating any callback as "underway" would report every missed + // resume as a successful start. + use hive_claude::Sink as _; + + fn fresh() -> (oneshot::Receiver, LivenessSink) { + let (tx, rx) = oneshot::channel(); + let sink = LivenessSink { + state: Arc::new(State::new(PathBuf::from("/dev/null"), signal_url())), + name: "n".to_owned(), + info: Arc::default(), + verdict: Some(Arc::new(Mutex::new(Some(tx)))), + }; + (rx, sink) + } + + let (mut rx, sink) = fresh(); + sink.on_event(&serde_json::json!({"type": "result", "is_error": true})); + assert!( + rx.try_recv().is_err(), + "the turn's own end-of-turn marker must not settle the wait as underway" + ); + assert!( + sink.state.last_event_age("n").is_some(), + "it is still liveness — the child did say something" + ); + + let (mut rx, sink) = fresh(); + sink.on_stderr_line("Error: --resume requires a valid session ID or session title"); + assert!( + rx.try_recv().is_err(), + "nor does stderr, which a missed resume writes to before it exits" + ); + + let (mut rx, sink) = fresh(); + sink.on_event(&serde_json::json!({"type": "system", "subtype": "init"})); + assert!( + matches!(rx.try_recv(), Ok(ResumeVerdict::Underway)), + "a non-terminal event is a turn in progress, which is the signal continue waits for" + ); +} + +#[test] +fn a_session_with_no_goal_stops_after_one_turn() { + // The pre-continuation shape, and the reason `goal` is what switches + // the loop on rather than a separate flag: nothing to continue + // toward is the same fact as nothing to continue. + let state = mid_run("n", "unused", 5); + state.set_goal("n", None, 5); + assert!( + matches!( + state.plan_after_turn("n"), + Continuation::Stop(StopReason::Done) + ), + "without a goal the first completed turn ends the run" + ); + assert_eq!( + state.turns("n"), + None, + "and there is no turn budget to report being partway through" + ); +} + +#[test] +fn a_goal_keeps_spending_turns_until_the_cap_and_then_stops() { + let state = mid_run("n", "make the gate pass", 3); + assert_eq!(state.turns("n"), Some((1, 3)), "the first turn is 1 of 3"); + + for expected in [2, 3] { + let Continuation::Continue { prompt } = state.plan_after_turn("n") else { + panic!("turn {expected} of 3 must still be spent"); + }; + assert!( + prompt.contains("make the gate pass"), + "the re-prompt continues toward the goal verbatim: {prompt}" + ); + assert!( + prompt.contains("have not reported the goal reached"), + "and says the one thing the subagent can't observe for itself: {prompt}" + ); + assert_eq!(state.turns("n"), Some((expected, 3))); + } + + assert_eq!( + state.plan_after_turn("n"), + Continuation::Stop(StopReason::TurnCap { turns: 3 }), + "the cap is the number of turns run, not one more" + ); + assert_eq!( + state.turns("n"), + Some((3, 3)), + "a capped run must not advance past its own cap" + ); +} + +#[test] +fn both_signals_stop_the_continuation_before_the_cap_is_reached() { + // The issue's own words: "both stop goal continues". Turn one of + // five, so only the signal can be what stopped it. + for stop in [ + StopReason::GoalReached(Some("wrote the fix".to_owned())), + StopReason::NeedHelp("no credential for the registry".to_owned()), + ] { + let state = mid_run("n", "a goal", 5); + state.record_stop("n", stop.clone()); + assert_eq!( + state.plan_after_turn("n"), + Continuation::Stop(stop.clone()), + "{stop:?} must end the run with turns still on the clock" + ); + assert_eq!( + state.turns("n"), + Some((1, 5)), + "and must not have spent one on the way out" + ); + } +} + +#[test] +fn a_cancelled_run_stops_with_turns_still_on_its_clock() { + // The loop half of the same fact, asserted directly: `Cancelled` is + // read where the other stop signals are, ahead of the goal, so it + // stops a run that has four turns left rather than being overridden + // by them. + let state = mid_run("n", "a goal", 5); + state.record_stop("n", StopReason::Cancelled); + assert_eq!( + state.plan_after_turn("n"), + Continuation::Stop(StopReason::Cancelled) + ); + assert_eq!( + state.turns("n"), + Some((1, 5)), + "and must not spend one on the way out" + ); +} + +#[test] +fn a_signal_on_the_last_allowed_turn_outranks_the_cap() { + // Both are true at once, and which one is reported is the difference + // between "it says it finished" and "it ran out of road". + let state = mid_run("n", "a goal", 1); + state.record_stop("n", StopReason::GoalReached(None)); + assert_eq!( + state.plan_after_turn("n"), + Continuation::Stop(StopReason::GoalReached(None)) + ); +} + +#[test] +fn a_subagent_cannot_signal_a_different_session() { + // The requirement itself, and the reason it's a test: two siblings + // running concurrently, each holding exactly one signal URL. Half the + // answer is in `mcp.rs` — neither tool has a `name` argument to put a + // sibling's name in (`the_signal_tools_take_no_session_name` pins + // that). The other half is here: whether the only identity a subagent + // *does* hold, its token, can be made to resolve to anyone else. + let state = State::new(PathBuf::from("/dev/null"), signal_url()); + state.reserve("alpha"); + state.reserve("beta"); + let alpha = token_of(&state.mint_signal_url("alpha")); + let beta = token_of(&state.mint_signal_url("beta")); + assert_ne!(alpha, beta, "two sessions must not share a token"); + + assert_eq!( + state.session_for_signal_token(&alpha).as_deref(), + Some("alpha") + ); + assert_eq!( + state.session_for_signal_token(&beta).as_deref(), + Some("beta") + ); + + // `alpha` signals the only way it can: on its own endpoint, with the + // session resolved from the token rather than supplied by the caller. + let resolved = state + .session_for_signal_token(&alpha) + .expect("alpha's own route resolves"); + need_help(&state, &resolved, "no credential".to_owned(), None); + assert_eq!( + state.stop_reason("alpha"), + Some(StopReason::NeedHelp("no credential".to_owned())) + ); + assert_eq!( + state.stop_reason("beta"), + None, + "a sibling's run must be untouched — there is no route `alpha` holds that reaches it" + ); + + // A subagent does know its siblings' *names* (a brief can mention + // them) — and a name is not a token, which is the whole point. + assert_eq!(state.session_for_signal_token("beta"), None); + assert_eq!(state.session_for_signal_token(&format!("{alpha}0")), None); +} + +#[test] +fn a_stop_reason_extends_the_done_message_rather_than_replacing_it() { + // "Extend", not "replace": the observed end of the turn and the + // reason the run stopped are different facts, and dropping the first + // would let a self-reported claim stand where an observation was. + let plain = turn_end_summary("n", &TurnEnd::Complete, None); + for stop in [ + StopReason::GoalReached(None), + StopReason::NeedHelp("blocked".to_owned()), + StopReason::TurnCap { turns: 5 }, + StopReason::Cancelled, + ] { + let extended = turn_end_summary("n", &TurnEnd::Complete, Some(&stop)); + assert!( + extended.starts_with(&plain), + "{stop:?} must extend the done message, not rewrite it: {extended}" + ); + assert!( + extended.len() > plain.len(), + "{stop:?} must actually add something: {extended}" + ); + } + assert_eq!( + turn_end_summary("n", &TurnEnd::Complete, Some(&StopReason::Done)), + plain, + "`Done` has nothing to add — the unextended message already says exactly that" + ); +} + +#[test] +fn the_turn_cap_todo_says_the_harness_limit_was_what_stopped_it() { + // Not a silent stop: the one notification a parent gets unprompted + // has to distinguish "it finished" from "we stopped asking". + let todo = turn_end_summary( + "n", + &TurnEnd::Complete, + Some(&StopReason::TurnCap { turns: 5 }), + ); + assert!( + todo.contains("harness turn limit was reached (5 turns)"), + "the todo must name the limit as the cause: {todo}" + ); + assert!( + todo.contains("without the goal ever being reported reached"), + "and say what that means for the work: {todo}" + ); +} + +#[test] +fn a_continue_gives_a_capped_session_its_allowance_back() { + // `TurnCap` stops the loop, it doesn't retire the session — and the + // parent spending a turn on purpose is not what the cap bounds. + let state = mid_run("n", "a goal", 2); + state.record_stop("n", StopReason::TurnCap { turns: 2 }); + state.clear_stop("n"); + state.restart_turns("n"); + assert_eq!(state.turns("n"), Some((1, 2))); + assert_eq!(state.stop_reason("n"), None); + assert!( + matches!(state.plan_after_turn("n"), Continuation::Continue { .. }), + "with the allowance back, the loop has a turn to spend again" + ); +} + +#[tokio::test] +async fn a_fresh_start_inherits_nothing_from_the_run_before_it() { + // `start` archives the prior session precisely so this is a fresh + // start; a leftover stop reason or report path would make the new run + // report the old one's ending, into the old one's file. + let state = Arc::new(State::new(PathBuf::from("/dev/null"), signal_url())); + state.record_stop("n", StopReason::NeedHelp("old block".to_owned())); + state.set_report_file("n", Some("/tmp/old-report.md")); + state.reserve("n"); + let refused = start(&state, start_request("n")).await; + assert!(refused.is_err(), "the reserved name is refused as before"); + + // The same clearing `start` does once it owns the name. + state.clear_stop("n"); + state.clear_report_file("n"); + assert_eq!(state.stop_reason("n"), None); + assert_eq!(state.report_file("n"), None); +} + +#[test] +fn the_report_path_is_taken_from_the_session_and_never_guessed() { + // Both halves of where it can come from: the brief `start` carried, + // and the subagent saying where it actually wrote. A signal that + // names no path leaves the remembered one alone rather than erasing + // it. + let state = State::new(PathBuf::from("/dev/null"), signal_url()); + assert_eq!( + state.report_file("n"), + None, + "a session nobody told about a report file has none — nothing is inferred" + ); + state.set_report_file("n", Some("/tmp/brief-said.md")); + goal_reached(&state, "n", None, None); + assert_eq!( + state.report_file("n"), + Some(PathBuf::from("/tmp/brief-said.md")), + "a signal with no path must not erase what the brief named" + ); + goal_reached(&state, "n", None, Some("/tmp/actually-wrote.md")); + assert_eq!( + state.report_file("n"), + Some(PathBuf::from("/tmp/actually-wrote.md")), + "and the subagent saying where it wrote is what wins" + ); +} + +#[tokio::test] +async fn the_stop_reason_is_appended_to_the_report_file_the_session_named() { + let dir = std::env::temp_dir().join(format!("hive-subagent-report-{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("scratch dir"); + let path = dir.join("report.md"); + std::fs::write(&path, "# what the subagent wrote\n").expect("seed the report"); + + write_stop_to_report(Some(path.clone()), "n", &StopReason::TurnCap { turns: 5 }).await; + + let body = std::fs::read_to_string(&path).expect("report still readable"); + assert!( + body.starts_with("# what the subagent wrote\n"), + "appended, never rewritten — the subagent wrote that file: {body}" + ); + assert!( + body.contains("harness turn limit was reached (5 turns)"), + "and the stop reason lands in the artifact a parent already reads: {body}" + ); + std::fs::remove_dir_all(&dir).ok(); +} + +#[tokio::test] +async fn an_unwritable_report_path_costs_the_line_and_nothing_else() { + // Best-effort by design: the same sentence is in the todo, so a path + // this daemon can't write is a missing convenience, not a lost fact. + write_stop_to_report( + Some(PathBuf::from("/proc/definitely/not/writable/report.md")), + "n", + &StopReason::Done, + ) + .await; + write_stop_to_report(None, "n", &StopReason::Done).await; +} + +#[test] +fn a_goal_briefing_tells_the_subagent_what_it_cannot_otherwise_know() { + let briefing = goal_briefing("batch-1", "get the gate to pass", 5); + assert!( + briefing.contains("get the gate to pass") && briefing.contains("up to 5 turns"), + "the goal and the budget both have to reach the subagent: {briefing}" + ); + assert!( + briefing.contains("goal_reached") && briefing.contains("need_help"), + "as do the two ways it has to stop the re-prompting: {briefing}" + ); + assert!( + briefing.contains("batch-1"), + "and its own name, which is what those tools are called with: {briefing}" + ); +} + +#[test] +fn a_signal_url_reaches_the_subagent_and_a_status_check_renders_no_config() { + // `turn` actually writes an --mcp-config file (crate::mcp_config::build), + // which resolves `hive_agent_sock::paths::harness_dir` — normally the + // container's injected `HYPERHIVE_HARNESS_DIR`, unset in a plain `cargo + // test` sandbox. Point it at a scratch dir for just this test rather + // than depending on ambient environment; only this test's call path + // reads the var, so there's no cross-test race to sequence around + // (contrast `otel_attrs_append_ambient_value_or_stand_alone` above). + let dir = std::env::temp_dir().join(format!( + "hive-subagent-mcp-test-harness-dir-{}", + std::process::id() + )); + // SAFETY: test-only env mutation; no other test reads this var. + unsafe { + std::env::set_var("HYPERHIVE_HARNESS_DIR", &dir); + } + + // The signal surface is how `goal_reached` is callable at all, so a + // spawned turn's config has to carry it; `status` builds a config + // purely to resolve the store and has no subagent to hand it to. + let turn = build_config("n", None, None, None, None, Some(&signal_url())); + let checked = build_config("n", None, None, None, None, None); + + // SAFETY: see above. + unsafe { + std::env::remove_var("HYPERHIVE_HARNESS_DIR"); + } + let _ = std::fs::remove_dir_all(&dir); + + assert!( + turn.mcp_config.is_some(), + "a turn's config must carry an --mcp-config with the signal surface in it" + ); + assert!( + turn.strict_mcp_config && checked.strict_mcp_config, + "the safety property is unchanged: no ambient MCP discovery either way" + ); +} + +#[test] +fn a_refused_continue_leaves_the_sessions_records_as_they_were() { + // A capped goal session on its last turn, stopped on a signal, with a + // remembered `dir`; the `continue` names a dir holding no session. + let root = scratch_dir("refused-keeps-records"); + let state = Arc::new(State::new(PathBuf::from("/dev/null"), signal_url())); + state.set_goal("n", Some("g".into()), 3); + state.plan_after_turn("n"); + state.plan_after_turn("n"); + state.record_stop("n", StopReason::NeedHelp("blocked on X".into())); + state.resolve_dir("n", Some("/remembered")); + assert_eq!(state.turns("n"), Some((3, 3))); + + assert!(state.reserve("n")); + let (tx, _rx) = oneshot::channel(); + let verdict: VerdictTx = Arc::new(Mutex::new(Some(tx))); + continue_on_runtime( + &state, + "n", + claude_config(&root), + root.to_str(), + "again".into(), + &verdict, + ) + .expect_err("no session under the scratch dir"); + + assert_eq!( + state.stop_reason("n"), + Some(StopReason::NeedHelp("blocked on X".into())), + "`status` still says why the session stopped" + ); + assert_eq!(state.turns("n"), Some((3, 3)), "the budget is not reset"); + assert_eq!( + state.peek_dir("n", None), + Some("/remembered".to_owned()), + "the refused call's dir is not remembered" + ); + std::fs::remove_dir_all(&root).ok(); +} diff --git a/hive-subagent-mcp/src/session/tests/run.rs b/hive-subagent-mcp/src/session/tests/run.rs new file mode 100644 index 000000000..acf9ebc43 --- /dev/null +++ b/hive-subagent-mcp/src/session/tests/run.rs @@ -0,0 +1,197 @@ +//! Starting and continuing a run on either runtime. + +use super::*; + +#[test] +fn a_subagent_run_is_killed_after_a_bash_task_and_before_the_session() { + assert_eq!(RUN_OOM_SCORE_ADJ, 900); + const { assert!(RUN_OOM_SCORE_ADJ < run_cgroup::BASH_TASK_OOM_SCORE_ADJ) }; +} + +// `Cancel` can only be constructed from a real spawned process (no test +// fixture in `hive_claude` for it), so these exercise the reservation +// half of `State` directly — the actual TOCTOU-closure logic — rather +// than the full start/spawn path. + +#[test] +fn classify_end_separates_a_signalled_child_from_a_clean_one() { + assert_eq!(classify_end(Ok(()), None), TurnEnd::Complete); + assert_eq!( + classify_end(Err(signalled_exit(libc::SIGKILL)), None), + TurnEnd::Killed { signal: 9 }, + "a SIGKILLed child must not read as a turn that ended on its own" + ); + assert_eq!( + classify_end(Err(signalled_exit(libc::SIGTERM)), None), + TurnEnd::Killed { signal: 15 } + ); + assert!( + matches!( + classify_end(Err(hive_claude::Error::PromptTooLong), None), + TurnEnd::Failed(_) + ), + "claude exiting on its own is a failure, not a kill" + ); +} + +#[test] +fn the_killed_todo_does_not_read_like_a_completion() { + let complete = turn_end_summary("n", &TurnEnd::Complete, None); + let killed = turn_end_summary("n", &TurnEnd::Killed { signal: 9 }, None); + assert_eq!( + complete, "subagent `n` finished: turn complete", + "the ordinary completion todo is unchanged" + ); + assert!( + killed.contains("KILLED mid-turn") && killed.contains("SIGKILL (signal 9)"), + "the killed todo must state the kill and the signal: {killed}" + ); + assert!( + !killed.contains("finished"), + "the one notification pushed without being asked must not read as a finished turn: \ + {killed}" + ); + assert_ne!(complete, killed); +} + +#[test] +fn continue_tells_the_caller_it_is_resuming_a_killed_session() { + let plain = note_resumed_after_kill("subagent `n` started", None); + assert_eq!( + plain, "subagent `n` started", + "an ordinary resume is unchanged" + ); + let after_kill = note_resumed_after_kill("subagent `n` started", Some(libc::SIGKILL)); + assert!( + after_kill.contains("killed") && after_kill.contains("SIGKILL (signal 9)"), + "resuming a killed session is allowed, but the caller has to be told: {after_kill}" + ); +} + +#[test] +fn a_missed_resume_names_the_directory_that_was_searched() { + // The failure that cost an afternoon: the session existed, just not + // where this daemon looked. claude's own message names the value it + // failed to match but never the directory, which is the fact that + // was missing. + let searched = "(searched /home/agent/.claude for cwd /home/agent/work; if it was started \ + elsewhere, pass the `dir` it was started in)"; + let end = classify_end(Err(hive_claude::Error::SessionNotFound), Some(searched)); + let TurnEnd::Failed(msg) = end else { + panic!("a missed resume is a failed turn"); + }; + assert!( + msg.contains("no session matched"), + "claude's own diagnosis must survive: {msg}" + ); + assert!( + msg.contains("/home/agent/.claude") && msg.contains("/home/agent/work"), + "and the search location must be appended to it: {msg}" + ); + assert!( + msg.contains("pass the `dir` it was started in"), + "naming the directory is only half of it — say what to do about it: {msg}" + ); +} + +#[test] +fn only_a_missed_resume_gets_the_search_location() { + // A `start` never passes one (nothing to resume), and an unrelated + // failure must not be decorated with a location that had no part in + // it. + let no_hint = classify_end(Err(hive_claude::Error::SessionNotFound), None); + assert_eq!( + no_hint, + TurnEnd::Failed("claude error: no session matched the requested id or title".to_owned()), + "with no resolvable location the underlying error still reaches the caller, plain" + ); + + let unrelated = classify_end(Err(hive_claude::Error::PromptTooLong), Some("(searched …)")); + let TurnEnd::Failed(msg) = unrelated else { + panic!("an overflowed context is a failed turn"); + }; + assert!( + !msg.contains("searched"), + "a context overflow has nothing to do with where the session lives: {msg}" + ); +} + +#[tokio::test] +async fn a_continue_whose_resume_missed_is_an_error_not_a_started_message() { + // The whole point of the bounded wait: a `continue` naming a session + // that isn't there must fail the tool call, not answer "started" and + // leave the real answer to a todo nobody is waiting on any more. + let (tx, rx) = oneshot::channel(); + tx.send(ResumeVerdict::Ended(missed_resume())) + .map_err(|_| ()) + .expect("the waiter is still listening"); + let err = await_resume(rx) + .await + .expect_err("a missed resume must reach the caller as an error"); + let msg = err.to_string(); + assert!( + msg.contains("no session matched"), + "claude's own diagnosis is the error: {msg}" + ); + assert!( + msg.contains("pass the `dir` it was started in"), + "and the searched location travels with it: {msg}" + ); +} + +#[tokio::test(start_paused = true)] +async fn a_turn_that_got_underway_answers_without_waiting_out_the_grace() { + // A successful `continue` must not pay a fixed delay — it returns on + // the first sign of the turn, not on the bound. Paused time makes + // that measurable: the clock only advances if something awaits it. + let (tx, rx) = oneshot::channel(); + tx.send(ResumeVerdict::Underway) + .map_err(|_| ()) + .expect("the waiter is still listening"); + let started = tokio::time::Instant::now(); + await_resume(rx) + .await + .expect("an underway turn is not an error"); + assert!( + started.elapsed() < RESUME_GRACE, + "a turn that spoke must settle the wait immediately, not on the bound: {:?}", + started.elapsed() + ); +} + +#[test] +fn the_default_cap_is_five_turns() { + // The number is the feature's own, not a value tuned here — pinned so + // a later edit to `DEFAULT_MAX_TURNS` has to be deliberate. + assert_eq!(DEFAULT_MAX_TURNS, 5); +} + +#[test] +fn an_acp_subagent_gets_the_tools_a_claude_subagent_would() { + let ask = |kind| PermissionAsk { + kind, + mcp_server: None, + }; + let none: &[Permission] = &[]; + let both = &[Permission::WebTools, Permission::Execution]; + for kind in ["read", "edit", "search"] { + assert!(acp_permits(&ask(kind), none), "{kind}"); + } + for kind in ["fetch", "execute"] { + assert!(!acp_permits(&ask(kind), none), "{kind} needs its group"); + assert!(acp_permits(&ask(kind), both), "{kind} with its group"); + } + assert!( + !acp_permits(&ask("delete"), both), + "an unnamed kind is refused" + ); + assert!( + !acp_permits(&ask("other"), both), + "other outside the MCP servers" + ); + let mcp = PermissionAsk { + kind: "other", + mcp_server: Some("subagent_control"), + }; + assert!(acp_permits(&mcp, none)); +} diff --git a/hive-subagent-mcp/src/session/tests/state.rs b/hive-subagent-mcp/src/session/tests/state.rs new file mode 100644 index 000000000..c850f9cac --- /dev/null +++ b/hive-subagent-mcp/src/session/tests/state.rs @@ -0,0 +1,612 @@ +//! The reservation, claim and signal-token half of `State`. + +use super::*; + +#[test] +fn reserve_is_exclusive_for_the_same_name() { + let state = State::new(PathBuf::from("/dev/null"), signal_url()); + assert!(state.reserve("dup"), "first reservation should succeed"); + assert!( + !state.reserve("dup"), + "a second reservation for the same name must be refused — this is the exact race \ + argus found: two calls both passing a check before either commits" + ); +} + +#[test] +fn reserve_does_not_cross_block_different_names() { + let state = State::new(PathBuf::from("/dev/null"), signal_url()); + assert!(state.reserve("a")); + assert!( + state.reserve("b"), + "unrelated names must not block each other" + ); +} + +#[test] +fn release_reservation_frees_the_name_for_reuse() { + let state = State::new(PathBuf::from("/dev/null"), signal_url()); + assert!(state.reserve("n")); + state.release_reservation("n"); + assert!( + state.reserve("n"), + "releasing a still-`None` reservation must free the name again" + ); +} + +#[test] +fn occupancy_reflects_the_reserved_but_not_running_state() { + let state = State::new(PathBuf::from("/dev/null"), signal_url()); + assert_eq!(state.occupancy("never-reserved"), None); + state.reserve("n"); + assert_eq!( + state.occupancy("n"), + Some(Occupancy::Starting), + "reserved-but-not-yet-spawned must read as occupied-but-not-running" + ); +} + +#[tokio::test] +async fn a_start_naming_an_unknown_role_errors_and_reserves_nothing() { + // The error path end to end: the refusal happens before anything is + // claimed, so an unknown role costs a message and nothing else — + // no reservation to release, no archived prior session, no spawn. + let state = Arc::new(State::new(PathBuf::from("/dev/null"), signal_url())); + let mut req = start_request("unknown-role-run"); + req.role = Some("no-such-role-ships-anywhere".to_owned()); + let err = start(&state, req) + .await + .expect_err("a role this agent lacks must refuse the start"); + assert!( + err.to_string().contains("no-such-role-ships-anywhere"), + "the refusal names the role that was asked for: {err}" + ); + assert_eq!( + state.occupancy("unknown-role-run"), + None, + "a refused start leaves the name free" + ); +} + +#[tokio::test] +async fn a_start_naming_an_unusable_role_refuses_before_touching_the_filesystem() { + let state = Arc::new(State::new(PathBuf::from("/dev/null"), signal_url())); + let mut req = start_request("bad-role-name"); + req.role = Some("../../etc/passwd".to_owned()); + let err = start(&state, req) + .await + .expect_err("a role name that is not an identifier refuses"); + assert!(err.to_string().contains("invalid role name"), "{err}"); + assert_eq!(state.occupancy("bad-role-name"), None); +} + +#[test] +fn resolve_dir_remembers_an_explicit_dir_and_falls_back_to_it_when_omitted() { + let state = State::new(PathBuf::from("/dev/null"), signal_url()); + assert_eq!( + state.resolve_dir("n", None), + None, + "nothing remembered yet — omitted dir has nothing to fall back to" + ); + assert_eq!( + state.resolve_dir("n", Some("/tmp/worktree")), + Some("/tmp/worktree".to_owned()), + "an explicit dir is returned as-is" + ); + assert_eq!( + state.resolve_dir("n", None), + Some("/tmp/worktree".to_owned()), + "a later omitted dir falls back to what was just remembered" + ); + assert_eq!( + state.resolve_dir("n", Some("/tmp/other")), + Some("/tmp/other".to_owned()), + "a later explicit dir overrides the memory, not just reads it" + ); + assert_eq!( + state.resolve_dir("n", None), + Some("/tmp/other".to_owned()), + "the fallback now reflects the override" + ); +} + +#[test] +fn resolve_dir_does_not_cross_names() { + let state = State::new(PathBuf::from("/dev/null"), signal_url()); + state.resolve_dir("a", Some("/tmp/a")); + assert_eq!( + state.resolve_dir("b", None), + None, + "an unrelated name's memory must stay empty" + ); +} + +#[test] +fn peek_dir_resolves_like_resolve_dir_but_never_writes() { + let state = State::new(PathBuf::from("/dev/null"), signal_url()); + state.resolve_dir("n", Some("/tmp/remembered")); + assert_eq!( + state.peek_dir("n", Some("/tmp/one-off")), + Some("/tmp/one-off".to_owned()), + "an explicit dir still resolves as given" + ); + assert_eq!( + state.resolve_dir("n", None), + Some("/tmp/remembered".to_owned()), + "but the one-off peek must not have overwritten the remembered value" + ); +} + +#[tokio::test] +async fn start_does_not_corrupt_the_remembered_dir_when_the_name_is_already_running() { + // The exact scenario argus caught in review: a rejected concurrent + // `start` used to commit its `dir` before the reservation check + // refused it, corrupting what a later bare `continue` would resolve + // to. Reordering `reserve_under` before `resolve_dir` in `start` closes it + // — a name that's already reserved must never reach `resolve_dir` at + // all, so `dirs` stays exactly as a caller left it. + let state = Arc::new(State::new(PathBuf::from("/dev/null"), signal_url())); + state.resolve_dir("dup", Some("/tmp/original")); + assert!( + state.reserve("dup"), + "simulate an in-flight start/continue already owning the name" + ); + let result = start( + &state, + StartRequest { + dir: Some("/tmp/rejected".to_owned()), + ..start_request("dup") + }, + ) + .await; + assert!( + result.is_err(), + "a name already reserved must be refused, not spawned" + ); + assert_eq!( + state.resolve_dir("dup", None), + Some("/tmp/original".to_owned()), + "the rejected call's dir must not have overwritten the remembered one" + ); +} + +#[test] +fn a_new_turn_clears_the_previous_turn_s_kill() { + let state = State::new(PathBuf::from("/dev/null"), signal_url()); + state.finish_turn("n", &TurnEnd::Killed { signal: 9 }); + assert_eq!(state.killed_by("n"), Some(9)); + // What `spawn_and_track` does once the next turn is confirmed + // spawned, and then what its own clean end does. + state.clear_kill("n"); + assert_eq!(state.killed_by("n"), None); + state.finish_turn("n", &TurnEnd::Complete); + assert_eq!( + state.killed_by("n"), + None, + "a turn that finished must not leave the old kill standing" + ); +} + +#[test] +fn a_later_event_resets_the_age_rather_than_letting_it_climb() { + // The distinction the whole record exists for: a child still + // producing output must not accumulate the age of a wedged one. + let state = State::new(PathBuf::from("/dev/null"), signal_url()); + state.note_event("n"); + std::thread::sleep(Duration::from_millis(20)); + let before = state.last_event_age("n").expect("clock started"); + state.note_event("n"); + let after = state.last_event_age("n").expect("clock still running"); + assert!( + after < before, + "a fresh event must reset the age, not extend it: {after:?} vs {before:?}" + ); +} + +#[test] +fn the_liveness_clock_does_not_cross_names() { + let state = State::new(PathBuf::from("/dev/null"), signal_url()); + state.note_event("a"); + assert_eq!( + state.last_event_age("b"), + None, + "one subagent's output says nothing about another's" + ); +} + +#[test] +fn a_token_stops_resolving_once_its_run_is_over() { + // The expiry half of "unknown or expired token ⇒ 404": a finished + // run's config file still names its URL, and that URL must be dead. + let state = State::new(PathBuf::from("/dev/null"), signal_url()); + state.reserve("n"); + let token = token_of(&state.mint_signal_url("n")); + state.finish_turn("n", &TurnEnd::Complete); + assert_eq!( + state.session_for_signal_token(&token), + None, + "the run ended, so the route it was issued must resolve to nothing" + ); + + // Same for a call that never reached a spawn at all. + state.reserve("n"); + let unspawned = token_of(&state.mint_signal_url("n")); + state.release_reservation("n"); + assert_eq!(state.session_for_signal_token(&unspawned), None); +} + +#[test] +fn a_re_minted_url_retires_the_previous_one() { + // A `continue` mints the resumed run its own token; the run before it + // is over, so the URL that run was handed must not still work. + let state = State::new(PathBuf::from("/dev/null"), signal_url()); + let first = token_of(&state.mint_signal_url("n")); + let second = token_of(&state.mint_signal_url("n")); + assert_eq!(state.session_for_signal_token(&first), None); + assert_eq!( + state.session_for_signal_token(&second).as_deref(), + Some("n") + ); +} + +#[test] +fn reserve_under_refuses_a_new_name_at_the_cap_and_takes_one_below_it() { + let state = State::new(PathBuf::from("/dev/null"), signal_url()); + assert_eq!(state.reserve_under("a", Some(2)), Ok(())); + assert_eq!(state.reserve_under("b", Some(2)), Ok(())); + assert_eq!( + state.reserve_under("c", Some(2)), + Err(Refusal::AtCap { running: 2, cap: 2 }) + ); + assert_eq!(state.reserve_under("c", None), Ok(()), "no cap, no limit"); + assert_eq!( + state.reserve_under("a", Some(3)), + Err(Refusal::Taken), + "a taken name at the cap is refused as taken, not as over the cap" + ); +} + +#[test] +fn a_cap_of_zero_refuses_every_start() { + let state = State::new(PathBuf::from("/dev/null"), signal_url()); + assert_eq!( + state.reserve_under("a", Some(0)), + Err(Refusal::AtCap { running: 0, cap: 0 }) + ); + let msg = refused(&state, "a", &Refusal::AtCap { running: 0, cap: 0 }, "").to_string(); + assert!(msg.contains("disabled"), "{msg}"); +} + +/// A run between turns and one winding down both still count. +#[test] +fn every_tracked_slot_counts_toward_the_cap() { + let state = State::new(PathBuf::from("/dev/null"), signal_url()); + assert!(state.reserve("a")); + state.between_turns("a"); + assert!(state.reserve("b")); + state + .running + .lock() + .unwrap() + .insert("b".to_owned(), Slot::Stopping); + assert_eq!( + state.reserve_under("c", Some(2)), + Err(Refusal::AtCap { running: 2, cap: 2 }) + ); +} + +/// `start` and `continue` read the cap live: the swarm's cap of 1 refuses +/// a second name, naming the count and the cap. +#[tokio::test] +async fn start_and_continue_refuse_a_new_run_at_the_swarm_cap() { + let (state, reads) = state_reading(capped(1), "busy"); + let started = start(&state, start_on("other", None)).await; + let continued = continue_on(&state, "other", None).await; + for result in [started, continued] { + let err = result.expect_err("one running, cap is 1").to_string(); + assert!( + err.contains("1 subagent running, cap is 1") && err.contains("swarm-ui"), + "{err}" + ); + } + assert_eq!(reads.load(std::sync::atomic::Ordering::Relaxed), 2); + assert_eq!(state.occupancy("other"), None, "nothing was reserved"); +} + +/// The refusal comes from the model check, ahead of `reserve_under`'s. +#[tokio::test] +async fn start_and_continue_refuse_a_model_outside_the_swarm_list_before_reserving() { + let (state, reads) = state_reading(swarm(&["sonnet"]), "n"); + let started = start(&state, start_on("n", Some("opus"))).await; + let continued = continue_on(&state, "n", Some("opus")).await; + for result in [started, continued] { + let err = result + .expect_err("opus is outside the swarm's list") + .to_string(); + assert!(err.contains("swarm's subagent_models"), "{err}"); + } + assert_eq!(reads.load(std::sync::atomic::Ordering::Relaxed), 2); +} + +#[tokio::test] +async fn start_and_continue_take_a_swarm_listed_model_the_local_list_lacks() { + let (state, _) = state_reading(swarm(&["opus"]), "n"); + let started = start(&state, start_on("n", Some("opus"))).await; + let continued = continue_on(&state, "n", Some("opus")).await; + for result in [started, continued] { + let err = result.expect_err("the name is reserved").to_string(); + assert!(err.contains("already running"), "{err}"); + } +} + +/// The key is read without a model too, for the cap; no model is checked. +#[tokio::test] +async fn start_and_continue_without_a_model_skip_the_model_check() { + let (state, reads) = state_reading(swarm(&["sonnet"]), "n"); + let started = start(&state, start_on("n", None)).await; + let continued = continue_on(&state, "n", None).await; + for result in [started, continued] { + let err = result.expect_err("the name is reserved").to_string(); + assert!(err.contains("already running"), "{err}"); + } + assert_eq!(reads.load(std::sync::atomic::Ordering::Relaxed), 2); +} + +#[tokio::test] +async fn resuming_a_name_reused_in_a_sibling_worktree_attaches_to_its_newest_session() { + // `n` started once in a sibling worktree, then twice here — the + // second archiving the first — leaves two live sessions titled `n`, + // which claude refuses to resume by title. Both a goal run's next + // turn and a `continue` must resume the session the last `start` + // here created. + let root = scratch_dir("resume-newest"); + let (here, sibling) = (root.join("here"), root.join("sibling")); + let home = root.join("claude-home"); + for dir in [&here, &sibling, &home] { + std::fs::create_dir_all(dir).expect("scratch subdir"); + } + let program = root.join("session-claude"); + write_executable(&program, SESSION_CLAUDE); + let config = |cwd: &Path| Config { + program: Some(program.clone()), + cwd: Some(cwd.to_path_buf()), + claude_config_dir: Some(home.clone()), + ..Config::default() + }; + let attaches = || lines(&home.join("attaches")); + let state = Arc::new(State::new(PathBuf::from("/dev/null"), signal_url())); + + for (cwd, goal) in [(&sibling, None), (&here, None), (&here, Some("g"))] { + assert!(state.reserve("n")); + state.clear_stop("n"); + state.set_goal("n", goal.map(str::to_owned), 2); + start_on_runtime(&state, "n", config(cwd), None, "go".into()) + .expect("the fake claude spawns"); + until("the run ends", || state.last_event_age("n").is_none()).await; + } + assert_eq!( + attaches(), + [ + "create session-0", + "create session-1", + "create session-2", + "resume session-2" + ], + "the goal run's second turn must resume its own session, not the title" + ); + + state.set_goal("n", None, 1); + state.clear_stop("n"); + assert!(state.reserve("n")); + let (tx, rx) = oneshot::channel(); + let verdict: VerdictTx = Arc::new(Mutex::new(Some(tx))); + continue_on_runtime(&state, "n", config(&here), None, "again".into(), &verdict) + .expect("the fake claude spawns"); + await_resume(rx) + .await + .expect("a title shared with a sibling worktree must not fail the continue"); + until("the continue's turn ends", || { + state.last_event_age("n").is_none() + }) + .await; + assert_eq!( + attaches(), + [ + "create session-0", + "create session-1", + "create session-2", + "resume session-2", + "resume session-2" + ], + "the continue must add its own resume of the session, not of the title" + ); + std::fs::remove_dir_all(&root).ok(); +} + +#[tokio::test] +async fn resuming_where_no_session_is_on_disk_is_refused_without_spawning() { + // `n` lives only in the sibling worktree, where claude would resolve + // the bare title; resuming from `here` must refuse instead. + let root = scratch_dir("resume-refused"); + let (here, sibling) = (root.join("here"), root.join("sibling")); + let home = root.join("claude-home"); + for dir in [&here, &sibling, &home] { + std::fs::create_dir_all(dir).expect("scratch subdir"); + } + let program = root.join("session-claude"); + write_executable(&program, SESSION_CLAUDE); + let config = |cwd: &Path| Config { + program: Some(program.clone()), + cwd: Some(cwd.to_path_buf()), + claude_config_dir: Some(home.clone()), + ..Config::default() + }; + let state = Arc::new(State::new(PathBuf::from("/dev/null"), signal_url())); + assert!(state.reserve("n")); + state.clear_stop("n"); + start_on_runtime(&state, "n", config(&sibling), None, "go".into()) + .expect("the fake claude spawns"); + until("the run ends", || state.last_event_age("n").is_none()).await; + + let searched = SessionStore::new(&home, &here).project_dir(); + assert!(state.reserve("n")); + let (tx, rx) = oneshot::channel(); + let verdict: VerdictTx = Arc::new(Mutex::new(Some(tx))); + let refused = continue_on_runtime(&state, "n", config(&here), None, "again".into(), &verdict) + .expect_err("no session titled `n` under `here`"); + assert_eq!( + refused.to_string(), + format!( + "no session titled `n` under {}; pass the `dir` the session was started in", + searched.display() + ) + ); + drop(rx); + assert_eq!( + lines(&home.join("attaches")), + ["create session-0"], + "claude was not spawned, so nothing attached" + ); + assert!(state.last_event_age("n").is_none(), "no turn is tracked"); + + assert!( + resume_target(&config(&sibling), "n").is_ok(), + "the directory it was started in still resumes" + ); + std::fs::remove_dir_all(&root).ok(); +} + +#[tokio::test] +async fn an_acp_parent_runs_its_subagents_on_its_acp_agent() { + let dir = scratch_dir("runtime-acp"); + let state = State::new(PathBuf::from("/dev/null"), signal_url()); + let state = Arc::new(on_acp_agent(state, &dir, "answer")); + let role = dir.join("role.md"); + std::fs::write(&role, "ROLE-TEXT").expect("write the role"); + + assert!(state.reserve("n")); + start_on_runtime( + &state, + "n", + claude_config(&dir), + Some(role), + "TRIGGER-ONE".into(), + ) + .expect("the ACP run starts"); + until("the start's run ends", || state.occupancy("n").is_none()).await; + + let prompts = lines(&dir.join("prompts")); + assert_eq!(prompts.len(), 1, "{prompts:?}"); + assert!( + prompts[0].contains("ROLE-TEXT") && prompts[0].contains("TRIGGER-ONE"), + "the first prompt carries the role, since ACP has no system prompt: {prompts:?}" + ); + assert_eq!( + std::fs::read_to_string(acp_session_file(&dir, "n")).unwrap(), + "s1" + ); + + assert!(state.reserve("n")); + let (tx, rx) = oneshot::channel(); + let verdict: VerdictTx = Arc::new(Mutex::new(Some(tx))); + continue_on_runtime( + &state, + "n", + claude_config(&dir), + None, + "TRIGGER-TWO".into(), + &verdict, + ) + .expect("the ACP continue starts"); + await_resume(rx).await.expect("the resumed turn lands"); + until("the continue's run ends", || state.occupancy("n").is_none()).await; + + let prompts = lines(&dir.join("prompts")); + assert_eq!(prompts.len(), 2, "{prompts:?}"); + assert!( + prompts[1].contains("TRIGGER-TWO") && !prompts[1].contains("ROLE-TEXT"), + "the continue resumes the session rather than starting one: {prompts:?}" + ); + assert!( + lines(&dir.join("prompts.methods")).contains(&"session/load".to_owned()), + "the continue's agent process loads the recorded session" + ); + assert_eq!( + turns_spawned(&dir.join("claude-turns")), + 0, + "an ACP agent's subagent never runs claude" + ); + std::fs::remove_dir_all(&dir).ok(); +} + +#[tokio::test] +async fn an_acp_continue_with_no_recorded_session_is_refused() { + let dir = scratch_dir("runtime-acp-missing"); + let state = State::new(PathBuf::from("/dev/null"), signal_url()); + let state = Arc::new(on_acp_agent(state, &dir, "answer")); + let (tx, _rx) = oneshot::channel(); + let verdict: VerdictTx = Arc::new(Mutex::new(Some(tx))); + + let err = continue_on_runtime( + &state, + "n", + claude_config(&dir), + None, + "go".into(), + &verdict, + ) + .expect_err("nothing to resume"); + assert!(err.to_string().contains("no ACP session"), "{err}"); + assert!( + !dir.join("prompts.methods").exists(), + "the agent is never started" + ); + std::fs::remove_dir_all(&dir).ok(); +} + +#[test] +fn a_run_without_a_cgroup_still_starts_at_the_subagent_score() { + let state = State::new(PathBuf::from("/dev/null"), signal_url()).entering_runs(None); + let config = state.entered_config(&Config::default(), None); + assert_eq!(config.program.as_deref(), Some(Path::new("/proc/self/exe"))); + assert_eq!( + env_of(&config.env, "HIVE_RUN_ENTRY_PROGRAM"), + Some("claude") + ); + assert_eq!( + env_of(&config.env, "HIVE_RUN_ENTRY_OOM_SCORE_ADJ"), + Some("900") + ); + assert_eq!(env_of(&config.env, "HIVE_RUN_ENTRY_CGROUP"), None); + + let command = AcpCommand { + command: "agent".to_owned(), + args: Vec::new(), + env: std::collections::BTreeMap::new(), + api_key_env: None, + }; + let command = state.entered_command(command, None); + assert_eq!(command.command, "/proc/self/exe"); + assert_eq!( + command + .env + .get("HIVE_RUN_ENTRY_PROGRAM") + .map(String::as_str), + Some("agent") + ); + assert_eq!( + command + .env + .get("HIVE_RUN_ENTRY_OOM_SCORE_ADJ") + .map(String::as_str), + Some("900") + ); +} + +#[test] +fn runs_are_started_plain_unless_the_daemon_enters_them() { + let state = State::new(PathBuf::from("/dev/null"), signal_url()); + let config = state.entered_config(&Config::default(), None); + assert_eq!(config.program, None); + assert!(config.env.is_empty()); +} diff --git a/hive-subagent-mcp/src/session/tests/status.rs b/hive-subagent-mcp/src/session/tests/status.rs new file mode 100644 index 000000000..c35251197 --- /dev/null +++ b/hive-subagent-mcp/src/session/tests/status.rs @@ -0,0 +1,615 @@ +//! What `status` and `interrupt` say. + +use super::*; + +#[test] +fn status_reports_killed_not_idle_for_a_signalled_session() { + // Both sessions exist on disk and neither is running: the only thing + // that can tell them apart is the recorded signal. + let killed = describe_status(&StatusFacts { + killed: Some(libc::SIGKILL), + session_exists: true, + ..StatusFacts::new("n") + }) + .expect("killed status"); + let idle = describe_status(&StatusFacts { + session_exists: true, + ..StatusFacts::new("n") + }) + .expect("idle status"); + assert!( + killed.contains("killed") && killed.contains("SIGKILL (signal 9)"), + "a killed session must say so, and name the signal: {killed}" + ); + assert!( + !killed.contains("idle"), + "a killed session must not also read as idle: {killed}" + ); + assert!(idle.contains("idle"), "a finished turn still reads idle"); + assert_ne!( + killed, idle, + "collapsing the two back together is the bug this reports" + ); +} + +#[test] +fn every_status_answer_names_its_state_and_the_next_move() { + // The tool description no longer lists the states, so each answer + // has to carry its own explanation — checked one state at a time, + // which is all a caller ever gets back. + let running = describe_status(&StatusFacts { + occupancy: Some(Occupancy::Running), + ..StatusFacts::new("n") + }) + .expect("running status"); + assert!( + running.contains("running") && running.contains("`interrupt`"), + "a running answer must say the turn is in flight and how to stop it: {running}" + ); + let starting = describe_status(&StatusFacts { + occupancy: Some(Occupancy::Starting), + ..StatusFacts::new("n") + }) + .expect("starting status"); + assert!( + starting.contains("starting") && starting.contains("check again"), + "a starting answer must say the spawn isn't confirmed yet and to retry: {starting}" + ); + let idle = describe_status(&StatusFacts { + session_exists: true, + ..StatusFacts::new("n") + }) + .expect("idle status"); + assert!( + idle.contains("idle") && idle.contains("`continue`"), + "an idle answer must say the last turn ended on its own and how to give it another: \ + {idle}" + ); + let killed = describe_status(&StatusFacts { + killed: Some(libc::SIGKILL), + session_exists: true, + ..StatusFacts::new("n") + }) + .expect("killed status"); + assert!( + killed.contains("killed") && killed.contains("`continue`"), + "a killed answer must name the kill and say resuming is still possible: {killed}" + ); + let missing = describe_status(&StatusFacts::new("n")) + .expect_err("nothing tracked and nothing on disk is an error, not a state"); + assert!( + missing.to_string().contains("`start`"), + "the no-such-session answer must point at what creates one: {missing}" + ); +} + +#[test] +fn a_killed_turn_and_a_clean_one_do_not_land_in_the_same_state() { + // The whole path a real turn takes, minus the process: what the + // driver returned -> what the daemon records -> what `status` says. + let state = State::new(PathBuf::from("/dev/null"), signal_url()); + for (name, outcome) in [ + ("gone", Err(signalled_exit(libc::SIGKILL))), + ("done", Ok(())), + ] { + assert!(state.reserve(name)); + state.finish_turn(name, &classify_end(outcome, None)); + assert_eq!( + state.occupancy(name), + None, + "the turn is over either way — nothing stays tracked as running" + ); + } + assert_eq!(state.killed_by("gone"), Some(9)); + assert_eq!(state.killed_by("done"), None); + + let gone = describe_status(&StatusFacts { + killed: state.killed_by("gone"), + session_exists: true, + ..StatusFacts::new("gone") + }) + .expect("status"); + let done = describe_status(&StatusFacts { + killed: state.killed_by("done"), + session_exists: true, + ..StatusFacts::new("done") + }) + .expect("status"); + assert!(gone.contains("killed"), "{gone}"); + assert!(done.contains("idle"), "{done}"); +} + +#[test] +fn describe_signal_names_the_ones_that_end_a_subagent() { + assert_eq!(describe_signal(9), "SIGKILL (signal 9)"); + assert_eq!(describe_signal(15), "SIGTERM (signal 15)"); + assert_eq!(describe_signal(2), "SIGINT (signal 2)"); + assert_eq!(describe_signal(7), "signal 7"); +} + +#[test] +fn a_running_status_reports_the_age_and_an_idle_one_does_not() { + let running = describe_status(&StatusFacts { + occupancy: Some(Occupancy::Running), + last_event_age: Some(Duration::from_secs(4)), + ..StatusFacts::new("n") + }) + .expect("running status"); + assert!( + running.contains("Last event 4s ago"), + "a running answer must carry the age — the one part of it a caller can act on: \ + {running}" + ); + let wedged = describe_status(&StatusFacts { + occupancy: Some(Occupancy::Running), + last_event_age: Some(Duration::from_mins(15)), + ..StatusFacts::new("n") + }) + .expect("running status"); + assert!( + wedged.contains("Last event 900s ago"), + "the wedged case is the one this exists for: {wedged}" + ); + assert_ne!( + running, wedged, + "4s-ago and 900s-ago must not render identically — collapsing them back together is \ + the bug this reports" + ); + + let idle = describe_status(&StatusFacts { + session_exists: true, + ..StatusFacts::new("n") + }) + .expect("idle status"); + assert!( + !idle.contains("Last event"), + "an idle session has no in-flight turn whose progress an age would describe: {idle}" + ); +} + +#[test] +fn a_running_status_still_answers_when_the_turn_ended_mid_call() { + // `status` reads `running` and the clock under separate locks, so a + // turn can finish between the two. The answer drops the age rather + // than inventing one. + let raced = describe_status(&StatusFacts { + occupancy: Some(Occupancy::Running), + ..StatusFacts::new("n") + }) + .expect("running status"); + assert!( + raced.contains("is running") && !raced.contains("Last event"), + "a missing age must cost the sentence, not the answer: {raced}" + ); +} + +#[tokio::test] +async fn an_early_end_that_is_not_a_failure_still_reads_as_started() { + // A turn that completed, or that a concurrent `interrupt` killed, + // inside the grace: both ended a turn that genuinely began, and both + // have a todo of their own to explain themselves. + for end in [TurnEnd::Complete, TurnEnd::Killed { signal: 9 }] { + let (tx, rx) = oneshot::channel(); + tx.send(ResumeVerdict::Ended(end.clone())) + .map_err(|_| ()) + .expect("the waiter is still listening"); + assert!( + await_resume(rx).await.is_ok(), + "{end:?} ended a turn that started — only a failure is the caller's error" + ); + } +} + +#[tokio::test] +async fn an_interrupt_cancels_the_whole_goal_run_and_not_merely_its_turn() { + // The regression, end to end through the real + // continuation loop: a goal run with four turns left is interrupted, + // its child exits cleanly the way claude actually does, and the loop + // must not spawn turn two. + let dir = std::env::temp_dir().join(format!( + "hive-subagent-cancel-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + std::fs::create_dir_all(&dir).expect("scratch dir"); + let log = dir.join("turns"); + let program = fake_claude(&dir, &log); + + let state = Arc::new(mid_run("n", "carry on indefinitely", 5)); + let config = Config { + program: Some(program), + ..Config::default() + }; + spawn_and_track( + &state, + "n", + &config, + &Attach::Create("n".to_owned()), + "turn one".to_owned(), + None, + ) + .expect("the fake claude spawns"); + + // Wait for the first turn to be genuinely under way before + // interrupting: signalling a child that hasn't run yet would prove + // nothing about the loop. + for _ in 0..100 { + if turns_spawned(&log) == 1 { + break; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + assert_eq!(turns_spawned(&log), 1, "the first turn never started"); + + interrupt(&state, "n").expect("a running turn is interruptible"); + + // Generous: the fake logs its invocation as its first act, so a + // re-prompt shows up here almost immediately once the loop decides + // to make one. + tokio::time::sleep(Duration::from_millis(1500)).await; + assert_eq!( + turns_spawned(&log), + 1, + "an interrupted goal run must not be re-prompted — that is the whole of the cancel" + ); + assert_eq!( + state.stop_reason("n"), + Some(StopReason::Cancelled), + "and the run must carry a reason saying why it stopped" + ); + std::fs::remove_dir_all(&dir).ok(); +} + +#[tokio::test] +async fn an_interrupt_stops_the_commands_the_subagent_started() { + let dir = scratch_dir("group"); + let pidfile = dir.join("grandchild.pid"); + let state = Arc::new(mid_run("n", "carry on indefinitely", 5)); + let config = Config { + program: Some(busy_claude(&dir, &pidfile)), + ..Config::default() + }; + spawn_and_track( + &state, + "n", + &config, + &Attach::Create("n".to_owned()), + "turn one".to_owned(), + None, + ) + .expect("the fake claude spawns"); + let grandchild = read_pid(&pidfile).await; + + interrupt(&state, "n").expect("a running turn is interruptible"); + + let mut alive = is_running(grandchild); + for _ in 0..250 { + if !alive { + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + alive = is_running(grandchild); + } + if alive { + // SAFETY: `kill(2)` on a pid this test started; keeps a failed + // run from leaving a 300s `sleep` behind. + unsafe { + libc::kill(grandchild, libc::SIGKILL); + } + } + std::fs::remove_dir_all(&dir).ok(); + assert!(!alive, "grandchild {grandchild} outlived the interrupt"); +} + +#[tokio::test] +async fn an_interrupt_lets_claude_shut_down_on_sigint() { + let dir = scratch_dir("sigint"); + std::fs::write(dir.join("release"), "").expect("release file"); + let state = Arc::new(mid_run("n", "carry on indefinitely", 5)); + spawn_graceful(&state, &dir).await; + + interrupt(&state, "n").expect("a running turn is interruptible"); + + until("the run ends", || state.occupancy("n").is_none()).await; + let interrupted = dir.join("interrupted").exists(); + std::fs::remove_dir_all(&dir).ok(); + assert!( + interrupted, + "claude must get SIGINT, which it shuts its tool commands down on, never SIGKILL" + ); + assert_eq!(state.killed_by("n"), None, "it exited on its own"); +} + +#[tokio::test] +async fn an_interrupted_name_stays_claimed_until_claude_has_exited() { + let dir = scratch_dir("stopping"); + let state = Arc::new(mid_run("n", "carry on indefinitely", 5)); + spawn_graceful(&state, &dir).await; + + interrupt(&state, "n").expect("a running turn is interruptible"); + until("the fake claude gets the SIGINT", || { + dir.join("interrupted").exists() + }) + .await; + + assert_eq!(state.occupancy("n"), Some(Occupancy::Stopping)); + let status = status(&state, "n", None).expect("status"); + assert!(status.contains("is stopping"), "{status}"); + let refused = continue_(&state, "n", "more".to_owned(), None, None, None) + .await + .expect_err("a second claude must not start on the session"); + assert!(refused.to_string().contains("is stopping"), "{refused}"); + assert!(interrupt(&state, "n").is_err(), "it was already signalled"); + + std::fs::write(dir.join("release"), "").expect("release file"); + until("the run ends", || state.occupancy("n").is_none()).await; + std::fs::remove_dir_all(&dir).ok(); + assert!( + state.reserve("n"), + "the name is free once claude has exited" + ); +} + +#[test] +fn a_continue_after_a_cancel_starts_the_run_over() { + // The deliberate other half: a cancel is not a permanent + // state. `continue` clears the reason and hands back a fresh + // allowance, which is what makes `interrupt` a pause an operator can + // undo rather than a session they have to abandon. + let state = mid_run("n", "a goal", 5); + state.record_stop("n", StopReason::Cancelled); + state.clear_stop("n"); + state.restart_turns("n"); + assert_eq!( + state.plan_after_turn("n"), + Continuation::Continue { + prompt: continuation_prompt("n", "a goal", 2, 5) + }, + "a continued session resumes toward its goal" + ); +} + +#[test] +fn need_help_is_a_state_a_parent_can_see_without_reading_anything() { + // Requirement in full: it stops the session *and* shows up in + // `status` as its own state, distinct from idle and from killed. + let blocked = describe_status(&StatusFacts { + stop: Some(StopReason::NeedHelp( + "the brief contradicts the code".to_owned(), + )), + turns: Some((2, 5)), + ..StatusFacts::new("n") + }) + .expect("a blocked session is a state, not an error"); + assert!( + blocked.contains("BLOCKED") && blocked.contains("the brief contradicts the code"), + "the block and its reason must both be in the answer: {blocked}" + ); + assert!( + !blocked.contains("Turn 2 of 5"), + "a subagent waiting on an answer needs the answer, not a turn count competing for \ + attention: {blocked}" + ); + assert!( + !blocked.contains("idle"), + "a blocked subagent must not also read as idle: {blocked}" + ); +} + +#[test] +fn turn_cap_status_still_carries_the_turn_count() { + // The turn count is the whole point of a `TurnCap` stop — omitting + // it here (unlike `NeedHelp`) would be the regression a later + // refactor could silently reintroduce. + let capped = describe_status(&StatusFacts { + stop: Some(StopReason::TurnCap { turns: 5 }), + turns: Some((5, 5)), + ..StatusFacts::new("n") + }) + .expect("a capped session is a state, not an error"); + assert!( + capped.contains("Turn 5 of 5"), + "the turn count is the point of a TurnCap status: {capped}" + ); +} + +#[test] +fn a_reported_goal_never_reads_as_a_verified_one() { + // The failure this is built against: `goal_reached` is self-reported + // by a subagent that has just been told it hasn't reached the goal. + // Every surface that renders it has to say so. + let status = describe_status(&StatusFacts { + stop: Some(StopReason::GoalReached(Some( + "refactored the parser".to_owned(), + ))), + ..StatusFacts::new("n") + }) + .expect("status"); + assert!( + status.contains("refactored the parser") && status.contains("claim"), + "status must carry both the report and the fact it's only a report: {status}" + ); + let todo = turn_end_summary( + "n", + &TurnEnd::Complete, + Some(&StopReason::GoalReached(Some( + "refactored the parser".to_owned(), + ))), + ); + assert!( + todo.contains("self-reported, not verified"), + "and so must the todo, which is the half a parent reads unprompted: {todo}" + ); +} + +#[test] +fn status_reports_the_turn_counter_in_every_state_a_goal_run_reaches() { + for occupancy in [ + Some(Occupancy::Running), + Some(Occupancy::Starting), + Some(Occupancy::Stopping), + None, + ] { + let answer = describe_status(&StatusFacts { + occupancy, + session_exists: true, + turns: Some((3, 5)), + ..StatusFacts::new("n") + }) + .expect("status"); + assert!( + answer.contains("Turn 3 of 5"), + "progress is the point of the counter — it can't be absent from {occupancy:?}: \ + {answer}" + ); + } + let goalless = describe_status(&StatusFacts { + occupancy: Some(Occupancy::Running), + ..StatusFacts::new("n") + }) + .expect("status"); + assert!( + !goalless.contains("Turn "), + "a session with no goal has no budget to be partway through: {goalless}" + ); +} + +#[test] +fn a_running_turn_that_has_already_signalled_says_so() { + // The window a parent would otherwise misread: the subagent has said + // it is blocked, its turn hasn't ended yet, and plain "running" would + // tell the parent to leave it alone. + let answer = describe_status(&StatusFacts { + occupancy: Some(Occupancy::Running), + stop: Some(StopReason::NeedHelp("no credential".to_owned())), + ..StatusFacts::new("n") + }) + .expect("status"); + assert!( + answer.contains("is running") && answer.contains("no credential"), + "both facts are true at once and both have to be in the answer: {answer}" + ); + let quiet = describe_status(&StatusFacts { + occupancy: Some(Occupancy::Running), + stop: Some(StopReason::Done), + ..StatusFacts::new("n") + }) + .expect("status"); + assert!( + !quiet.contains("already signalled"), + "`Done` is not a signal the subagent raised — nothing to announce: {quiet}" + ); +} + +#[test] +fn a_kill_outranks_a_stop_reason_the_subagent_had_already_raised() { + // Both records can be set at once — a subagent calls `goal_reached` + // and something SIGKILLs it before the turn ends. The observed kill + // is the one that can't be a claim. + let answer = describe_status(&StatusFacts { + killed: Some(libc::SIGKILL), + stop: Some(StopReason::GoalReached(None)), + session_exists: true, + ..StatusFacts::new("n") + }) + .expect("status"); + assert!( + answer.contains("was killed"), + "the kill is what happened: {answer}" + ); + assert!( + !answer.contains("goal reached"), + "a claim made just before being killed must not be the headline: {answer}" + ); +} + +#[tokio::test] +async fn a_claude_parent_runs_its_subagents_on_claude() { + let dir = scratch_dir("runtime-claude"); + let state = Arc::new(State::new(PathBuf::from("/dev/null"), signal_url())); + assert!(state.reserve("n")); + + start_on_runtime(&state, "n", claude_config(&dir), None, "go".into()) + .expect("the fake claude spawns"); + until("claude runs the turn", || { + turns_spawned(&dir.join("claude-turns")) == 1 + }) + .await; + interrupt(&state, "n").expect("a running claude turn is interruptible"); + until("the run ends", || state.occupancy("n").is_none()).await; + + // This `start` had no goal, so the fake claude's clean exit after + // SIGINT (`TurnEnd::Complete`) is exactly the case that used to + // report "finished: turn complete" with no sign it was interrupted. + // `plan_after_turn` checks `stop_reason` before it checks `goals`, so + // the recorded `Cancelled` survives even here — this is the + // non-goal case the goal-run-cancel fix left unverified. + assert_eq!( + state.stop_reason("n"), + Some(StopReason::Cancelled), + "a plain (non-goal) interrupted turn must still record why it stopped" + ); + + assert!( + !acp_session_file(&dir, "n").exists() && !dir.join("prompts.methods").exists(), + "a claude agent's subagent never touches an ACP agent" + ); + std::fs::remove_dir_all(&dir).ok(); +} + +#[tokio::test] +async fn an_interrupt_cancels_an_acp_goal_run() { + let dir = scratch_dir("runtime-acp-cancel"); + let state = Arc::new(on_acp_agent( + mid_run("n", "carry on indefinitely", 5), + &dir, + "hold", + )); + start_on_runtime(&state, "n", claude_config(&dir), None, "go".into()) + .expect("the ACP run starts"); + until("the first prompt reaches the agent", || { + dir.join("prompts").exists() + }) + .await; + + interrupt(&state, "n").expect("a running ACP turn is interruptible"); + assert_eq!( + state.occupancy("n"), + None, + "an interrupted ACP turn frees its name at once; only claude's stays claimed" + ); + until("the run ends", || state.last_event_age("n").is_none()).await; + + assert_eq!(lines(&dir.join("prompts")).len(), 1, "no second goal turn"); + assert!( + lines(&dir.join("prompts.methods")).contains(&"session/cancel".to_owned()), + "the turn was stopped with `session/cancel`" + ); + assert_eq!(state.stop_reason("n"), Some(StopReason::Cancelled)); + std::fs::remove_dir_all(&dir).ok(); +} + +#[tokio::test] +async fn an_interrupt_before_the_acp_turn_is_live_is_refused() { + let dir = scratch_dir("runtime-acp-early-cancel"); + let state = State::new(PathBuf::from("/dev/null"), signal_url()); + let state = Arc::new(on_acp_agent(state, &dir, "answer")); + assert!(state.reserve("n")); + start_on_runtime(&state, "n", claude_config(&dir), None, "go".into()) + .expect("the ACP run starts"); + + // The test runtime is single-threaded, so the run's task has not + // been polled yet: no turn is in flight. + let err = interrupt(&state, "n").expect_err("nothing to cancel yet"); + assert!(err.to_string().contains("still starting"), "{err}"); + assert_eq!(state.stop_reason("n"), None); + + until("the run ends", || state.occupancy("n").is_none()).await; + assert_eq!(lines(&dir.join("prompts")).len(), 1); + assert_eq!( + state.stop_reason("n"), + Some(StopReason::Done), + "the run was never marked cancelled" + ); + std::fs::remove_dir_all(&dir).ok(); +}