Watch
0
0
Fork
You've already forked hyperhive
0
hyperhive/hive-subagent-mcp/src/session/state.rs

716 lines
32 KiB
Rust

//! 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<HashMap<String, Slot>>,
dirs: Mutex<HashMap<String, String>>,
killed: Mutex<HashMap<String, i32>>,
last_event: Mutex<HashMap<String, Instant>>,
/// 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<HashMap<String, GoalState>>,
pub(super) stops: Mutex<HashMap<String, StopReason>>,
reports: Mutex<HashMap<String, PathBuf>>,
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<SignalTokens>,
/// 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<crate::swarm_term::Publisher>,
/// 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<crate::swarm_models::Reader>,
/// The agent's own model list, checked when the swarm sets none:
/// [`available_models`] outside tests.
pub(super) local_models: fn() -> Option<String>,
/// 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<RunCgroups>,
/// The `<n>` of the next run cgroup `<name>-<n>`.
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<String, String>,
/// The resolution the route does: token -> the session it speaks for.
by_token: HashMap<String, String>,
}
/// 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<crate::swarm_term::Publisher>) -> 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<crate::swarm_models::Reader>) -> 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<RunCgroups>) -> 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<RunCgroup> {
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<Option<u32>> {
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<String> {
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<Occupancy> {
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<u32>) -> 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<crate::swarm_term::RunInfo>) {
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<i32> {
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<Duration> {
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<String> {
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<String> {
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<String>, 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<StopReason> {
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<PathBuf> {
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),
}
}
}