返回 CodeWhale
todo.rs
根目录 / crates / engine / src / tools / todo.rs
1 //! Todo list tool and supporting data structures.
2
3 use std::sync::Arc;
4 use tokio::sync::Mutex;
5
6 use async_trait::async_trait;
7 use serde::{Deserialize, Serialize};
8 use serde_json::json;
9
10 use crate::tools::spec::{
11 ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec,
12 };
13
14 // === Types ===
15
16 /// Status for a todo item.
17 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
18 #[serde(rename_all = "snake_case")]
19 pub enum TodoStatus {
20 Pending,
21 InProgress,
22 Completed,
23 #[serde(alias = "canceled")]
24 Cancelled,
25 }
26
27 impl TodoStatus {
28 pub fn as_str(self) -> &'static str {
29 match self {
30 TodoStatus::Pending => "pending",
31 TodoStatus::InProgress => "in_progress",
32 TodoStatus::Completed => "completed",
33 TodoStatus::Cancelled => "cancelled",
34 }
35 }
36
37 /// Parse a string into a todo status.
38 #[must_use]
39 pub fn parse(value: &str) -> Option<Self> {
40 match value.trim().to_lowercase().as_str() {
41 "pending" => Some(TodoStatus::Pending),
42 "in_progress" | "inprogress" | "in-progress" | "in progress" => {
43 Some(TodoStatus::InProgress)
44 }
45 "completed" | "complete" | "done" => Some(TodoStatus::Completed),
46 "cancelled" | "canceled" => Some(TodoStatus::Cancelled),
47 _ => None,
48 }
49 }
50
51 /// Whether this item has reached a terminal outcome. Cancellation settles
52 /// work without misreporting it as successful completion.
53 #[must_use]
54 pub fn is_settled(self) -> bool {
55 matches!(self, TodoStatus::Completed | TodoStatus::Cancelled)
56 }
57 }
58
59 /// A single todo item.
60 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
61 pub struct TodoItem {
62 pub id: u32,
63 pub content: String,
64 pub status: TodoStatus,
65 }
66
67 /// Snapshot of a todo list for display or serialization.
68 #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
69 pub struct TodoListSnapshot {
70 #[serde(default, skip_serializing_if = "Vec::is_empty")]
71 pub items: Vec<TodoItem>,
72 #[serde(default)]
73 pub completion_pct: u8,
74 #[serde(default, skip_serializing_if = "Option::is_none")]
75 pub in_progress_id: Option<u32>,
76 }
77
78 impl TodoListSnapshot {
79 #[must_use]
80 pub fn is_empty(&self) -> bool {
81 self.items.is_empty()
82 }
83 }
84
85 /// Mutable list of todo items with helper operations.
86 #[derive(Debug, Clone, Default)]
87 pub struct TodoList {
88 items: Vec<TodoItem>,
89 next_id: u32,
90 }
91
92 impl TodoList {
93 /// Create an empty todo list.
94 #[must_use]
95 pub fn new() -> Self {
96 Self {
97 items: Vec::new(),
98 next_id: 1,
99 }
100 }
101
102 /// Return a snapshot of the list with computed metrics.
103 #[must_use]
104 pub fn snapshot(&self) -> TodoListSnapshot {
105 TodoListSnapshot {
106 items: self.items.clone(),
107 completion_pct: self.completion_percentage(),
108 in_progress_id: self.in_progress_id(),
109 }
110 }
111
112 /// Rebuild a mutable list from a persisted snapshot.
113 ///
114 /// Derived snapshot fields are deliberately recomputed. IDs and the
115 /// single-in-progress invariant are validated before any live state is
116 /// replaced, so malformed session data cannot leave a half-restored list.
117 pub fn from_snapshot(snapshot: &TodoListSnapshot) -> Result<Self, String> {
118 let mut seen = std::collections::HashSet::with_capacity(snapshot.items.len());
119 let mut in_progress_count = 0usize;
120 let mut max_id = 0u32;
121 let mut items = Vec::with_capacity(snapshot.items.len());
122
123 for item in &snapshot.items {
124 if item.id == 0 {
125 return Err("To-do item IDs must be greater than zero".to_string());
126 }
127 if !seen.insert(item.id) {
128 return Err(format!("Duplicate To-do item ID {}", item.id));
129 }
130 if item.status == TodoStatus::InProgress {
131 in_progress_count += 1;
132 if in_progress_count > 1 {
133 return Err("Only one To-do item may be in progress".to_string());
134 }
135 }
136 max_id = max_id.max(item.id);
137 items.push(TodoItem {
138 id: item.id,
139 content: item.content.clone(),
140 status: item.status,
141 });
142 }
143
144 let next_id = if items.is_empty() {
145 1
146 } else {
147 max_id
148 .checked_add(1)
149 .ok_or_else(|| "To-do item IDs are exhausted".to_string())?
150 };
151 Ok(Self { items, next_id })
152 }
153
154 /// Add a new todo item.
155 pub fn add(&mut self, content: String, status: TodoStatus) -> TodoItem {
156 let status = match status {
157 TodoStatus::InProgress => {
158 self.set_single_in_progress(None);
159 TodoStatus::InProgress
160 }
161 other => other,
162 };
163
164 let item = TodoItem {
165 id: self.next_id,
166 content,
167 status,
168 };
169 self.next_id += 1;
170 self.items.push(item.clone());
171 item
172 }
173
174 /// Compute completion percentage for the list.
175 #[must_use]
176 pub fn completion_percentage(&self) -> u8 {
177 if self.items.is_empty() {
178 return 0;
179 }
180 let total = self.items.len();
181 let settled = self
182 .items
183 .iter()
184 .filter(|item| item.status.is_settled())
185 .count();
186 let percent = settled.saturating_mul(100);
187 let percent = (percent + total / 2) / total;
188 u8::try_from(percent).unwrap_or(u8::MAX)
189 }
190
191 /// Return the id of the in-progress item, if any.
192 #[must_use]
193 pub fn in_progress_id(&self) -> Option<u32> {
194 self.items
195 .iter()
196 .find(|item| item.status == TodoStatus::InProgress)
197 .map(|item| item.id)
198 }
199
200 /// Clear all todo items.
201 pub fn clear(&mut self) {
202 self.items.clear();
203 self.next_id = 1;
204 }
205
206 fn set_single_in_progress(&mut self, allow_id: Option<u32>) {
207 for item in &mut self.items {
208 if Some(item.id) != allow_id && item.status == TodoStatus::InProgress {
209 item.status = TodoStatus::Pending;
210 }
211 }
212 }
213 }
214
215 // === TodoWriteTool - ToolSpec implementation ===
216
217 /// Shared reference to a `TodoList` for use across tools
218 pub type SharedTodoList = Arc<Mutex<TodoList>>;
219
220 /// Create a new shared `TodoList`
221 pub fn new_shared_todo_list() -> SharedTodoList {
222 Arc::new(Mutex::new(TodoList::new()))
223 }
224
225 const CANONICAL_WORK_SURFACE: &str = "work";
226 const CANONICAL_PROGRESS_TOOL: &str = "todo_write";
227 const DURABLE_WORK_OWNER: &str = "fleet_workflow_ledger";
228
229 /// Tool for writing and updating the todo list
230 pub struct TodoWriteTool {
231 todo_list: SharedTodoList,
232 }
233
234 impl TodoWriteTool {
235 /// Canonical model-facing progress surface (#4132).
236 pub fn new(todo_list: SharedTodoList) -> Self {
237 Self { todo_list }
238 }
239 }
240
241 #[async_trait]
242 impl ToolSpec for TodoWriteTool {
243 fn name(&self) -> &'static str {
244 CANONICAL_PROGRESS_TOOL
245 }
246
247 fn description(&self) -> &'static str {
248 "Replace the To-do list the user watches. For any task with three or more steps or more than one file, write the list before you start, keep exactly one item in_progress, and mark items done as you finish them. Skip it only for a single quick answer or edit."
249 }
250
251 fn input_schema(&self) -> serde_json::Value {
252 json!({
253 "type": "object",
254 "properties": {
255 "todos": {
256 "type": "array",
257 "description": "The complete list of To-do items. This replaces the existing list.",
258 "items": {
259 "type": "object",
260 "properties": {
261 "content": {
262 "type": "string",
263 "description": "The task description"
264 },
265 "status": {
266 "type": "string",
267 "enum": ["pending", "in_progress", "completed", "cancelled"],
268 "description": "Task status"
269 }
270 },
271 "required": ["content", "status"]
272 }
273 }
274 },
275 "required": ["todos"]
276 })
277 }
278
279 fn capabilities(&self) -> Vec<ToolCapability> {
280 Vec::new()
281 }
282
283 fn is_read_only_for(&self, _input: &serde_json::Value) -> bool {
284 // This mutates only the caller's in-memory progress list. Sub-agent
285 // runtimes allocate a fresh list per child, so it cannot touch the
286 // workspace, Git, remote services, or a parent/sibling's state. Treat
287 // it as bounded agent-owned state for read-only authority envelopes.
288 true
289 }
290
291 fn approval_requirement(&self) -> ApprovalRequirement {
292 ApprovalRequirement::Auto
293 }
294
295 async fn execute(
296 &self,
297 input: serde_json::Value,
298 context: &ToolContext,
299 ) -> Result<ToolResult, ToolError> {
300 let todos = input
301 .get("todos")
302 .and_then(|v| v.as_array())
303 .ok_or_else(|| ToolError::invalid_input("Missing or invalid 'todos' array"))?;
304
305 let in_progress: Vec<usize> = todos
306 .iter()
307 .enumerate()
308 .filter(|(_, item)| {
309 item.get("status")
310 .and_then(|v| v.as_str())
311 .and_then(TodoStatus::parse)
312 == Some(TodoStatus::InProgress)
313 })
314 .map(|(index, _)| index + 1)
315 .collect();
316 if in_progress.len() > 1 {
317 return Err(ToolError::invalid_input(format!(
318 "todo_write allows exactly one in_progress item; items {} are all in_progress. \
319 Keep the one you are working on in_progress and mark the others pending or completed.",
320 in_progress
321 .iter()
322 .map(usize::to_string)
323 .collect::<Vec<_>>()
324 .join(", ")
325 )));
326 }
327
328 let mut list = TodoList::new();
329
330 for item in todos {
331 let content = item
332 .get("content")
333 .and_then(|v| v.as_str())
334 .ok_or_else(|| ToolError::invalid_input("Todo item missing 'content'"))?;
335
336 let status = match item.get("status").and_then(|v| v.as_str()) {
337 Some(raw) => TodoStatus::parse(raw).ok_or_else(|| {
338 // #5123-class: unknown statuses used to silently coerce to
339 // pending on the canonical progress surface.
340 ToolError::invalid_input(format!(
341 "unknown todo status '{raw}'; expected pending, in_progress, \
342 completed, or cancelled"
343 ))
344 })?,
345 None => TodoStatus::Pending,
346 };
347
348 list.add(content.to_string(), status);
349 }
350
351 let snapshot = publish_todo_snapshot(
352 context,
353 &self.todo_list,
354 CANONICAL_PROGRESS_TOOL,
355 list.snapshot(),
356 )
357 .await?;
358 let result = serde_json::to_string_pretty(&snapshot).unwrap_or_else(|_| "{}".to_string());
359
360 Ok(ToolResult::success(format!(
361 "Todo list updated ({} items, {}% settled)\n{}",
362 snapshot.items.len(),
363 snapshot.completion_pct,
364 result
365 ))
366 .with_metadata(work_progress_metadata(&snapshot)))
367 }
368 }
369
370 async fn publish_todo_snapshot(
371 context: &ToolContext,
372 todo_list: &SharedTodoList,
373 tool_name: &str,
374 desired: TodoListSnapshot,
375 ) -> Result<TodoListSnapshot, ToolError> {
376 if let Some(work) = context.runtime.work.as_ref()
377 && work.matches_todos(todo_list)
378 {
379 return work
380 .apply_todo_update(&context.state_namespace, tool_name, &desired)
381 .await
382 .map_err(ToolError::execution_failed);
383 }
384 *todo_list.lock().await =
385 TodoList::from_snapshot(&desired).map_err(ToolError::execution_failed)?;
386 Ok(desired)
387 }
388
389 fn work_progress_metadata(snapshot: &TodoListSnapshot) -> serde_json::Value {
390 let items = snapshot
391 .items
392 .iter()
393 .map(|item| {
394 json!({
395 "id": item.id,
396 "content": item.content,
397 "status": item.status.as_str(),
398 })
399 })
400 .collect::<Vec<_>>();
401 json!({
402 "canonical_tool": CANONICAL_PROGRESS_TOOL,
403 "work_surface": {
404 "canonical": CANONICAL_WORK_SURFACE,
405 "model_visible": true,
406 "durable_owner": DURABLE_WORK_OWNER,
407 "progress_key": "task_updates.checklist"
408 },
409 "task_updates": {
410 "checklist": {
411 "items": items,
412 "completion_pct": snapshot.completion_pct,
413 "in_progress_id": snapshot.in_progress_id,
414 "updated_at": null
415 }
416 }
417 })
418 }
419
420 #[cfg(test)]
421 mod tests {
422 #[test]
423 fn todo_write_is_bounded_agent_owned_state_for_read_only_envelopes() {
424 let tool = super::TodoWriteTool::new(super::new_shared_todo_list());
425 assert!(crate::tools::spec::ToolSpec::is_read_only_for(
426 &tool,
427 &serde_json::json!({
428 "todos": [{"content": "private evidence note", "status": "pending"}]
429 })
430 ));
431 assert!(
432 !crate::tools::spec::ToolSpec::capabilities(&tool)
433 .contains(&crate::tools::spec::ToolCapability::WritesFiles),
434 "todo_write changes only the in-memory progress list"
435 );
436 assert_eq!(
437 crate::tools::spec::ToolSpec::approval_requirement(&tool),
438 crate::tools::spec::ApprovalRequirement::Auto
439 );
440 }
441
442 use super::*;
443
444 #[test]
445 fn cancelled_is_a_terminal_round_trippable_todo_state() {
446 assert_eq!(TodoStatus::parse("cancelled"), Some(TodoStatus::Cancelled));
447 assert_eq!(TodoStatus::parse("canceled"), Some(TodoStatus::Cancelled));
448
449 let mut list = TodoList::new();
450 list.add("abandoned approach".to_string(), TodoStatus::Cancelled);
451 let snapshot = list.snapshot();
452 assert_eq!(snapshot.completion_pct, 100);
453 assert_eq!(snapshot.in_progress_id, None);
454 assert_eq!(
455 serde_json::to_value(snapshot.items[0].status).expect("serialize"),
456 serde_json::json!("cancelled")
457 );
458
459 let schema = TodoWriteTool::new(new_shared_todo_list()).input_schema();
460 let statuses = &schema["properties"]["todos"]["items"]["properties"]["status"]["enum"];
461 assert!(statuses.as_array().is_some_and(|values| {
462 values
463 .iter()
464 .any(|value| value.as_str() == Some("cancelled"))
465 }));
466 }
467
468 #[test]
469 fn persisted_snapshot_restores_ids_status_and_recomputes_metrics() {
470 let snapshot = TodoListSnapshot {
471 items: vec![
472 TodoItem {
473 id: 4,
474 content: " inspect ".to_string(),
475 status: TodoStatus::Completed,
476 },
477 TodoItem {
478 id: 9,
479 content: "patch".to_string(),
480 status: TodoStatus::InProgress,
481 },
482 ],
483 completion_pct: 0,
484 in_progress_id: None,
485 };
486
487 let mut restored = TodoList::from_snapshot(&snapshot).expect("restore");
488 let restored_snapshot = restored.snapshot();
489 assert_eq!(restored_snapshot.items[0].id, 4);
490 assert_eq!(restored_snapshot.items[0].content, " inspect ");
491 assert_eq!(restored_snapshot.items[1].id, 9);
492 assert_eq!(restored_snapshot.completion_pct, 50);
493 assert_eq!(restored_snapshot.in_progress_id, Some(9));
494 assert_eq!(
495 restored.add("verify".to_string(), TodoStatus::Pending).id,
496 10
497 );
498 }
499
500 #[test]
501 fn malformed_persisted_snapshot_is_rejected_deterministically() {
502 let duplicate = TodoListSnapshot {
503 items: vec![
504 TodoItem {
505 id: 1,
506 content: "one".to_string(),
507 status: TodoStatus::InProgress,
508 },
509 TodoItem {
510 id: 1,
511 content: "two".to_string(),
512 status: TodoStatus::Pending,
513 },
514 ],
515 ..TodoListSnapshot::default()
516 };
517 assert_eq!(
518 TodoList::from_snapshot(&duplicate).unwrap_err(),
519 "Duplicate To-do item ID 1"
520 );
521
522 let multiple_active = TodoListSnapshot {
523 items: vec![
524 TodoItem {
525 id: 1,
526 content: "one".to_string(),
527 status: TodoStatus::InProgress,
528 },
529 TodoItem {
530 id: 2,
531 content: "two".to_string(),
532 status: TodoStatus::InProgress,
533 },
534 ],
535 ..TodoListSnapshot::default()
536 };
537 assert_eq!(
538 TodoList::from_snapshot(&multiple_active).unwrap_err(),
539 "Only one To-do item may be in progress"
540 );
541 }
542
543 #[tokio::test]
544 async fn work_update_rejects_unknown_status_instead_of_coercing_to_pending() {
545 // #5123-class: statuses like "blocked" / "in-progress" used to be
546 // recorded as pending with a success receipt on the canonical
547 // progress surface.
548 let tool = TodoWriteTool::new(new_shared_todo_list());
549 let context = ToolContext::new(std::env::temp_dir());
550 let err = tool
551 .execute(
552 json!({"todos": [{ "content": "x", "status": "blocked" }]}),
553 &context,
554 )
555 .await
556 .expect_err("unknown status must fail fast");
557 assert!(format!("{err}").contains("unknown todo status"), "{err}");
558
559 // Common near-misses resolve via the synonym table.
560 assert_eq!(TodoStatus::parse("complete"), Some(TodoStatus::Completed));
561 assert_eq!(
562 TodoStatus::parse("in-progress"),
563 Some(TodoStatus::InProgress)
564 );
565 assert_eq!(TodoStatus::parse("blocked"), None);
566 }
567
568 #[tokio::test]
569 async fn work_update_returns_canonical_task_update_metadata() {
570 let tool = TodoWriteTool::new(new_shared_todo_list());
571 let context = ToolContext::new(std::env::temp_dir());
572 let result = tool
573 .execute(
574 json!({
575 "todos": [
576 { "content": "wire durable task tools", "status": "in_progress" },
577 { "content": "run gates", "status": "pending" }
578 ]
579 }),
580 &context,
581 )
582 .await
583 .expect("work_update succeeds");
584
585 assert!(tool.model_visible());
586 let metadata = result.metadata.expect("metadata");
587 assert_eq!(metadata["canonical_tool"], "todo_write");
588 assert_eq!(metadata["work_surface"]["canonical"], "work");
589 assert_eq!(metadata["work_surface"]["model_visible"], true);
590 assert_eq!(
591 metadata["work_surface"]["durable_owner"],
592 "fleet_workflow_ledger"
593 );
594 assert_eq!(
595 metadata["work_surface"]["progress_key"],
596 "task_updates.checklist"
597 );
598 assert_eq!(
599 metadata["task_updates"]["checklist"]["in_progress_id"],
600 json!(1)
601 );
602 assert_eq!(
603 metadata["task_updates"]["checklist"]["items"][0]["content"],
604 "wire durable task tools"
605 );
606 }
607
608 #[tokio::test]
609 async fn work_update_routes_through_attached_graph() {
610 let todos = new_shared_todo_list();
611 let plan = crate::tools::plan::new_shared_plan_state();
612 let work = crate::work_graph::new_shared_work_runtime(todos.clone(), plan);
613 let mut context = ToolContext::new(std::env::temp_dir());
614 context.runtime.work = Some(work.clone());
615
616 TodoWriteTool::new(todos.clone())
617 .execute(
618 json!({"todos": [
619 {"content": "Graph-owned", "status": "completed"},
620 {"content": "Discarded branch", "status": "cancelled"}
621 ]}),
622 &context,
623 )
624 .await
625 .expect("second work_update");
626
627 let state = work
628 .capture(Some(&context.state_namespace))
629 .expect("capture")
630 .expect("graph state");
631 assert_eq!(state.todos.items[0].status, TodoStatus::Completed);
632 assert_eq!(state.todos.items[1].status, TodoStatus::Cancelled);
633 assert_eq!(state.todos.completion_pct, 100);
634 let node = state
635 .graph
636 .node(&state.graph.compat.todos[0].node)
637 .expect("projected node");
638 assert_eq!(node.state, crate::work_graph::NodeState::Completed);
639 let cancelled_node = state
640 .graph
641 .node(&state.graph.compat.todos[1].node)
642 .expect("cancelled projected node");
643 assert_eq!(
644 cancelled_node.state,
645 crate::work_graph::NodeState::Cancelled
646 );
647 assert!(todos.lock().await.snapshot().is_empty());
648 assert_eq!(work.publish_pending().await, Ok(true));
649 assert_eq!(
650 todos.lock().await.snapshot().items[0].status,
651 TodoStatus::Completed
652 );
653 assert_eq!(
654 todos.lock().await.snapshot().items[1].status,
655 TodoStatus::Cancelled
656 );
657 }
658 }
659
659 lines RUST