1use crate::plans::{self, Plan, Status};
19use crate::session::SessionStore;
20use crate::tools::{CallScope, Tool, ToolError};
21use async_trait::async_trait;
22use serde_json::{json, Value};
23
24pub struct PlanTool {
25 store: SessionStore,
26}
27
28impl PlanTool {
29 pub fn new(store: SessionStore) -> Self {
30 Self { store }
31 }
32
33 fn parse_items(&self, args: &Value) -> Result<Option<Vec<crate::plans::Item>>, ToolError> {
38 let Some(raw) = args.get("items") else {
39 return Ok(None);
40 };
41 let list = raw.as_array().ok_or_else(|| {
42 ToolError::InvalidArgs(
43 "`items` must be a list of steps, or left out to read".to_string(),
44 )
45 })?;
46 let mut items = Vec::with_capacity(list.len());
47 for (index, entry) in list.iter().enumerate() {
48 let position = index + 1;
49 let object = entry.as_object().ok_or_else(|| {
50 ToolError::InvalidArgs(format!("item {position} is not an object"))
51 })?;
52 let text = |key: &str| -> Result<String, ToolError> {
53 match object.get(key) {
54 Some(Value::String(s)) => Ok(s.clone()),
55 Some(_) => Err(ToolError::InvalidArgs(format!(
56 "item {position}: `{key}` must be a string"
57 ))),
58 None if key == "content" => Ok(String::new()),
59 None => Ok(String::new()),
60 }
61 };
62 let id = text("id")?;
63 let content = text("content")?;
64 let status = match object.get("status") {
65 None | Some(Value::Null) => Status::Pending,
66 Some(Value::String(word)) => Status::parse(word).ok_or_else(|| {
67 ToolError::InvalidArgs(format!(
68 "item {position} (`{id}`): `{word}` is not a status; use `pending`, \
69 `in_progress`, `done` or `cancelled`"
70 ))
71 })?,
72 Some(_) => {
73 return Err(ToolError::InvalidArgs(format!(
74 "item {position}: `status` must be a word"
75 )))
76 }
77 };
78 let parent = match object.get("parent") {
79 None | Some(Value::Null) => None,
80 Some(Value::String(p)) if p.trim().is_empty() => None,
81 Some(Value::String(p)) => Some(p.clone()),
82 Some(_) => {
83 return Err(ToolError::InvalidArgs(format!(
84 "item {position}: `parent` must be the id of another step"
85 )))
86 }
87 };
88 items.push(crate::plans::Item {
89 id,
90 content,
91 status,
92 parent,
93 });
94 }
95 Ok(Some(items))
96 }
97
98 fn render(&self, plan: &Plan, demoted: &[String]) -> String {
99 let counts = plan.counts();
100 let (finished, total) = plan.progress();
101 let mut out = format!("plan {finished}/{total}");
102 match plan.current() {
103 Some(current) => out.push_str(&format!(" · next {}", current.id)),
104 None if total > 0 => out.push_str(" · none in progress"),
105 None => {}
106 }
107 if plan.items.is_empty() {
108 out.push_str("\n(no steps)");
109 }
110 for item in &plan.items {
111 out.push_str(&format!(
114 "\n{} {} {}",
115 item.status.mark(),
116 item.id,
117 item.content
118 ));
119 if let Some(parent) = &item.parent {
120 out.push_str(&format!(" (in {parent})"));
121 }
122 }
123 if !demoted.is_empty() {
124 out.push_str(&format!(
125 "\nonly one step can be `in_progress`: {} demoted to `pending` ({})",
126 if demoted.len() == 1 {
127 "it was"
128 } else {
129 "they were"
130 },
131 demoted.join(", ")
132 ));
133 }
134 out.push_str(&format!(
135 "\nrevision {} · {} pending, {} in progress, {} done, {} cancelled",
136 plan.revision, counts.pending, counts.in_progress, counts.done, counts.cancelled
137 ));
138 out
139 }
140}
141
142#[async_trait]
143impl Tool for PlanTool {
144 fn name(&self) -> &str {
145 "plan"
146 }
147
148 fn description(&self) -> &str {
149 "Keep the list of steps for the job in hand: what is left, in what order, and which step \
150 is being done now. Call it with `items` to write, or omit `items` to read the list back. \
151 List order is priority; exactly one step may be `in_progress` (a second is demoted to \
152 `pending` and the result says which); `merge: true` patches steps by `id` instead of \
153 replacing the whole list; `parent` puts a step inside a phase. Statuses: pending, \
154 in_progress, done, cancelled. On a job with many parts, write one item per part so none \
155 is silently dropped, and keep the list current as you go — it is what survives a \
156 compaction."
157 }
158
159 fn parameters(&self) -> Value {
160 json!({"type":"object","properties":{
161 "items":{"type":"array","description":"The whole list, in priority order. Omit to read. An empty list clears the plan.","items":{"type":"object","properties":{
162 "id":{"type":"string","description":"A short unique id for the step, for example `#550` or `tests`. A merge patches by this."},
163 "content":{"type":"string","description":"What the step is, in one line."},
164 "status":{"type":"string","description":"pending, in_progress, done or cancelled. Default pending."},
165 "parent":{"type":"string","description":"The id of the phase this step belongs to, if any."}
166 },"required":["id","content"]}},
167 "merge":{"type":"boolean","description":"Patch the steps named by `id` and append the new ones, instead of replacing the list. Default false."}
168 }})
169 }
170
171 fn needs_approval(&self, _args: &Value) -> bool {
174 false
175 }
176
177 fn describe_call(&self, args: &Value) -> String {
178 match args.get("items").and_then(Value::as_array) {
179 Some(items) => format!("plan · {} step(s)", items.len()),
180 None => "plan · read".to_string(),
181 }
182 }
183
184 async fn call(&self, _args: Value) -> Result<String, ToolError> {
188 Err(ToolError::Failed(
189 "`plan` keeps a list per session, and this call names none".to_string(),
190 ))
191 }
192
193 async fn call_scoped(&self, args: Value, scope: &CallScope<'_>) -> Result<String, ToolError> {
194 let session = scope.run.session.clone();
195 let Some(incoming) = self.parse_items(&args)? else {
196 return match self.store.plan(&session).map_err(failed)? {
197 Some(plan) => Ok(self.render(&plan, &[])),
198 None => Ok(
199 "no plan in this session yet — call `plan` with `items` to write the steps"
200 .to_string(),
201 ),
202 };
203 };
204 plans::validate(&incoming).map_err(ToolError::InvalidArgs)?;
207 let merge = args.get("merge").and_then(Value::as_bool).unwrap_or(false);
208 let existing = self.store.plan(&session).map_err(failed)?;
209 let mut items = match (merge, existing) {
210 (true, Some(plan)) => plans::merge(&plan.items, &incoming),
211 _ => incoming,
213 };
214 let demoted = plans::one_in_progress(&mut items);
215 let revision = self.store.set_plan(&session, &items).map_err(failed)?;
216 Ok(self.render(&Plan { revision, items }, &demoted))
217 }
218}
219
220fn failed(error: crate::error::Error) -> ToolError {
221 ToolError::Failed(format!("{error}"))
222}
223
224#[cfg(test)]
225mod tests {
226 use super::*;
227 use crate::tools::{AllowAll, RunScope, ToolRegistry};
228
229 struct Fixture {
230 _dir: tempfile::TempDir,
231 store: SessionStore,
232 }
233
234 fn fixture() -> Fixture {
235 let dir = tempfile::tempdir().unwrap();
236 let store = SessionStore::new(dir.path().to_path_buf());
237 Fixture { _dir: dir, store }
238 }
239
240 async fn call(store: SessionStore, args: Value) -> Result<String, ToolError> {
241 let tool = PlanTool::new(store);
242 let registry = ToolRegistry::new(4096);
243 let run = RunScope::new("s1");
244 let scope = CallScope {
245 approver: &AllowAll,
246 run: &run,
247 registry: ®istry,
248 call_id: None,
249 };
250 tool.call_scoped(args, &scope).await
251 }
252
253 #[tokio::test]
254 async fn a_write_then_a_read_gives_the_same_list_back() {
255 let f = fixture();
256 let out = call(
257 f.store.clone(),
258 json!({"items":[
259 {"id":"a","content":"read the audit","status":"done"},
260 {"id":"b","content":"fix the writer","status":"in_progress"},
261 {"id":"c","content":"release"}
262 ]}),
263 )
264 .await
265 .unwrap();
266 assert!(out.starts_with("plan 1/3 · next b"), "{out}");
267 assert!(out.contains("[x] a read the audit"), "{out}");
268 assert!(out.contains("[~] b fix the writer"), "{out}");
269 assert!(out.contains("[ ] c release"), "{out}");
270 assert!(
271 out.contains("revision 1 · 1 pending, 1 in progress, 1 done, 0 cancelled"),
272 "{out}"
273 );
274
275 let read = call(f.store.clone(), json!({})).await.unwrap();
276 assert_eq!(
277 read, out,
278 "a read must be the same list a write answered with, revision included"
279 );
280 }
281
282 #[tokio::test]
283 async fn every_write_bumps_the_revision_so_two_surfaces_can_tell() {
284 let f = fixture();
285 call(
286 f.store.clone(),
287 json!({"items":[{"id":"a","content":"one"}]}),
288 )
289 .await
290 .unwrap();
291 let second = call(
292 f.store.clone(),
293 json!({"items":[{"id":"a","content":"one","status":"done"}]}),
294 )
295 .await
296 .unwrap();
297 assert!(second.contains("revision 2"), "{second}");
298 }
299
300 #[tokio::test]
301 async fn a_merge_patches_by_id_and_keeps_the_order() {
302 let f = fixture();
303 call(
304 f.store.clone(),
305 json!({"items":[
306 {"id":"a","content":"first"},
307 {"id":"b","content":"second"},
308 {"id":"c","content":"third"}
309 ]}),
310 )
311 .await
312 .unwrap();
313 let out = call(
314 f.store.clone(),
315 json!({"merge":true,"items":[{"id":"b","content":"second, done","status":"done"}]}),
316 )
317 .await
318 .unwrap();
319 assert!(out.contains("[x] b second, done"), "{out}");
320 let order: Vec<&str> = out
321 .lines()
322 .filter(|l| l.starts_with('['))
323 .map(|l| l[4..].split_whitespace().next().unwrap())
325 .collect();
326 assert_eq!(order, ["a", "b", "c"], "b is still second: {out}");
327 assert!(out.contains("plan 1/3"), "{out}");
328 }
329
330 #[tokio::test]
331 async fn two_steps_in_progress_are_normalised_and_the_result_says_so() {
332 let f = fixture();
333 let out = call(
334 f.store.clone(),
335 json!({"items":[
336 {"id":"a","content":"first","status":"in_progress"},
337 {"id":"b","content":"second","status":"in_progress"}
338 ]}),
339 )
340 .await
341 .unwrap();
342 assert!(out.contains("only one step can be `in_progress`"), "{out}");
343 assert!(out.contains("demoted to `pending` (b)"), "{out}");
344 assert!(out.contains("[ ] b second"), "{out}");
345 assert!(out.contains("1 pending, 1 in progress"), "{out}");
346 }
347
348 #[tokio::test]
349 async fn a_step_with_no_content_is_refused_and_the_list_is_untouched() {
350 let f = fixture();
351 call(
352 f.store.clone(),
353 json!({"items":[{"id":"a","content":"the real plan"}]}),
354 )
355 .await
356 .unwrap();
357 let refused = call(
358 f.store.clone(),
359 json!({"items":[{"id":"x","content":"ok"},{"id":"y","content":" "}]}),
360 )
361 .await
362 .unwrap_err();
363 assert_eq!(
364 refused.to_string(),
365 "invalid arguments: item 2 (`y`) has no `content`; a step with nothing to do cannot be \
366 done or dropped"
367 );
368 let read = call(f.store.clone(), json!({})).await.unwrap();
369 assert!(read.contains("a the real plan"), "{read}");
370 assert!(!read.contains(" x "), "nothing was written: {read}");
371 assert!(
372 read.contains("revision 1"),
373 "and the revision did not move: {read}"
374 );
375 }
376
377 #[tokio::test]
378 async fn an_unknown_status_names_the_word_and_the_ones_to_use() {
379 let f = fixture();
380 let refused = call(
381 f.store.clone(),
382 json!({"items":[{"id":"a","content":"x","status":"blocked"}]}),
383 )
384 .await
385 .unwrap_err();
386 assert!(
387 refused.to_string().contains("`blocked` is not a status"),
388 "{refused}"
389 );
390 assert!(
391 refused
392 .to_string()
393 .contains("`pending`, `in_progress`, `done` or `cancelled`"),
394 "{refused}"
395 );
396 }
397
398 #[tokio::test]
399 async fn an_empty_list_clears_the_plan() {
400 let f = fixture();
401 call(
402 f.store.clone(),
403 json!({"items":[{"id":"a","content":"one"}]}),
404 )
405 .await
406 .unwrap();
407 let out = call(f.store.clone(), json!({"items":[]})).await.unwrap();
408 assert!(out.starts_with("plan 0/0"), "{out}");
409 assert!(out.contains("(no steps)"), "{out}");
410 assert!(out.contains("revision 2"), "{out}");
411 }
412
413 #[tokio::test]
414 async fn a_session_with_no_plan_says_so_rather_than_inventing_one() {
415 let f = fixture();
416 let out = call(f.store.clone(), json!({})).await.unwrap();
417 assert_eq!(
418 out,
419 "no plan in this session yet — call `plan` with `items` to write the steps"
420 );
421 }
422
423 #[tokio::test]
424 async fn a_phase_is_a_step_and_its_children_name_it() {
425 let f = fixture();
426 let out = call(
427 f.store.clone(),
428 json!({"items":[
429 {"id":"writer","content":"the writer cluster","status":"in_progress"},
430 {"id":"#535","content":"array header ends a section","parent":"writer"}
431 ]}),
432 )
433 .await
434 .unwrap();
435 assert!(
436 out.contains("#535 array header ends a section (in writer)"),
437 "{out}"
438 );
439 }
440}