trusty_code/session/registry_agents.rs
1//! `SessionRegistry::get_agents` — the live agent-roster query behind
2//! `session.get_agents` (DOC-39 §5.4). Split out of `registry.rs` purely to
3//! keep that production file under the crate's 500-SLOC cap — this is a
4//! child module of `registry` (declared via `#[path = ...] mod agents;`), so
5//! it shares full access to `SessionRegistry`'s private helpers exactly as
6//! if these methods were still defined in that file.
7//!
8//! Why: DOC-39 §3.2/§5.4 documents that "who is running?" was daemon-owned
9//! state a UI client had to reconstruct itself by folding the SSE replay —
10//! the shape §2.1 forbids (C-1: the daemon owns all logic; a client never
11//! derives). §5.4 names `session.get_agents` as "the principled endpoint;
12//! the fold is a Phase-1 loan, not a design" and directs that loan to be
13//! repaid by moving the fold server-side.
14//!
15//! **This module went through two designs, and the first one had a bug a
16//! code-critic review on the #2962 PR caught as a HIGH.** The first cut
17//! folded `SessionRegistry::replay`'s ring-buffer snapshot on every
18//! `get_agents` call. That moved WHERE the fold ran (daemon, not client) but
19//! not WHAT it could lose: the ring buffer is capacity-bounded
20//! (`ring_capacity`, default [`super::DEFAULT_RING_CAPACITY`]) and evicts
21//! oldest-first, so a long-running agent's `ToolStarted` could age out of
22//! the ring before any LATER attributed event for that same `agent_id`
23//! landed — making it vanish from the roster entirely, indistinguishable
24//! from "never spawned" even though it may still genuinely be running. That
25//! is the exact silent-data-loss shape §5.4's original text warned about;
26//! folding server-side did not close it.
27//! What: [`get_agents`] instead reads `SessionEntry::agents` — an
28//! ALWAYS-RETAINED `Vec<AgentRosterState>`, kept up to date by
29//! `SessionEntry::note_agent_activity` (called from
30//! `SessionRegistry::record`, the SAME critical section that pushes onto the
31//! ring — see that field's own docs in `registry.rs`) and evicted only when
32//! the session itself goes away, never by ring capacity. This closes the
33//! HIGH: an agent's roster row survives for the life of the session
34//! regardless of how much ring-buffer traffic follows it.
35//!
36//! **What is NOT populated, and why (§5.4 AC-15.1 is only partially met):**
37//! - `model` — always `None`. No production event ties a resolved model
38//! string to a stable `agent_id` yet; `LlmRequested`/`LlmResponded` carry
39//! `model`, but only `agent_name` (a string DOC-39 AC-13.2 explicitly
40//! retires as a correlation key), and folding by name would silently
41//! misattribute the model when two same-named agents run concurrently —
42//! exactly the bug #2898 existed to close. Closing this gap needs `model`
43//! threaded onto an `agent_id`-carrying event, which is out of this
44//! endpoint's scope.
45//! - `task` — always `None`. `PmDelegating.agent`/`task_preview` predates
46//! `agent_id` and is keyed by name only, so it cannot be joined onto a
47//! specific spawn without the same name-collision risk as `model` above.
48//! - `files_changed` — always `[]`. No event or registry state tracks it
49//! today; §5.4 lists it in the target result shape but it is net-new domain
50//! state, not a folding gap.
51//!
52//! (#8235) `todos` is no longer one of those deferred defaults: the
53//! `todo_write` tool (`tools::checklist`) writes it through
54//! `SessionRegistry::set_agent_todos` (`registry_todos.rs`) and this endpoint
55//! projects it. It is a `Vec<TodoItem>`, not a `Vec<String>` — the reserved
56//! field's element type was never exercised, and a rendered string would
57//! force every reader to parse a done-mark back out, which §2.1 C-1 forbids.
58//!
59//! `AgentSpawned`/`AgentStarted`/`AgentDone`/`AgentFailed` (DOC-39 AC-13)
60//! are NOT sources here even though their shape looks purpose-built for a
61//! roster: `events.rs`'s own docs and #2898's CHANGELOG entry record that
62//! none of them are emitted by any production call site yet, so keying off
63//! them would silently return an always-empty roster instead of the real,
64//! already-flowing tool-attribution activity `registry.rs::tool_attribution`
65//! sources from.
66//! Test: `registry_agents::tests::*`; `protocol_agents::tests::*` covers the
67//! RPC-level wiring.
68
69use serde::Serialize;
70
71use super::*;
72
73/// `state` value for an agent whose live roster row (`AgentRosterState`) is
74/// currently `running: true` — its last known event is an unmatched
75/// `ToolStarted`.
76const STATE_RUNNING: &str = "running";
77/// `state` value for an agent whose live roster row is `running: false` — no
78/// tool call is known to be in flight.
79const STATE_IDLE: &str = "idle";
80
81/// One entry in `session.get_agents`'s live roster (DOC-39 §5.4).
82///
83/// Why: the wire shape `session.get_agents` returns per agent — see the
84/// module docs for exactly which fields are read from the always-retained
85/// `SessionEntry::agents` state and which are deferred defaults.
86/// What: `agent_id` is the DOC-39 AC-13 stable per-spawn id; `name` is the
87/// human-readable agent name (`"pm"` for the root loop, an agent config name
88/// like `"python-engineer"` for a delegation). See module docs for
89/// `model`/`task`/`todos`/`files_changed`.
90/// Test: `registry_agents::tests::*`.
91#[derive(Debug, Clone, Serialize)]
92pub struct AgentRosterEntry {
93 pub agent_id: String,
94 pub name: String,
95 pub model: Option<String>,
96 pub state: String,
97 pub task: Option<String>,
98 /// (#8235) This agent's session checklist, newest write wins — `[]` until
99 /// its first `todo_write` call.
100 pub todos: Vec<crate::events::TodoItem>,
101 pub files_changed: Vec<String>,
102}
103
104impl SessionRegistry {
105 /// `session.get_agents(session_id) -> { agents: [AgentRosterEntry] }`
106 /// (DOC-39 §5.4).
107 ///
108 /// Why: the principled, daemon-owned, EVICTION-SAFE replacement for the
109 /// client-side ring-buffer fold §5.4 originally acknowledged as a
110 /// time-boxed Phase-1 loan — see the module docs for why reading the
111 /// bounded ring directly (this endpoint's first cut) was itself still a
112 /// silent-data-loss bug, not a fix.
113 /// What: `-32007 session_not_found` if `id` is unknown. Otherwise
114 /// projects `SessionEntry::agents` (the always-retained per-agent
115 /// roster, in first-seen order) into one [`AgentRosterEntry`] per row. A
116 /// session with no tool activity yet returns an empty roster, not an
117 /// error — the same "empty means nothing yet" convention
118 /// `session.get_goals`/`session.get_transcript` use.
119 /// Test: `registry_agents::tests::get_agents_empty_session_returns_empty_roster`,
120 /// `registry_agents::tests::get_agents_running_tool_reports_running_state`,
121 /// `registry_agents::tests::get_agents_finished_tool_reports_idle_state`,
122 /// `registry_agents::tests::get_agents_distinguishes_same_named_concurrent_spawns`,
123 /// `registry_agents::tests::get_agents_survives_ring_eviction`,
124 /// `registry_agents::tests::get_agents_unknown_session_errors`.
125 pub fn get_agents(&self, id: &str) -> Result<Vec<AgentRosterEntry>, RpcError> {
126 let sessions = self.lock();
127 let entry = sessions
128 .get(id)
129 .ok_or_else(|| RpcError::session_not_found(id))?;
130 Ok(entry
131 .agents
132 .iter()
133 .map(|a| AgentRosterEntry {
134 agent_id: a.agent_id.clone(),
135 name: a.name.clone(),
136 model: None,
137 state: if a.running { STATE_RUNNING } else { STATE_IDLE }.to_string(),
138 task: None,
139 // #8235: the roster row's own list, as `todo_write` last
140 // replaced it.
141 todos: a.todos.clone(),
142 files_changed: Vec::new(),
143 })
144 .collect())
145 }
146}
147
148#[cfg(test)]
149mod tests {
150 use super::*;
151
152 /// A session with no recorded tool activity returns an empty roster, not
153 /// an error.
154 #[test]
155 fn get_agents_empty_session_returns_empty_roster() {
156 let registry = SessionRegistry::new();
157 let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
158
159 let roster = registry.get_agents(&session.id).unwrap();
160
161 assert!(roster.is_empty());
162 }
163
164 /// An agent whose most recent event is `ToolStarted` reports `"running"`.
165 #[test]
166 fn get_agents_running_tool_reports_running_state() {
167 let registry = SessionRegistry::new();
168 let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
169 registry
170 .record_tool_started(
171 &session.id,
172 "python-engineer",
173 "eng-1",
174 "bash",
175 "c1",
176 "cargo test",
177 )
178 .unwrap();
179
180 let roster = registry.get_agents(&session.id).unwrap();
181
182 assert_eq!(roster.len(), 1);
183 assert_eq!(roster[0].agent_id, "eng-1");
184 assert_eq!(roster[0].name, "python-engineer");
185 assert_eq!(roster[0].state, "running");
186 assert_eq!(roster[0].model, None);
187 assert_eq!(roster[0].task, None);
188 assert!(roster[0].todos.is_empty());
189 assert!(roster[0].files_changed.is_empty());
190 }
191
192 /// Once the started tool call finishes, that agent's state flips to
193 /// `"idle"`.
194 #[test]
195 fn get_agents_finished_tool_reports_idle_state() {
196 let registry = SessionRegistry::new();
197 let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
198 registry
199 .record_tool_started(&session.id, "pm", "pm-1", "bash", "c1", "echo hi")
200 .unwrap();
201 registry
202 .record_tool_finished(&session.id, "pm", "pm-1", "bash", "c1", true, "hi")
203 .unwrap();
204
205 let roster = registry.get_agents(&session.id).unwrap();
206
207 assert_eq!(roster.len(), 1);
208 assert_eq!(roster[0].state, "idle");
209 }
210
211 /// Two distinct `agent_id`s produce two roster rows, in first-seen order,
212 /// even when they share the same agent NAME — the DOC-39 AC-13 case this
213 /// endpoint exists to make queryable.
214 #[test]
215 fn get_agents_distinguishes_same_named_concurrent_spawns() {
216 let registry = SessionRegistry::new();
217 let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
218 registry
219 .record_tool_started(&session.id, "python-engineer", "spawn-a", "bash", "c1", "x")
220 .unwrap();
221 registry
222 .record_tool_started(&session.id, "python-engineer", "spawn-b", "bash", "c2", "y")
223 .unwrap();
224
225 let roster = registry.get_agents(&session.id).unwrap();
226
227 assert_eq!(roster.len(), 2);
228 assert_eq!(roster[0].agent_id, "spawn-a");
229 assert_eq!(roster[1].agent_id, "spawn-b");
230 assert!(roster.iter().all(|a| a.name == "python-engineer"));
231 }
232
233 /// THE code-critic HIGH this module's second design closes: an agent
234 /// whose `ToolStarted` has aged OUT of the (here, tiny) ring buffer must
235 /// still appear in `get_agents`, still `"running"` — the ring's bounded
236 /// capacity must never be able to make a still-running agent vanish from
237 /// the roster. Uses `SessionRegistry::with_capacity` (the same seam
238 /// `registry_tests.rs` uses for `ring_buffer_drops_oldest_when_full`) to
239 /// force eviction cheaply instead of pushing thousands of events.
240 #[test]
241 fn get_agents_survives_ring_eviction() {
242 let registry = SessionRegistry::with_capacity(2);
243 let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
244
245 // Agent A starts a tool call — its `ToolStarted` is recorded at some
246 // early `seq`.
247 registry
248 .record_tool_started(&session.id, "python-engineer", "agent-a", "bash", "c1", "x")
249 .unwrap();
250
251 // Agent B then starts and finishes enough tool calls to push A's
252 // `ToolStarted` out of the (capacity-2) ring buffer entirely.
253 for i in 0..5 {
254 let call_id = format!("b-{i}");
255 registry
256 .record_tool_started(&session.id, "engineer-b", "agent-b", "bash", &call_id, "y")
257 .unwrap();
258 registry
259 .record_tool_finished(
260 &session.id,
261 "engineer-b",
262 "agent-b",
263 "bash",
264 &call_id,
265 true,
266 "ok",
267 )
268 .unwrap();
269 }
270
271 // Sanity check: A's `ToolStarted` really is no longer in the replay
272 // — this test would be vacuous otherwise.
273 let replay = registry.replay(&session.id).unwrap();
274 assert!(
275 !replay.iter().any(|e| matches!(
276 &e.event,
277 crate::events::Event::ToolStarted { agent_id, .. } if agent_id == "agent-a"
278 )),
279 "test setup bug: agent-a's ToolStarted must have been evicted from the ring"
280 );
281
282 // THE assertion: agent-a still appears in the roster, still
283 // "running" — the always-retained map survived what the ring did not.
284 let roster = registry.get_agents(&session.id).unwrap();
285 let agent_a = roster
286 .iter()
287 .find(|a| a.agent_id == "agent-a")
288 .unwrap_or_else(|| panic!("agent-a must survive ring eviction: {roster:?}"));
289 assert_eq!(agent_a.state, "running");
290 assert_eq!(agent_a.name, "python-engineer");
291
292 let agent_b = roster.iter().find(|a| a.agent_id == "agent-b").unwrap();
293 assert_eq!(agent_b.state, "idle");
294 }
295
296 /// An unknown session must map to `-32007 session_not_found`.
297 #[test]
298 fn get_agents_unknown_session_errors() {
299 let registry = SessionRegistry::new();
300 let err = registry.get_agents("nope").unwrap_err();
301 assert_eq!(err.code, -32007);
302 }
303}