Skip to main content

trusty_code/session/
registry_todos.rs

1//! `SessionRegistry::set_agent_todos` — the session checklist's write path
2//! (#8235). Split out of `registry.rs` for the same 500-SLOC-cap reason as
3//! `registry_events.rs`; this is a child module of `registry` (declared via
4//! `#[path = ...] mod todo_ops;`), so it shares full access to
5//! `SessionRegistry`'s private `lock`/`record` helpers and `SessionEntry`'s
6//! fields exactly as if these methods were still defined in that file.
7//!
8//! Why: DOC-39 §5.4 reserved `AgentRosterEntry.todos` and
9//! `session::registry_agents`'s own module docs recorded it as "always `[]` —
10//! no event or registry state tracks it today". This is that state. It lives
11//! on the roster row (`AgentRosterState.todos`) rather than on the
12//! `Transcript` where goal slots live, for three reasons: DOC-39 §4.5
13//! requires checklists to be PER-AGENT, the roster is the read path #8235
14//! names, and a `Transcript` only exists after the session's first `task.run`
15//! (see `registry_goals`'s "no transcript yet" error) whereas a roster row is
16//! created by the first attributed event of any agent.
17//! What: [`SessionRegistry::set_agent_todos`] find-or-inserts the writer's
18//! roster row, replaces its list whole, and then records
19//! `Event::TodosChanged` so an attached client learns of the change without
20//! polling. The write is keyed by `agent_id`, so two agents in one session
21//! own two lists and neither can rewrite the other's; two SESSIONS are
22//! already isolated by `SessionEntry`.
23//! Test: `tests::*`; `session::protocol_agents::tests::get_agents_reports_a_written_checklist`
24//! covers the RPC read path and `task::todo_store::tests::*` the tool round
25//! trip.
26
27use super::*;
28use crate::events::TodoItem;
29
30impl SessionRegistry {
31    /// Replace `agent_id`'s checklist in session `id`, then stream the change
32    /// (#8235).
33    ///
34    /// Why: the ONE write path onto the roster's `todos`, so the state and
35    /// the `Event::TodosChanged` that announces it can never disagree — a
36    /// second call site could update one without the other.
37    /// What: `Err(session_not_found)` if `id` is unknown;
38    /// `Err(invalid_argument)` for an empty `agent_id`, which has no roster
39    /// row to key on and would therefore make the write silently invisible.
40    /// Otherwise find-or-inserts the row (a new row starts `running: false` —
41    /// writing a checklist is not a tool call in flight), replaces `todos`
42    /// whole, releases the lock, and records the event. An existing row keeps
43    /// its `running` state and its `name` is refreshed, matching
44    /// `SessionEntry::note_agent_activity`'s last-writer-wins convention.
45    /// Test: `tests::set_agent_todos_writes_the_roster_row`,
46    /// `tests::set_agent_todos_replaces_the_whole_list`,
47    /// `tests::set_agent_todos_keeps_two_agents_lists_apart`,
48    /// `tests::set_agent_todos_keeps_two_sessions_lists_apart`,
49    /// `tests::set_agent_todos_streams_a_change_event`,
50    /// `tests::set_agent_todos_unknown_session_errors`,
51    /// `tests::set_agent_todos_empty_agent_id_errors`,
52    /// `tests::set_agent_todos_leaves_running_state_alone`.
53    pub fn set_agent_todos(
54        &self,
55        id: &str,
56        agent: &str,
57        agent_id: &str,
58        todos: Vec<TodoItem>,
59    ) -> Result<(), RpcError> {
60        if agent_id.is_empty() {
61            return Err(RpcError::invalid_argument(
62                "a checklist needs a non-empty agent_id to attribute it to".to_string(),
63            ));
64        }
65        {
66            let mut sessions = self.lock();
67            let entry = sessions
68                .get_mut(id)
69                .ok_or_else(|| RpcError::session_not_found(id))?;
70            match entry.agents.iter_mut().find(|a| a.agent_id == agent_id) {
71                Some(existing) => {
72                    existing.name = agent.to_string();
73                    existing.todos = todos.clone();
74                }
75                None => entry.agents.push(AgentRosterState {
76                    agent_id: agent_id.to_string(),
77                    name: agent.to_string(),
78                    running: false,
79                    todos: todos.clone(),
80                }),
81            }
82        }
83        self.record(
84            id,
85            Event::TodosChanged {
86                session_id: id.to_string(),
87                agent: agent.to_string(),
88                agent_id: agent_id.to_string(),
89                todos,
90            },
91        );
92        Ok(())
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99    use crate::events::TodoStatus;
100
101    /// `(content, status)` pairs as [`TodoItem`]s.
102    fn items(pairs: &[(&str, TodoStatus)]) -> Vec<TodoItem> {
103        pairs
104            .iter()
105            .map(|(content, status)| TodoItem {
106                content: (*content).to_string(),
107                status: *status,
108            })
109            .collect()
110    }
111
112    fn registry_with_session() -> (SessionRegistry, String) {
113        let registry = SessionRegistry::new();
114        let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
115        (registry, session.id)
116    }
117
118    /// A write on a session with no prior tool activity still lands: it mints
119    /// the roster row, so a checklist written before the first tool call is
120    /// not lost.
121    #[test]
122    fn set_agent_todos_writes_the_roster_row() {
123        let (registry, id) = registry_with_session();
124
125        registry
126            .set_agent_todos(
127                &id,
128                "pm",
129                "pm-1",
130                items(&[("add the flag", TodoStatus::InProgress)]),
131            )
132            .expect("write");
133
134        let roster = registry.get_agents(&id).expect("roster");
135        assert_eq!(roster.len(), 1);
136        assert_eq!(roster[0].agent_id, "pm-1");
137        assert_eq!(roster[0].todos.len(), 1);
138        assert_eq!(roster[0].todos[0].content, "add the flag");
139        assert_eq!(roster[0].todos[0].status, TodoStatus::InProgress);
140    }
141
142    /// The second write REPLACES the first list rather than appending to it —
143    /// the whole-list-replace semantics #8235 specifies.
144    #[test]
145    fn set_agent_todos_replaces_the_whole_list() {
146        let (registry, id) = registry_with_session();
147        registry
148            .set_agent_todos(
149                &id,
150                "pm",
151                "pm-1",
152                items(&[("a", TodoStatus::Pending), ("b", TodoStatus::Pending)]),
153            )
154            .expect("first write");
155
156        registry
157            .set_agent_todos(&id, "pm", "pm-1", items(&[("a", TodoStatus::Completed)]))
158            .expect("second write");
159
160        let roster = registry.get_agents(&id).expect("roster");
161        assert_eq!(roster[0].todos.len(), 1, "append, not replace");
162        assert_eq!(roster[0].todos[0].status, TodoStatus::Completed);
163    }
164
165    /// An empty list clears the checklist.
166    #[test]
167    fn set_agent_todos_empty_list_clears() {
168        let (registry, id) = registry_with_session();
169        registry
170            .set_agent_todos(&id, "pm", "pm-1", items(&[("a", TodoStatus::Pending)]))
171            .expect("write");
172
173        registry
174            .set_agent_todos(&id, "pm", "pm-1", Vec::new())
175            .expect("clear");
176
177        let roster = registry.get_agents(&id).expect("roster");
178        assert!(roster[0].todos.is_empty());
179    }
180
181    /// THE subagent boundary: a delegated agent writing its own checklist
182    /// leaves the PM's plan untouched, because the list is keyed by
183    /// `agent_id`.
184    #[test]
185    fn set_agent_todos_keeps_two_agents_lists_apart() {
186        let (registry, id) = registry_with_session();
187        registry
188            .set_agent_todos(
189                &id,
190                "pm",
191                "pm-1",
192                items(&[("route the work", TodoStatus::InProgress)]),
193            )
194            .expect("pm write");
195
196        registry
197            .set_agent_todos(
198                &id,
199                "engineer",
200                "eng-1",
201                items(&[("write the code", TodoStatus::Pending)]),
202            )
203            .expect("engineer write");
204
205        let roster = registry.get_agents(&id).expect("roster");
206        let pm = roster
207            .iter()
208            .find(|a| a.agent_id == "pm-1")
209            .expect("pm row");
210        let eng = roster
211            .iter()
212            .find(|a| a.agent_id == "eng-1")
213            .expect("engineer row");
214        assert_eq!(pm.todos.len(), 1);
215        assert_eq!(pm.todos[0].content, "route the work");
216        assert_eq!(eng.todos[0].content, "write the code");
217    }
218
219    /// Two concurrent sessions never see each other's lists — #8235's closure
220    /// condition, and the property trusty-memory's palace-scoped task slots
221    /// could not offer.
222    #[test]
223    fn set_agent_todos_keeps_two_sessions_lists_apart() {
224        let registry = SessionRegistry::new();
225        let a = registry.create("a".to_string(), None, crate::binding::ProjectBinding::None);
226        let b = registry.create("b".to_string(), None, crate::binding::ProjectBinding::None);
227        registry
228            .set_agent_todos(&a.id, "pm", "pm-1", items(&[("in a", TodoStatus::Pending)]))
229            .expect("write a");
230
231        registry
232            .set_agent_todos(&b.id, "pm", "pm-1", items(&[("in b", TodoStatus::Pending)]))
233            .expect("write b");
234
235        assert_eq!(
236            registry.get_agents(&a.id).expect("roster a")[0].todos[0].content,
237            "in a"
238        );
239        assert_eq!(
240            registry.get_agents(&b.id).expect("roster b")[0].todos[0].content,
241            "in b"
242        );
243    }
244
245    /// The write streams `Event::TodosChanged` carrying the same list, so an
246    /// attached client needs no follow-up read.
247    #[test]
248    fn set_agent_todos_streams_a_change_event() {
249        let (registry, id) = registry_with_session();
250
251        registry
252            .set_agent_todos(
253                &id,
254                "pm",
255                "pm-1",
256                items(&[("add a test", TodoStatus::InProgress)]),
257            )
258            .expect("write");
259
260        let replay = registry.replay(&id).expect("replay");
261        let streamed = replay
262            .iter()
263            .find_map(|e| match &e.event {
264                Event::TodosChanged {
265                    agent,
266                    agent_id,
267                    todos,
268                    ..
269                } => Some((agent.clone(), agent_id.clone(), todos.clone())),
270                _ => None,
271            })
272            .expect("a todos_changed event must be recorded");
273        assert_eq!(streamed.0, "pm");
274        assert_eq!(streamed.1, "pm-1");
275        assert_eq!(streamed.2[0].content, "add a test");
276    }
277
278    /// Writing a checklist must not report an agent as running — only a
279    /// `ToolStarted` does that.
280    #[test]
281    fn set_agent_todos_leaves_running_state_alone() {
282        let (registry, id) = registry_with_session();
283        registry
284            .record_tool_started(&id, "pm", "pm-1", "bash", "c1", "ls")
285            .expect("tool started");
286
287        registry
288            .set_agent_todos(&id, "pm", "pm-1", items(&[("a", TodoStatus::Pending)]))
289            .expect("write");
290
291        let roster = registry.get_agents(&id).expect("roster");
292        assert_eq!(
293            roster[0].state, "running",
294            "a checklist write must not clear an in-flight tool call"
295        );
296    }
297
298    /// An unknown session maps to `-32007 session_not_found`.
299    #[test]
300    fn set_agent_todos_unknown_session_errors() {
301        let registry = SessionRegistry::new();
302        let err = registry
303            .set_agent_todos("nope", "pm", "pm-1", Vec::new())
304            .expect_err("unknown session");
305        assert_eq!(err.code, -32007);
306    }
307
308    /// An empty `agent_id` is refused rather than silently dropped.
309    #[test]
310    fn set_agent_todos_empty_agent_id_errors() {
311        let (registry, id) = registry_with_session();
312
313        let err = registry
314            .set_agent_todos(&id, "pm", "", items(&[("a", TodoStatus::Pending)]))
315            .expect_err("empty agent_id");
316
317        assert!(
318            err.message.contains("agent_id"),
319            "not actionable: {}",
320            err.message
321        );
322        assert!(registry.get_agents(&id).expect("roster").is_empty());
323    }
324}