Skip to main content

trusty_code/tools/
checklist.rs

1//! The `todo_write` tool — the model-facing write path onto a session's
2//! per-agent checklist (#8235).
3//!
4//! Why: the roster's `todos` field (DOC-39 §5.4, `session::registry_agents`)
5//! was reserved and always empty because nothing could write it, so a
6//! multi-step task had no in-flight plan anywhere. The #8235 parity capture
7//! is the cost: asked for a flag, a test and a changelog line, the agent
8//! landed the flag and went idle with the other two silently dropped. Goal
9//! slots (`tools::goals`) are not that mechanism — five fixed slots, no
10//! per-step state, and their own description tells the model they are "NOT a
11//! todo list".
12//! What: [`TodoWriteTool`] validates the model's whole-list argument and hands
13//! it to a [`TodoStore`]. The store trait lives HERE, in the tools layer, and
14//! `task::todo_store::SessionTodoStore` implements it — the same layering
15//! `agent_loop::sink::ToolEventSink` uses, so `tools` never depends upward on
16//! `session`/`task`. Registered on the daemon-session registry only
17//! (`task::executor::run_and_record`), exactly like `set_goal`/`clear_goal`.
18//!
19//! **Whole-list replace, not a patch.** #8235's own closure condition names
20//! "a whole-list-replace call", and the token arithmetic agrees: a patch
21//! protocol needs stable per-item ids the model must carry across
22//! compaction, plus a companion read tool to recover them after a reset —
23//! two calls and a stale-id failure mode to save a handful of tokens on a
24//! list that is rarely longer than ten short lines.
25//! Test: `tests::*` (this file's sibling `checklist_tests.rs`) for schema,
26//! validation and store dispatch; `task::todo_store::tests::*` for the
27//! round trip out through `session.get_agents`.
28
29use std::sync::Arc;
30
31use async_trait::async_trait;
32use serde::Deserialize;
33use serde_json::{Value, json};
34use thiserror::Error;
35
36use crate::events::{TodoItem, TodoStatus};
37use crate::tools::traits::{ToolExecutor, ToolResult};
38
39/// The `todo_write` tool's registered/advertised name.
40///
41/// Why: snake_case per this crate's tool-naming convention, but otherwise
42/// Claude Code's `TodoWrite` verbatim — the model's prior on that name is
43/// worth more than a novel one like `set_todos`.
44pub const TODO_WRITE_TOOL_NAME: &str = "todo_write";
45
46/// Hard ceiling on a single checklist's length.
47///
48/// Why: the list is retained for the life of the session and re-serialised
49/// into every roster read and change event, so an unbounded list is
50/// unbounded session memory and unbounded wire payload. Twenty steps is well
51/// past the point where a plan stops being a plan.
52pub const MAX_TODOS: usize = 20;
53
54/// Why a `todo_write` call was refused (#8235).
55///
56/// Why: every variant is text the MODEL reads and must be able to act on, so
57/// each names the offending item and the fix rather than merely reporting
58/// that something was wrong. Kept as a `thiserror` enum (not a bare `String`)
59/// so `parse_todos` is unit-testable against the specific refusal.
60/// What: the first five are validation; [`Self::Unavailable`] is the store
61/// refusing the write (in practice: the session ended mid-run).
62/// Test: `tests::rejects_unknown_status`, `tests::rejects_empty_content`,
63/// `tests::rejects_two_in_progress`, `tests::rejects_more_than_max_todos`,
64/// `tests::store_failure_is_a_recoverable_tool_error`.
65#[derive(Debug, Error, PartialEq, Eq)]
66pub enum TodoError {
67    /// An item's `content` was empty or whitespace only.
68    #[error(
69        "todo {index} has empty content — every step needs a short description of the work, \
70         e.g. \"add the --json flag\""
71    )]
72    EmptyContent { index: usize },
73    /// An item's `status` was not one of the three known states.
74    #[error(
75        "todo {index} has unknown status {status:?} — use \"pending\", \"in_progress\" or \
76         \"completed\""
77    )]
78    UnknownStatus { index: usize, status: String },
79    /// More than one item claimed `in_progress`.
80    #[error(
81        "{count} todos are marked in_progress — at most one step may be in_progress at a time; \
82         mark the others pending or completed and send the whole list again"
83    )]
84    MultipleInProgress { count: usize },
85    /// The list was longer than [`MAX_TODOS`].
86    #[error(
87        "{count} todos exceeds the limit of {max} — keep the checklist to the steps of the \
88         task in hand, not every eventual follow-up",
89        max = MAX_TODOS
90    )]
91    TooManyItems { count: usize },
92    /// The store could not accept the write; nothing was changed.
93    #[error("the checklist was not stored ({0}) — the list is unchanged")]
94    Unavailable(String),
95}
96
97/// Where a validated checklist is written (#8235).
98///
99/// Why: the seam that keeps `tools` from depending on `session` — the only
100/// implementation, `task::todo_store::SessionTodoStore`, holds the
101/// `Arc<SessionRegistry>` and the writing agent's identity, so this tool
102/// never learns which session or agent it serves. Same rationale as
103/// `agent_loop::sink::ToolEventSink`'s module docs.
104/// What: [`Self::replace`] is all-or-nothing — it either stores `todos`
105/// whole or returns [`TodoError::Unavailable`] having changed nothing. Not
106/// `async`: `SessionRegistry`'s writes are synchronous.
107/// Test: `task::todo_store::tests::*` (the real store);
108/// `tests::*` (a recording double).
109pub trait TodoStore: Send + Sync {
110    /// Replace the calling agent's whole checklist with `todos`.
111    fn replace(&self, todos: Vec<TodoItem>) -> Result<(), TodoError>;
112}
113
114/// One raw checklist item as the model sent it.
115///
116/// Why: `status` is taken as a `String`, not as [`TodoStatus`], on purpose —
117/// a serde enum would fail the WHOLE argument deserialisation with
118/// "unknown variant" and no item index, and #8235 requires a refusal the
119/// model can act on. [`parse_todos`] converts it and names the bad item.
120#[derive(Debug, Deserialize)]
121struct RawTodo {
122    content: String,
123    status: String,
124}
125
126/// Parsed `todo_write` arguments.
127#[derive(Debug, Deserialize)]
128struct TodoWriteArgs {
129    todos: Vec<RawTodo>,
130}
131
132/// Validate and convert the model's raw list into storable [`TodoItem`]s.
133///
134/// Why: validation is a pure function so every refusal has a test that needs
135/// no store, no session and no agent loop — and so `execute` cannot
136/// accidentally write a partially-validated list: this returns `Err` before
137/// the store is ever touched (#8235's fail-open check).
138/// What: trims each `content` and rejects an empty one; maps `status`
139/// through [`TodoStatus`]; rejects a list longer than [`MAX_TODOS`] or with
140/// more than one `in_progress`. An EMPTY list is valid and means "clear the
141/// checklist". The length check runs first so an over-long list is reported
142/// as such rather than as whichever item happens to be malformed.
143/// Test: `tests::accepts_a_valid_list`, `tests::accepts_an_empty_list`,
144/// `tests::rejects_unknown_status`, `tests::rejects_empty_content`,
145/// `tests::rejects_two_in_progress`, `tests::rejects_more_than_max_todos`.
146fn parse_todos(raw: Vec<RawTodo>) -> Result<Vec<TodoItem>, TodoError> {
147    if raw.len() > MAX_TODOS {
148        return Err(TodoError::TooManyItems { count: raw.len() });
149    }
150    let mut items = Vec::with_capacity(raw.len());
151    for (i, item) in raw.into_iter().enumerate() {
152        let content = item.content.trim();
153        if content.is_empty() {
154            return Err(TodoError::EmptyContent { index: i });
155        }
156        let status = parse_status(&item.status).ok_or_else(|| TodoError::UnknownStatus {
157            index: i,
158            status: item.status.clone(),
159        })?;
160        items.push(TodoItem {
161            content: content.to_string(),
162            status,
163        });
164    }
165    let in_progress = items
166        .iter()
167        .filter(|t| t.status == TodoStatus::InProgress)
168        .count();
169    if in_progress > 1 {
170        return Err(TodoError::MultipleInProgress { count: in_progress });
171    }
172    Ok(items)
173}
174
175/// Map a wire status string onto [`TodoStatus`], or `None` if unknown.
176fn parse_status(raw: &str) -> Option<TodoStatus> {
177    match raw {
178        "pending" => Some(TodoStatus::Pending),
179        "in_progress" => Some(TodoStatus::InProgress),
180        "completed" => Some(TodoStatus::Completed),
181        _ => None,
182    }
183}
184
185/// One line of feedback describing the stored list.
186///
187/// Why: the model gets a confirmation it can check against what it sent
188/// without the tool echoing the whole list back into context on every call.
189/// What: counts per state, plus the `in_progress` step's own text when there
190/// is one, since that is the single fact the next turn acts on.
191/// Test: `tests::success_text_names_the_in_progress_step`,
192/// `tests::success_text_reports_an_empty_list`.
193fn summarise(todos: &[TodoItem]) -> String {
194    if todos.is_empty() {
195        return "Checklist cleared.".to_string();
196    }
197    let count = |s: TodoStatus| todos.iter().filter(|t| t.status == s).count();
198    let mut out = format!(
199        "Checklist updated: {} of {} completed, {} pending.",
200        count(TodoStatus::Completed),
201        todos.len(),
202        count(TodoStatus::Pending)
203    );
204    if let Some(active) = todos
205        .iter()
206        .find(|t| t.status == TodoStatus::InProgress)
207        .map(|t| t.content.as_str())
208    {
209        out.push_str(&format!(" In progress: {active}"));
210    }
211    out
212}
213
214/// `ToolExecutor` for `todo_write` (#8235).
215///
216/// Why: see module docs.
217/// What: holds the [`TodoStore`] the run's registry was built with; `execute`
218/// validates then writes, and every failure path returns a recoverable
219/// `ToolResult::err` — never a panic, never a success over an unchanged list.
220/// Test: `tests::*`.
221pub struct TodoWriteTool {
222    store: Arc<dyn TodoStore>,
223}
224
225impl TodoWriteTool {
226    /// Construct against the session's checklist store.
227    pub fn new(store: Arc<dyn TodoStore>) -> Self {
228        Self { store }
229    }
230}
231
232#[async_trait]
233impl ToolExecutor for TodoWriteTool {
234    fn name(&self) -> &str {
235        TODO_WRITE_TOOL_NAME
236    }
237
238    /// JSON schema for `todo_write`.
239    ///
240    /// Why: the description is the only place the model reliably reads about
241    /// this tool — `task::executor`'s delegating path scopes the system
242    /// prompt to the agent card's own `tcode_tools` and this tool is not one
243    /// of them, exactly as `set_goal`/`clear_goal` are not. So the "when to
244    /// use it" rule lives here, kept to three sentences.
245    /// What: `todos` (array of `{content, status}`, required). `status` is
246    /// declared as an enum for the model's benefit; `parse_todos` re-checks
247    /// it, because a loose schema validator accepting a bad value must still
248    /// produce an indexed refusal rather than a serde error.
249    /// Test: `tests::schema_declares_todos_and_the_three_statuses`.
250    fn schema(&self) -> Value {
251        json!({
252            "type": "function",
253            "function": {
254                "name": TODO_WRITE_TOOL_NAME,
255                "description": "Track the steps of a multi-step task as a checklist. Call it once when you plan the work, then again the moment a step starts or finishes, so the list always shows what is done and what remains. Send the WHOLE list every time — it replaces the stored one — and keep at most one step in_progress.",
256                "parameters": {
257                    "type": "object",
258                    "properties": {
259                        "todos": {
260                            "type": "array",
261                            "description": "The complete checklist, in the order the steps should happen. An empty array clears it.",
262                            "items": {
263                                "type": "object",
264                                "properties": {
265                                    "content": {
266                                        "type": "string",
267                                        "description": "The step, as a short imperative phrase."
268                                    },
269                                    "status": {
270                                        "type": "string",
271                                        "enum": ["pending", "in_progress", "completed"],
272                                        "description": "pending = not started; in_progress = being worked on now (at most one); completed = done."
273                                    }
274                                },
275                                "required": ["content", "status"],
276                                "additionalProperties": false
277                            }
278                        }
279                    },
280                    "required": ["todos"],
281                    "additionalProperties": false
282                }
283            }
284        })
285    }
286
287    /// Validate the model's whole list, then replace the stored one.
288    ///
289    /// Why: ordered validate-then-write so no refusal can leave a partially
290    /// applied list behind — #8235's fail-open check.
291    /// What: a malformed argument shape, any [`TodoError`] from
292    /// [`parse_todos`], and a store refusal each become a recoverable
293    /// `ToolResult::err` carrying the model-actionable text.
294    /// Test: `tests::valid_call_reaches_the_store`,
295    /// `tests::rejected_call_never_reaches_the_store`,
296    /// `tests::malformed_args_are_a_recoverable_error`,
297    /// `tests::store_failure_is_a_recoverable_tool_error`.
298    async fn execute(&self, args: Value) -> ToolResult {
299        let parsed: TodoWriteArgs = match serde_json::from_value(args) {
300            Ok(p) => p,
301            Err(e) => {
302                return ToolResult::err(format!(
303                    "todo_write arguments did not match the expected shape ({e}). Pass \
304                     'todos' as an array of objects, each with a 'content' string and a \
305                     'status' of \"pending\", \"in_progress\" or \"completed\"."
306                ));
307            }
308        };
309        let todos = match parse_todos(parsed.todos) {
310            Ok(t) => t,
311            Err(e) => return ToolResult::err(e.to_string()),
312        };
313        let summary = summarise(&todos);
314        match self.store.replace(todos) {
315            Ok(()) => ToolResult::ok(summary),
316            Err(e) => ToolResult::err(e.to_string()),
317        }
318    }
319}
320
321#[cfg(test)]
322#[path = "checklist_tests.rs"]
323mod tests;