Skip to main content

trusty_code/task/
todo_store.rs

1//! Concrete [`TodoStore`](crate::tools::TodoStore) writing the `todo_write`
2//! tool's list onto one session's roster row (#8235).
3//!
4//! Why: `tools::checklist` must not depend on `session`, and the tool must not
5//! learn which session or agent it serves — the same layering, and the same
6//! reason, as `task::sink`'s `SessionToolEventSink` (see
7//! `agent_loop::sink`'s module docs). This is the glue: `task` is the
8//! daemon-execution layer that knows both halves.
9//! What: [`SessionTodoStore`] holds an `Arc<SessionRegistry>` plus the
10//! session id and the WRITER's `agent`/`agent_id`, so the tool's every write
11//! is attributed to the loop that registered it and cannot address another
12//! agent's list. A registry error becomes
13//! [`TodoError::Unavailable`](crate::tools::TodoError::Unavailable), which
14//! the tool reports to the model as a recoverable failure over an unchanged
15//! list.
16//! Test: `tests::*` — the tool-to-`session.get_agents` round trip #8235 asks
17//! for, asserted through the read path rather than the store's own state.
18
19use std::sync::Arc;
20
21use crate::events::TodoItem;
22use crate::session::SessionRegistry;
23use crate::tools::{TodoError, TodoStore};
24
25/// Writes one agent's checklist into one session's roster (#8235).
26///
27/// Why: see module docs.
28/// What: every field is fixed at construction — the tool passes only the
29/// list, so it can neither retarget the session nor forge another agent's
30/// identity.
31/// Test: `tests::tool_write_is_visible_through_get_agents`.
32pub struct SessionTodoStore {
33    registry: Arc<SessionRegistry>,
34    session_id: String,
35    agent: String,
36    agent_id: String,
37}
38
39impl SessionTodoStore {
40    /// Build a store targeting `session_id`, attributing writes to
41    /// `agent`/`agent_id`.
42    pub fn new(
43        registry: Arc<SessionRegistry>,
44        session_id: impl Into<String>,
45        agent: impl Into<String>,
46        agent_id: impl Into<String>,
47    ) -> Self {
48        Self {
49            registry,
50            session_id: session_id.into(),
51            agent: agent.into(),
52            agent_id: agent_id.into(),
53        }
54    }
55}
56
57impl TodoStore for SessionTodoStore {
58    /// Forward the validated list to `SessionRegistry::set_agent_todos`.
59    ///
60    /// Why: an `RpcError` here means the session went away mid-run, which the
61    /// model can act on (stop planning, finish) — so it is reported rather
62    /// than logged and swallowed. A swallowed failure would be the fail-open
63    /// shape #8235 forbids: a success over an unchanged list.
64    /// Test: `tests::a_vanished_session_is_reported_not_swallowed`.
65    fn replace(&self, todos: Vec<TodoItem>) -> Result<(), TodoError> {
66        self.registry
67            .set_agent_todos(&self.session_id, &self.agent, &self.agent_id, todos)
68            .map_err(|e| TodoError::Unavailable(e.message))
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use serde_json::json;
75
76    use super::*;
77    use crate::binding::ProjectBinding;
78    use crate::events::TodoStatus;
79    use crate::tools::{TodoWriteTool, ToolExecutor};
80
81    fn session() -> (Arc<SessionRegistry>, String) {
82        let registry = Arc::new(SessionRegistry::new());
83        let created = registry.create("t".to_string(), None, ProjectBinding::None);
84        (registry, created.id)
85    }
86
87    /// THE #8235 round trip: a `todo_write` call by the model is visible in
88    /// `session.get_agents`'s `todos` — asserted through the read path, not by
89    /// inspecting the tool or the store.
90    #[tokio::test]
91    async fn tool_write_is_visible_through_get_agents() {
92        let (registry, id) = session();
93        let tool = TodoWriteTool::new(Arc::new(SessionTodoStore::new(
94            Arc::clone(&registry),
95            &id,
96            "pm",
97            "pm-1",
98        )));
99
100        let result = tool
101            .execute(json!({"todos": [
102                {"content": "add the --json flag", "status": "completed"},
103                {"content": "add a test", "status": "in_progress"},
104                {"content": "add a changelog line", "status": "pending"}
105            ]}))
106            .await;
107
108        assert!(!result.is_error(), "{result:?}");
109        let roster = registry.get_agents(&id).expect("roster");
110        assert_eq!(roster.len(), 1);
111        assert_eq!(roster[0].agent_id, "pm-1");
112        let todos = &roster[0].todos;
113        assert_eq!(todos.len(), 3);
114        assert_eq!(todos[1].content, "add a test");
115        assert_eq!(todos[1].status, TodoStatus::InProgress);
116    }
117
118    /// A refused call leaves the previously stored list exactly as it was —
119    /// the fail-open check, asserted at the read path.
120    #[tokio::test]
121    async fn a_refused_call_leaves_the_stored_list_unchanged() {
122        let (registry, id) = session();
123        let tool = TodoWriteTool::new(Arc::new(SessionTodoStore::new(
124            Arc::clone(&registry),
125            &id,
126            "pm",
127            "pm-1",
128        )));
129        tool.execute(json!({"todos": [{"content": "plan", "status": "in_progress"}]}))
130            .await;
131
132        let refused = tool
133            .execute(json!({"todos": [
134                {"content": "a", "status": "in_progress"},
135                {"content": "b", "status": "in_progress"}
136            ]}))
137            .await;
138
139        assert!(refused.is_error());
140        let roster = registry.get_agents(&id).expect("roster");
141        assert_eq!(roster[0].todos.len(), 1);
142        assert_eq!(roster[0].todos[0].content, "plan");
143    }
144
145    /// A store whose session has gone reports the failure to the model rather
146    /// than returning success over a dropped write.
147    #[tokio::test]
148    async fn a_vanished_session_is_reported_not_swallowed() {
149        let registry = Arc::new(SessionRegistry::new());
150        let tool = TodoWriteTool::new(Arc::new(SessionTodoStore::new(
151            registry, "gone", "pm", "pm-1",
152        )));
153
154        let result = tool
155            .execute(json!({"todos": [{"content": "a", "status": "pending"}]}))
156            .await;
157
158        assert!(result.is_error(), "{result:?}");
159    }
160
161    /// A sub-agent's store writes its OWN roster row; the PM's plan is
162    /// untouched. This is the scope boundary #8235's dispatch asks to be
163    /// pinned: a delegated agent handed this tool cannot rewrite the PM's
164    /// checklist, because its store carries its own `agent_id`.
165    #[tokio::test]
166    async fn a_sub_agent_cannot_rewrite_the_pms_list() {
167        let (registry, id) = session();
168        let pm = TodoWriteTool::new(Arc::new(SessionTodoStore::new(
169            Arc::clone(&registry),
170            &id,
171            "pm",
172            "pm-1",
173        )));
174        let engineer = TodoWriteTool::new(Arc::new(SessionTodoStore::new(
175            Arc::clone(&registry),
176            &id,
177            "engineer",
178            "eng-1",
179        )));
180        pm.execute(json!({"todos": [{"content": "route the work", "status": "in_progress"}]}))
181            .await;
182
183        engineer
184            .execute(json!({"todos": [{"content": "write the code", "status": "in_progress"}]}))
185            .await;
186
187        let roster = registry.get_agents(&id).expect("roster");
188        let pm_row = roster
189            .iter()
190            .find(|a| a.agent_id == "pm-1")
191            .expect("pm row");
192        assert_eq!(pm_row.todos.len(), 1);
193        assert_eq!(pm_row.todos[0].content, "route the work");
194        let eng_row = roster
195            .iter()
196            .find(|a| a.agent_id == "eng-1")
197            .expect("engineer row");
198        assert_eq!(eng_row.todos[0].content, "write the code");
199    }
200}