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//! - `todos`, `files_changed` — always `[]`. No event or registry state
49//! tracks either today; §5.4 lists them in the target result shape but
50//! they are net-new domain state, not a folding gap.
51//!
52//! `AgentSpawned`/`AgentStarted`/`AgentDone`/`AgentFailed` (DOC-39 AC-13)
53//! are NOT sources here even though their shape looks purpose-built for a
54//! roster: `events.rs`'s own docs and #2898's CHANGELOG entry record that
55//! none of them are emitted by any production call site yet, so keying off
56//! them would silently return an always-empty roster instead of the real,
57//! already-flowing tool-attribution activity `registry.rs::tool_attribution`
58//! sources from.
59//! Test: `registry_agents::tests::*`; `protocol_agents::tests::*` covers the
60//! RPC-level wiring.
61
62use serde::Serialize;
63
64use super::*;
65
66/// `state` value for an agent whose live roster row (`AgentRosterState`) is
67/// currently `running: true` — its last known event is an unmatched
68/// `ToolStarted`.
69const STATE_RUNNING: &str = "running";
70/// `state` value for an agent whose live roster row is `running: false` — no
71/// tool call is known to be in flight.
72const STATE_IDLE: &str = "idle";
73
74/// One entry in `session.get_agents`'s live roster (DOC-39 §5.4).
75///
76/// Why: the wire shape `session.get_agents` returns per agent — see the
77/// module docs for exactly which fields are read from the always-retained
78/// `SessionEntry::agents` state and which are deferred defaults.
79/// What: `agent_id` is the DOC-39 AC-13 stable per-spawn id; `name` is the
80/// human-readable agent name (`"pm"` for the root loop, an agent config name
81/// like `"python-engineer"` for a delegation). See module docs for
82/// `model`/`task`/`todos`/`files_changed`.
83/// Test: `registry_agents::tests::*`.
84#[derive(Debug, Clone, Serialize)]
85pub struct AgentRosterEntry {
86 pub agent_id: String,
87 pub name: String,
88 pub model: Option<String>,
89 pub state: String,
90 pub task: Option<String>,
91 pub todos: Vec<String>,
92 pub files_changed: Vec<String>,
93}
94
95impl SessionRegistry {
96 /// `session.get_agents(session_id) -> { agents: [AgentRosterEntry] }`
97 /// (DOC-39 §5.4).
98 ///
99 /// Why: the principled, daemon-owned, EVICTION-SAFE replacement for the
100 /// client-side ring-buffer fold §5.4 originally acknowledged as a
101 /// time-boxed Phase-1 loan — see the module docs for why reading the
102 /// bounded ring directly (this endpoint's first cut) was itself still a
103 /// silent-data-loss bug, not a fix.
104 /// What: `-32007 session_not_found` if `id` is unknown. Otherwise
105 /// projects `SessionEntry::agents` (the always-retained per-agent
106 /// roster, in first-seen order) into one [`AgentRosterEntry`] per row. A
107 /// session with no tool activity yet returns an empty roster, not an
108 /// error — the same "empty means nothing yet" convention
109 /// `session.get_goals`/`session.get_transcript` use.
110 /// Test: `registry_agents::tests::get_agents_empty_session_returns_empty_roster`,
111 /// `registry_agents::tests::get_agents_running_tool_reports_running_state`,
112 /// `registry_agents::tests::get_agents_finished_tool_reports_idle_state`,
113 /// `registry_agents::tests::get_agents_distinguishes_same_named_concurrent_spawns`,
114 /// `registry_agents::tests::get_agents_survives_ring_eviction`,
115 /// `registry_agents::tests::get_agents_unknown_session_errors`.
116 pub fn get_agents(&self, id: &str) -> Result<Vec<AgentRosterEntry>, RpcError> {
117 let sessions = self.lock();
118 let entry = sessions
119 .get(id)
120 .ok_or_else(|| RpcError::session_not_found(id))?;
121 Ok(entry
122 .agents
123 .iter()
124 .map(|a| AgentRosterEntry {
125 agent_id: a.agent_id.clone(),
126 name: a.name.clone(),
127 model: None,
128 state: if a.running { STATE_RUNNING } else { STATE_IDLE }.to_string(),
129 task: None,
130 todos: Vec::new(),
131 files_changed: Vec::new(),
132 })
133 .collect())
134 }
135}
136
137#[cfg(test)]
138mod tests {
139 use super::*;
140
141 /// A session with no recorded tool activity returns an empty roster, not
142 /// an error.
143 #[test]
144 fn get_agents_empty_session_returns_empty_roster() {
145 let registry = SessionRegistry::new();
146 let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
147
148 let roster = registry.get_agents(&session.id).unwrap();
149
150 assert!(roster.is_empty());
151 }
152
153 /// An agent whose most recent event is `ToolStarted` reports `"running"`.
154 #[test]
155 fn get_agents_running_tool_reports_running_state() {
156 let registry = SessionRegistry::new();
157 let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
158 registry
159 .record_tool_started(
160 &session.id,
161 "python-engineer",
162 "eng-1",
163 "bash",
164 "c1",
165 "cargo test",
166 )
167 .unwrap();
168
169 let roster = registry.get_agents(&session.id).unwrap();
170
171 assert_eq!(roster.len(), 1);
172 assert_eq!(roster[0].agent_id, "eng-1");
173 assert_eq!(roster[0].name, "python-engineer");
174 assert_eq!(roster[0].state, "running");
175 assert_eq!(roster[0].model, None);
176 assert_eq!(roster[0].task, None);
177 assert!(roster[0].todos.is_empty());
178 assert!(roster[0].files_changed.is_empty());
179 }
180
181 /// Once the started tool call finishes, that agent's state flips to
182 /// `"idle"`.
183 #[test]
184 fn get_agents_finished_tool_reports_idle_state() {
185 let registry = SessionRegistry::new();
186 let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
187 registry
188 .record_tool_started(&session.id, "pm", "pm-1", "bash", "c1", "echo hi")
189 .unwrap();
190 registry
191 .record_tool_finished(&session.id, "pm", "pm-1", "bash", "c1", true, "hi")
192 .unwrap();
193
194 let roster = registry.get_agents(&session.id).unwrap();
195
196 assert_eq!(roster.len(), 1);
197 assert_eq!(roster[0].state, "idle");
198 }
199
200 /// Two distinct `agent_id`s produce two roster rows, in first-seen order,
201 /// even when they share the same agent NAME — the DOC-39 AC-13 case this
202 /// endpoint exists to make queryable.
203 #[test]
204 fn get_agents_distinguishes_same_named_concurrent_spawns() {
205 let registry = SessionRegistry::new();
206 let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
207 registry
208 .record_tool_started(&session.id, "python-engineer", "spawn-a", "bash", "c1", "x")
209 .unwrap();
210 registry
211 .record_tool_started(&session.id, "python-engineer", "spawn-b", "bash", "c2", "y")
212 .unwrap();
213
214 let roster = registry.get_agents(&session.id).unwrap();
215
216 assert_eq!(roster.len(), 2);
217 assert_eq!(roster[0].agent_id, "spawn-a");
218 assert_eq!(roster[1].agent_id, "spawn-b");
219 assert!(roster.iter().all(|a| a.name == "python-engineer"));
220 }
221
222 /// THE code-critic HIGH this module's second design closes: an agent
223 /// whose `ToolStarted` has aged OUT of the (here, tiny) ring buffer must
224 /// still appear in `get_agents`, still `"running"` — the ring's bounded
225 /// capacity must never be able to make a still-running agent vanish from
226 /// the roster. Uses `SessionRegistry::with_capacity` (the same seam
227 /// `registry_tests.rs` uses for `ring_buffer_drops_oldest_when_full`) to
228 /// force eviction cheaply instead of pushing thousands of events.
229 #[test]
230 fn get_agents_survives_ring_eviction() {
231 let registry = SessionRegistry::with_capacity(2);
232 let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
233
234 // Agent A starts a tool call — its `ToolStarted` is recorded at some
235 // early `seq`.
236 registry
237 .record_tool_started(&session.id, "python-engineer", "agent-a", "bash", "c1", "x")
238 .unwrap();
239
240 // Agent B then starts and finishes enough tool calls to push A's
241 // `ToolStarted` out of the (capacity-2) ring buffer entirely.
242 for i in 0..5 {
243 let call_id = format!("b-{i}");
244 registry
245 .record_tool_started(&session.id, "engineer-b", "agent-b", "bash", &call_id, "y")
246 .unwrap();
247 registry
248 .record_tool_finished(
249 &session.id,
250 "engineer-b",
251 "agent-b",
252 "bash",
253 &call_id,
254 true,
255 "ok",
256 )
257 .unwrap();
258 }
259
260 // Sanity check: A's `ToolStarted` really is no longer in the replay
261 // — this test would be vacuous otherwise.
262 let replay = registry.replay(&session.id).unwrap();
263 assert!(
264 !replay.iter().any(|e| matches!(
265 &e.event,
266 crate::events::Event::ToolStarted { agent_id, .. } if agent_id == "agent-a"
267 )),
268 "test setup bug: agent-a's ToolStarted must have been evicted from the ring"
269 );
270
271 // THE assertion: agent-a still appears in the roster, still
272 // "running" — the always-retained map survived what the ring did not.
273 let roster = registry.get_agents(&session.id).unwrap();
274 let agent_a = roster
275 .iter()
276 .find(|a| a.agent_id == "agent-a")
277 .unwrap_or_else(|| panic!("agent-a must survive ring eviction: {roster:?}"));
278 assert_eq!(agent_a.state, "running");
279 assert_eq!(agent_a.name, "python-engineer");
280
281 let agent_b = roster.iter().find(|a| a.agent_id == "agent-b").unwrap();
282 assert_eq!(agent_b.state, "idle");
283 }
284
285 /// An unknown session must map to `-32007 session_not_found`.
286 #[test]
287 fn get_agents_unknown_session_errors() {
288 let registry = SessionRegistry::new();
289 let err = registry.get_agents("nope").unwrap_err();
290 assert_eq!(err.code, -32007);
291 }
292}