Skip to main content

agentmux_srv_core/backend/blockcontroller/
loop_stop.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//! What follows a turn the loop guard (`agents::loop_guard`) ended, the same for every controller: a note held for
4//! the agent's next turn, and one to its leader (`docs/specs/SPEC_ROUTE_AGENT_BRAKES_2026_11_10.md` section 5). How the
5//! turn is ended is the controller's own: Claude's control-protocol interrupt (`persistent/loop_stop.rs`), ACP's
6//! `session/cancel` (`acp_spawn.rs`).
7
8use crate::agents::loop_guard::Stuck;
9use crate::backend::storage::store::Store;
10use std::sync::Arc;
11
12/// The key the agent's note is held under; a second one replaces the first.
13const NOTE_KEY: &str = "loop-guard";
14
15/// The note the agent finds at the start of its next turn.
16pub(crate) fn agent_note(stuck: &Stuck) -> String {
17    let what = crate::backend::reactive::sanitize::quote_in_system_note(&stuck.describe());
18    format!("[AgentMux] Your last turn was ended: {what}. Do not make that call again as it was; read what it answered, change what you pass, or ask your leader.")
19}
20
21/// The note to the agent's leader, if it has one on this machine with a pane open.
22fn tell_leader(mstore: &Arc<Store>, block_id: &str, stuck: &Stuck) {
23    let Some(agent) = crate::identity::resolver::block_agent_id(mstore, block_id) else { return };
24    let name = mstore.agent_def_get(&agent).ok().flatten().map(|d| d.name).unwrap_or_else(|| agent.clone());
25    let body = format!("{name}'s turn was ended: {}. It can be sent a new message and goes on.", stuck.describe());
26    if !crate::backend::worker_notes::tell_leader(mstore, &agent, &body) {
27        tracing::info!(agent = %agent, "loop guard: no leader to tell that the turn was ended");
28    }
29}
30
31/// The turn of `block_id` was ended for `stuck`: hold the agent's note and tell its leader.
32pub(crate) fn after_ending(block_id: &str, mstore: Option<&Arc<Store>>, stuck: &Stuck) {
33    tracing::warn!(block_id = %block_id, what = %stuck.describe(), "loop guard: ending the turn");
34    crate::backend::reactive::held_notes::hold(block_id, NOTE_KEY, &agent_note(stuck));
35    if let Some(mstore) = mstore.cloned() {
36        let (block_id, stuck) = (block_id.to_string(), stuck.clone());
37        // Reads the store and takes the handler's lock: not on the reader's task.
38        tokio::task::spawn_blocking(move || tell_leader(&mstore, &block_id, &stuck));
39    }
40}