返回 CodeWhale
plans.rs
1 //! `/v1/plan`, `/v1/todo`, `/v1/plans`, `/v1/todos`, and the per-thread pair —
2 //! read-only inventory over the plan/todo tool receipts the runtime store
3 //! already persists on turn items.
4 //!
5 //! There is no second plan store. An `update_plan` receipt carries the plan
6 //! payload; a `todo_write` / `work_update` receipt carries the whole
7 //! checklist. The newest receipt per thread is the live projection, and
8 //! earlier `update_plan` receipts in the same thread report
9 //! `superseded: true`. Match on `metadata.tool_name` (never on item `kind` — the store
10 //! files `todo_write` under `file_change` because the name contains "write")
11 //! and parse the args JSON out of `metadata.tool_input`, falling back to
12 //! `detail` for seeded history receipts that predate durable `tool_input`
13 //! (the same fallback restart history rebuild uses in runtime_threads.rs).
14 //!
15 //! **What this module does not do:** it does not read the live `PlanState` /
16 //! `SharedTodoList` — those are per-engine session state, not durable
17 //! receipts, and a headless Runtime may have no engine loaded for the thread.
18 //! To-do history is not tracked: only the newest checklist receipt projects,
19 //! matching the client. And the cross-thread routes pay one
20 //! `get_thread_detail` whole-store walk per scanned thread — the store keeps
21 //! no plan/todo index — so `limit` bounds how many of the newest threads are
22 //! scanned.
23
24 use axum::Json;
25 use axum::extract::{Path, Query, State};
26 use serde::Serialize;
27 use serde_json::Value;
28
29 use codewhale_engine::runtime_threads::{TurnItemLifecycleStatus, TurnItemRecord};
30 use codewhale_engine::tools::plan::{PlanItemArg, PlanSnapshot};
31 use codewhale_engine::tools::todo::TodoStatus;
32
33 use super::{ApiError, RuntimeApiState, ThreadsQuery, map_thread_err, resolve_thread_filter};
34
35 /// One `update_plan` receipt projected for the API.
36 #[derive(Debug, Clone, Serialize)]
37 #[serde(rename_all = "camelCase")]
38 pub(super) struct PlanRevisionView {
39 item_id: String,
40 turn_id: String,
41 /// Receipt lifecycle (`completed`, `failed`, …), not plan state.
42 status: TurnItemLifecycleStatus,
43 title: Option<String>,
44 objective: Option<String>,
45 explanation: Option<String>,
46 recommended_approach: Option<String>,
47 /// `PlanItemArg` already serializes as `{step, status}` with status in
48 /// `pending|in_progress|completed`.
49 steps: Vec<PlanItemArg>,
50 /// True when a newer `update_plan` receipt in the same thread superseded
51 /// this revision.
52 superseded: bool,
53 }
54
55 /// A thread's current plan plus its revision history.
56 #[derive(Debug, Serialize)]
57 #[serde(rename_all = "camelCase")]
58 pub(super) struct ThreadPlanView {
59 thread_id: String,
60 /// Fields of the newest revision, flattened to the top level.
61 #[serde(flatten)]
62 current: PlanRevisionView,
63 /// Every `update_plan` receipt, newest first; `revisions[0]` is `current`.
64 revisions: Vec<PlanRevisionView>,
65 }
66
67 /// The newest revision of one thread's plan, for `/v1/plans` rows.
68 #[derive(Debug, Serialize)]
69 #[serde(rename_all = "camelCase")]
70 pub(super) struct PlanEntryView {
71 thread_id: String,
72 #[serde(flatten)]
73 revision: PlanRevisionView,
74 }
75
76 #[derive(Debug, Serialize)]
77 pub(super) struct PlansResponse {
78 plans: Vec<PlanEntryView>,
79 }
80
81 #[derive(Debug, Serialize)]
82 pub(super) struct TodosResponse {
83 todos: Vec<ThreadTodoView>,
84 }
85
86 #[derive(Debug, Clone, Serialize)]
87 #[serde(rename_all = "camelCase")]
88 pub(super) struct TodoItemView {
89 content: String,
90 status: TodoStatus,
91 #[serde(skip_serializing_if = "Option::is_none")]
92 id: Option<u32>,
93 }
94
95 /// A thread's latest checklist receipt projected for the API.
96 #[derive(Debug, Serialize)]
97 #[serde(rename_all = "camelCase")]
98 pub(super) struct ThreadTodoView {
99 thread_id: String,
100 item_id: Option<String>,
101 turn_id: Option<String>,
102 /// Receipt tool name (`todo_write`, `work_update`, …).
103 tool: String,
104 /// Receipt lifecycle (`completed`, `failed`, …), not list state.
105 status: Option<TurnItemLifecycleStatus>,
106 items: Vec<TodoItemView>,
107 completion_pct: Option<u8>,
108 }
109
110 fn is_plan_tool(name: &str) -> bool {
111 name == "update_plan"
112 }
113
114 /// Names a checklist receipt can persist under: the canonical `todo_write`,
115 /// its registered compat aliases (registry.rs `with_todo_tool`), and the
116 /// `todos` name.
117 fn is_todo_tool(name: &str) -> bool {
118 matches!(
119 name,
120 "todo_write"
121 | "work_update"
122 | "TodoWrite"
123 | "todo"
124 | "todos"
125 | "checklist_write"
126 | "checklist_update"
127 )
128 }
129
130 fn tool_name(item: &TurnItemRecord) -> &str {
131 item.metadata
132 .as_ref()
133 .and_then(|meta| meta.get("tool_name"))
134 .and_then(Value::as_str)
135 .unwrap_or_default()
136 }
137
138 /// The receipt's args JSON. Live calls persist it as a string under
139 /// `metadata.tool_input` at `ToolCallStarted` and carry it through completion;
140 /// seeded history receipts carry `tool_name` but leave the input in `detail`,
141 /// which is why the fallback exists only when `tool_input` is absent.
142 fn tool_input(item: &TurnItemRecord) -> Option<Value> {
143 let raw = item
144 .metadata
145 .as_ref()
146 .and_then(|meta| meta.get("tool_input"))
147 .and_then(Value::as_str)
148 .map(str::to_string)
149 .or_else(|| item.detail.clone())?;
150 serde_json::from_str(&raw).ok()
151 }
152
153 /// Every `update_plan` receipt in the thread, oldest first, with `superseded`
154 /// set on all but the newest.
155 fn plan_revisions(items: &[TurnItemRecord]) -> Vec<PlanRevisionView> {
156 let mut revisions = Vec::new();
157 for item in items {
158 if !is_plan_tool(tool_name(item)) {
159 continue;
160 }
161 let Some(input) = tool_input(item) else {
162 continue;
163 };
164 // The engine's canonical tolerant parser for this payload: it cleans
165 // optional strings and coerces unknown/absent step status to Pending.
166 let snapshot = PlanSnapshot::from_tool_input(&input);
167 revisions.push(PlanRevisionView {
168 item_id: item.id.clone(),
169 turn_id: item.turn_id.clone(),
170 status: item.status,
171 title: snapshot.title,
172 objective: snapshot.objective,
173 explanation: snapshot.explanation,
174 recommended_approach: snapshot.recommended_approach,
175 steps: snapshot.items,
176 superseded: false,
177 });
178 }
179 if let Some(current_id) = revisions.last().map(|rev| rev.item_id.clone()) {
180 for rev in &mut revisions {
181 rev.superseded = rev.item_id != current_id;
182 }
183 }
184 revisions
185 }
186
187 /// The newest checklist receipt in the thread, or `None` when it has none.
188 /// Each receipt replaces the whole list, so only the latest projects.
189 fn latest_todo(items: &[TurnItemRecord]) -> Option<ThreadTodoView> {
190 let mut latest: Option<ThreadTodoView> = None;
191 for item in items {
192 let tool = tool_name(item);
193 if !is_todo_tool(tool) {
194 continue;
195 }
196 let Some(input) = tool_input(item) else {
197 continue;
198 };
199 let todos = input
200 .get("todos")
201 .and_then(Value::as_array)
202 .cloned()
203 .or_else(|| {
204 input
205 .pointer("/task_updates/checklist/items")
206 .and_then(Value::as_array)
207 .cloned()
208 })
209 .unwrap_or_default();
210 let mut steps = Vec::new();
211 for todo in &todos {
212 let content = todo
213 .get("content")
214 .or_else(|| todo.get("text"))
215 .or_else(|| todo.get("step"))
216 .and_then(Value::as_str)
217 .map(str::trim)
218 .unwrap_or_default();
219 if content.is_empty() {
220 continue;
221 }
222 let status = todo
223 .get("status")
224 .and_then(Value::as_str)
225 .and_then(TodoStatus::parse)
226 .unwrap_or(TodoStatus::Pending);
227 let id = todo
228 .get("id")
229 .and_then(Value::as_u64)
230 .and_then(|n| u32::try_from(n).ok());
231 steps.push(TodoItemView {
232 content: content.to_string(),
233 status,
234 id,
235 });
236 }
237 let completion_pct = input
238 .get("completion_pct")
239 .or_else(|| input.pointer("/task_updates/checklist/completion_pct"))
240 .and_then(Value::as_u64)
241 .map(|n| n.min(100) as u8)
242 .or_else(|| {
243 if steps.is_empty() {
244 None
245 } else {
246 let settled = steps.iter().filter(|s| s.status.is_settled()).count();
247 Some(((settled * 100) / steps.len()) as u8)
248 }
249 });
250 latest = Some(ThreadTodoView {
251 thread_id: String::new(),
252 item_id: Some(item.id.clone()),
253 turn_id: Some(item.turn_id.clone()),
254 tool: tool.to_string(),
255 status: Some(item.status),
256 items: steps,
257 completion_pct,
258 });
259 }
260 latest
261 }
262
263 /// `GET /v1/threads/{id}/plan` — the thread's latest plan and its revisions.
264 pub(super) async fn get_thread_plan(
265 State(state): State<RuntimeApiState>,
266 Path(id): Path<String>,
267 ) -> Result<Json<ThreadPlanView>, ApiError> {
268 let detail = state
269 .runtime_threads
270 .get_thread_detail(&id)
271 .await
272 .map_err(map_thread_err)?;
273 let mut revisions = plan_revisions(&detail.items);
274 revisions.reverse();
275 let Some(current) = revisions.first().cloned() else {
276 return Err(ApiError::not_found(format!("Thread '{id}' has no plan")));
277 };
278 Ok(Json(ThreadPlanView {
279 thread_id: id,
280 current,
281 revisions,
282 }))
283 }
284
285 /// `GET /v1/threads/{id}/todo` — the thread's latest checklist.
286 pub(super) async fn get_thread_todo(
287 State(state): State<RuntimeApiState>,
288 Path(id): Path<String>,
289 ) -> Result<Json<ThreadTodoView>, ApiError> {
290 let detail = state
291 .runtime_threads
292 .get_thread_detail(&id)
293 .await
294 .map_err(map_thread_err)?;
295 let Some(mut todo) = latest_todo(&detail.items) else {
296 return Err(ApiError::not_found(format!(
297 "Thread '{id}' has no todo list"
298 )));
299 };
300 todo.thread_id = id;
301 Ok(Json(todo))
302 }
303
304 /// `GET /v1/plan` — the latest plan on the most recently updated thread that
305 /// has one. Threads are already newest-first; the first hit wins.
306 pub(super) async fn latest_plan(
307 State(state): State<RuntimeApiState>,
308 Query(query): Query<ThreadsQuery>,
309 ) -> Result<Json<ThreadPlanView>, ApiError> {
310 let filter = resolve_thread_filter(query.include_archived, query.archived_only);
311 let threads = state
312 .runtime_threads
313 .list_threads(filter, query.limit)
314 .await
315 .map_err(|e| ApiError::internal(e.to_string()))?;
316 for thread in threads {
317 let detail = state
318 .runtime_threads
319 .get_thread_detail(&thread.id)
320 .await
321 .map_err(map_thread_err)?;
322 let mut revisions = plan_revisions(&detail.items);
323 if revisions.is_empty() {
324 continue;
325 }
326 revisions.reverse();
327 let current = revisions[0].clone();
328 return Ok(Json(ThreadPlanView {
329 thread_id: thread.id,
330 current,
331 revisions,
332 }));
333 }
334 Err(ApiError::not_found("No thread has a plan"))
335 }
336
337 /// `GET /v1/todo` — the latest checklist on the most recently updated thread
338 /// that has one.
339 pub(super) async fn latest_todo_route(
340 State(state): State<RuntimeApiState>,
341 Query(query): Query<ThreadsQuery>,
342 ) -> Result<Json<ThreadTodoView>, ApiError> {
343 let filter = resolve_thread_filter(query.include_archived, query.archived_only);
344 let threads = state
345 .runtime_threads
346 .list_threads(filter, query.limit)
347 .await
348 .map_err(|e| ApiError::internal(e.to_string()))?;
349 for thread in threads {
350 let detail = state
351 .runtime_threads
352 .get_thread_detail(&thread.id)
353 .await
354 .map_err(map_thread_err)?;
355 if let Some(mut todo) = latest_todo(&detail.items) {
356 todo.thread_id = thread.id;
357 return Ok(Json(todo));
358 }
359 }
360 Err(ApiError::not_found("No thread has a todo list"))
361 }
362
363 /// `GET /v1/plans` — every scanned thread's latest plan, newest thread first.
364 pub(super) async fn list_plans(
365 State(state): State<RuntimeApiState>,
366 Query(query): Query<ThreadsQuery>,
367 ) -> Result<Json<PlansResponse>, ApiError> {
368 let filter = resolve_thread_filter(query.include_archived, query.archived_only);
369 let threads = state
370 .runtime_threads
371 .list_threads(filter, query.limit)
372 .await
373 .map_err(|e| ApiError::internal(e.to_string()))?;
374 let mut plans = Vec::new();
375 for thread in threads {
376 let detail = state
377 .runtime_threads
378 .get_thread_detail(&thread.id)
379 .await
380 .map_err(map_thread_err)?;
381 if let Some(revision) = plan_revisions(&detail.items).into_iter().last() {
382 plans.push(PlanEntryView {
383 thread_id: thread.id,
384 revision,
385 });
386 }
387 }
388 Ok(Json(PlansResponse { plans }))
389 }
390
391 /// `GET /v1/todos` — every scanned thread's latest checklist, newest thread
392 /// first.
393 pub(super) async fn list_todos(
394 State(state): State<RuntimeApiState>,
395 Query(query): Query<ThreadsQuery>,
396 ) -> Result<Json<TodosResponse>, ApiError> {
397 let filter = resolve_thread_filter(query.include_archived, query.archived_only);
398 let threads = state
399 .runtime_threads
400 .list_threads(filter, query.limit)
401 .await
402 .map_err(|e| ApiError::internal(e.to_string()))?;
403 let mut todos = Vec::new();
404 for thread in threads {
405 let detail = state
406 .runtime_threads
407 .get_thread_detail(&thread.id)
408 .await
409 .map_err(map_thread_err)?;
410 if let Some(mut todo) = latest_todo(&detail.items) {
411 todo.thread_id = thread.id;
412 todos.push(todo);
413 }
414 }
415 Ok(Json(TodosResponse { todos }))
416 }
417
418 #[cfg(test)]
419 mod tests {
420 use super::*;
421 use chrono::Utc;
422 use codewhale_engine::runtime_threads::TurnItemKind;
423 use serde_json::json;
424
425 fn receipt(id: &str, tool: &str, input: &Value) -> TurnItemRecord {
426 let now = Utc::now();
427 TurnItemRecord {
428 schema_version: 2,
429 id: id.to_string(),
430 turn_id: "turn_1".to_string(),
431 kind: TurnItemKind::ToolCall,
432 status: TurnItemLifecycleStatus::Completed,
433 summary: tool.to_string(),
434 detail: Some("tool output".to_string()),
435 metadata: Some(json!({
436 "tool_use_id": format!("call_{id}"),
437 "tool_name": tool,
438 "tool_input": input.to_string(),
439 })),
440 artifact_refs: Vec::new(),
441 artifacts: Vec::new(),
442 started_at: Some(now),
443 ended_at: Some(now),
444 }
445 }
446
447 #[test]
448 fn plan_revisions_mark_all_but_newest_superseded() {
449 let items = vec![
450 receipt(
451 "p1",
452 "update_plan",
453 &json!({
454 "title": "First",
455 "plan": [{"step": "A", "status": "completed"}]
456 }),
457 ),
458 receipt("other", "shell", &json!({"cmd": "pwd"})),
459 receipt(
460 "p2",
461 "update_plan",
462 &json!({
463 "objective": "Ship it",
464 "plan": [
465 {"step": "Probe", "status": "completed"},
466 {"step": "Land", "status": "in_progress"}
467 ]
468 }),
469 ),
470 ];
471 let revisions = plan_revisions(&items);
472 assert_eq!(revisions.len(), 2);
473 assert!(revisions[0].superseded);
474 assert!(!revisions[1].superseded);
475 assert_eq!(revisions[1].item_id, "p2");
476 assert_eq!(revisions[1].objective.as_deref(), Some("Ship it"));
477 assert_eq!(revisions[1].steps.len(), 2);
478 assert_eq!(
479 revisions[1].steps[1].status,
480 codewhale_engine::tools::plan::StepStatus::InProgress
481 );
482 }
483
484 #[test]
485 fn latest_todo_keeps_only_the_newest_receipt() {
486 let items = vec![
487 receipt(
488 "t1",
489 "todo_write",
490 &json!({"todos": [{"id": 1, "content": "old", "status": "pending"}]}),
491 ),
492 receipt(
493 "t2",
494 "work_update",
495 &json!({
496 "todos": [
497 {"id": 1, "content": "probe", "status": "completed"},
498 {"id": 2, "content": "land", "status": "in_progress"},
499 {"id": 3, "content": "push", "status": "pending"}
500 ]
501 }),
502 ),
503 ];
504 let todo = latest_todo(&items).expect("a todo receipt exists");
505 assert_eq!(todo.item_id.as_deref(), Some("t2"));
506 assert_eq!(todo.tool, "work_update");
507 assert_eq!(todo.items.len(), 3);
508 assert_eq!(todo.items[1].status, TodoStatus::InProgress);
509 assert_eq!(todo.completion_pct, Some(33));
510 assert!(latest_todo(&items[..0]).is_none());
511 }
512
513 #[test]
514 fn seeded_receipt_without_tool_input_reads_detail() {
515 let mut item = receipt(
516 "seeded",
517 "update_plan",
518 &json!({"title": "Seeded", "plan": [{"step": "A", "status": "pending"}]}),
519 );
520 // Seeded history carries the args JSON in `detail`, not
521 // `metadata.tool_input` (runtime_threads.rs SeedItem::ToolUse).
522 let input = item
523 .metadata
524 .as_ref()
525 .and_then(|m| m.get("tool_input"))
526 .and_then(Value::as_str)
527 .unwrap_or_default()
528 .to_string();
529 item.detail = Some(input);
530 item.metadata = Some(json!({"tool_use_id": "call_seeded", "tool_name": "update_plan"}));
531 let revisions = plan_revisions(&[item]);
532 assert_eq!(revisions.len(), 1);
533 assert_eq!(revisions[0].title.as_deref(), Some("Seeded"));
534 }
535 }
536
536 lines RUST