use crate::plans::{self, Plan, Status};
use crate::session::SessionStore;
use crate::tools::{CallScope, Tool, ToolError};
use async_trait::async_trait;
use serde_json::{json, Value};
pub struct PlanTool {
store: SessionStore,
}
impl PlanTool {
pub fn new(store: SessionStore) -> Self {
Self { store }
}
fn parse_items(&self, args: &Value) -> Result<Option<Vec<crate::plans::Item>>, ToolError> {
let Some(raw) = args.get("items") else {
return Ok(None);
};
let list = raw.as_array().ok_or_else(|| {
ToolError::InvalidArgs(
"`items` must be a list of steps, or left out to read".to_string(),
)
})?;
let mut items = Vec::with_capacity(list.len());
for (index, entry) in list.iter().enumerate() {
let position = index + 1;
let object = entry.as_object().ok_or_else(|| {
ToolError::InvalidArgs(format!("item {position} is not an object"))
})?;
let text = |key: &str| -> Result<String, ToolError> {
match object.get(key) {
Some(Value::String(s)) => Ok(s.clone()),
Some(_) => Err(ToolError::InvalidArgs(format!(
"item {position}: `{key}` must be a string"
))),
None if key == "content" => Ok(String::new()),
None => Ok(String::new()),
}
};
let id = text("id")?;
let content = text("content")?;
let status = match object.get("status") {
None | Some(Value::Null) => Status::Pending,
Some(Value::String(word)) => Status::parse(word).ok_or_else(|| {
ToolError::InvalidArgs(format!(
"item {position} (`{id}`): `{word}` is not a status; use `pending`, \
`in_progress`, `done` or `cancelled`"
))
})?,
Some(_) => {
return Err(ToolError::InvalidArgs(format!(
"item {position}: `status` must be a word"
)))
}
};
let parent = match object.get("parent") {
None | Some(Value::Null) => None,
Some(Value::String(p)) if p.trim().is_empty() => None,
Some(Value::String(p)) => Some(p.clone()),
Some(_) => {
return Err(ToolError::InvalidArgs(format!(
"item {position}: `parent` must be the id of another step"
)))
}
};
items.push(crate::plans::Item {
id,
content,
status,
parent,
});
}
Ok(Some(items))
}
fn render(&self, plan: &Plan, demoted: &[String]) -> String {
let counts = plan.counts();
let (finished, total) = plan.progress();
let mut out = format!("plan {finished}/{total}");
match plan.current() {
Some(current) => out.push_str(&format!(" · next {}", current.id)),
None if total > 0 => out.push_str(" · none in progress"),
None => {}
}
if plan.items.is_empty() {
out.push_str("\n(no steps)");
}
for item in &plan.items {
out.push_str(&format!(
"\n{} {} {}",
item.status.mark(),
item.id,
item.content
));
if let Some(parent) = &item.parent {
out.push_str(&format!(" (in {parent})"));
}
}
if !demoted.is_empty() {
out.push_str(&format!(
"\nonly one step can be `in_progress`: {} demoted to `pending` ({})",
if demoted.len() == 1 {
"it was"
} else {
"they were"
},
demoted.join(", ")
));
}
out.push_str(&format!(
"\nrevision {} · {} pending, {} in progress, {} done, {} cancelled",
plan.revision, counts.pending, counts.in_progress, counts.done, counts.cancelled
));
out
}
}
#[async_trait]
impl Tool for PlanTool {
fn name(&self) -> &str {
"plan"
}
fn description(&self) -> &str {
"Keep the list of steps for the job in hand: what is left, in what order, and which step \
is being done now. Call it with `items` to write, or omit `items` to read the list back. \
List order is priority; exactly one step may be `in_progress` (a second is demoted to \
`pending` and the result says which); `merge: true` patches steps by `id` instead of \
replacing the whole list; `parent` puts a step inside a phase. Statuses: pending, \
in_progress, done, cancelled. On a job with many parts, write one item per part so none \
is silently dropped, and keep the list current as you go — it is what survives a \
compaction."
}
fn parameters(&self) -> Value {
json!({"type":"object","properties":{
"items":{"type":"array","description":"The whole list, in priority order. Omit to read. An empty list clears the plan.","items":{"type":"object","properties":{
"id":{"type":"string","description":"A short unique id for the step, for example `#550` or `tests`. A merge patches by this."},
"content":{"type":"string","description":"What the step is, in one line."},
"status":{"type":"string","description":"pending, in_progress, done or cancelled. Default pending."},
"parent":{"type":"string","description":"The id of the phase this step belongs to, if any."}
},"required":["id","content"]}},
"merge":{"type":"boolean","description":"Patch the steps named by `id` and append the new ones, instead of replacing the list. Default false."}
}})
}
fn needs_approval(&self, _args: &Value) -> bool {
false
}
fn describe_call(&self, args: &Value) -> String {
match args.get("items").and_then(Value::as_array) {
Some(items) => format!("plan · {} step(s)", items.len()),
None => "plan · read".to_string(),
}
}
async fn call(&self, _args: Value) -> Result<String, ToolError> {
Err(ToolError::Failed(
"`plan` keeps a list per session, and this call names none".to_string(),
))
}
async fn call_scoped(&self, args: Value, scope: &CallScope<'_>) -> Result<String, ToolError> {
let session = scope.run.session.clone();
let Some(incoming) = self.parse_items(&args)? else {
return match self.store.plan(&session).map_err(failed)? {
Some(plan) => Ok(self.render(&plan, &[])),
None => Ok(
"no plan in this session yet — call `plan` with `items` to write the steps"
.to_string(),
),
};
};
plans::validate(&incoming).map_err(ToolError::InvalidArgs)?;
let merge = args.get("merge").and_then(Value::as_bool).unwrap_or(false);
let existing = self.store.plan(&session).map_err(failed)?;
let mut items = match (merge, existing) {
(true, Some(plan)) => plans::merge(&plan.items, &incoming),
_ => incoming,
};
let demoted = plans::one_in_progress(&mut items);
let revision = self.store.set_plan(&session, &items).map_err(failed)?;
Ok(self.render(&Plan { revision, items }, &demoted))
}
}
fn failed(error: crate::error::Error) -> ToolError {
ToolError::Failed(format!("{error}"))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tools::{AllowAll, RunScope, ToolRegistry};
struct Fixture {
_dir: tempfile::TempDir,
store: SessionStore,
}
fn fixture() -> Fixture {
let dir = tempfile::tempdir().unwrap();
let store = SessionStore::new(dir.path().to_path_buf());
Fixture { _dir: dir, store }
}
async fn call(store: SessionStore, args: Value) -> Result<String, ToolError> {
let tool = PlanTool::new(store);
let registry = ToolRegistry::new(4096);
let run = RunScope::new("s1");
let scope = CallScope {
approver: &AllowAll,
run: &run,
registry: ®istry,
call_id: None,
};
tool.call_scoped(args, &scope).await
}
#[tokio::test]
async fn a_write_then_a_read_gives_the_same_list_back() {
let f = fixture();
let out = call(
f.store.clone(),
json!({"items":[
{"id":"a","content":"read the audit","status":"done"},
{"id":"b","content":"fix the writer","status":"in_progress"},
{"id":"c","content":"release"}
]}),
)
.await
.unwrap();
assert!(out.starts_with("plan 1/3 · next b"), "{out}");
assert!(out.contains("[x] a read the audit"), "{out}");
assert!(out.contains("[~] b fix the writer"), "{out}");
assert!(out.contains("[ ] c release"), "{out}");
assert!(
out.contains("revision 1 · 1 pending, 1 in progress, 1 done, 0 cancelled"),
"{out}"
);
let read = call(f.store.clone(), json!({})).await.unwrap();
assert_eq!(
read, out,
"a read must be the same list a write answered with, revision included"
);
}
#[tokio::test]
async fn every_write_bumps_the_revision_so_two_surfaces_can_tell() {
let f = fixture();
call(
f.store.clone(),
json!({"items":[{"id":"a","content":"one"}]}),
)
.await
.unwrap();
let second = call(
f.store.clone(),
json!({"items":[{"id":"a","content":"one","status":"done"}]}),
)
.await
.unwrap();
assert!(second.contains("revision 2"), "{second}");
}
#[tokio::test]
async fn a_merge_patches_by_id_and_keeps_the_order() {
let f = fixture();
call(
f.store.clone(),
json!({"items":[
{"id":"a","content":"first"},
{"id":"b","content":"second"},
{"id":"c","content":"third"}
]}),
)
.await
.unwrap();
let out = call(
f.store.clone(),
json!({"merge":true,"items":[{"id":"b","content":"second, done","status":"done"}]}),
)
.await
.unwrap();
assert!(out.contains("[x] b second, done"), "{out}");
let order: Vec<&str> = out
.lines()
.filter(|l| l.starts_with('['))
.map(|l| l[4..].split_whitespace().next().unwrap())
.collect();
assert_eq!(order, ["a", "b", "c"], "b is still second: {out}");
assert!(out.contains("plan 1/3"), "{out}");
}
#[tokio::test]
async fn two_steps_in_progress_are_normalised_and_the_result_says_so() {
let f = fixture();
let out = call(
f.store.clone(),
json!({"items":[
{"id":"a","content":"first","status":"in_progress"},
{"id":"b","content":"second","status":"in_progress"}
]}),
)
.await
.unwrap();
assert!(out.contains("only one step can be `in_progress`"), "{out}");
assert!(out.contains("demoted to `pending` (b)"), "{out}");
assert!(out.contains("[ ] b second"), "{out}");
assert!(out.contains("1 pending, 1 in progress"), "{out}");
}
#[tokio::test]
async fn a_step_with_no_content_is_refused_and_the_list_is_untouched() {
let f = fixture();
call(
f.store.clone(),
json!({"items":[{"id":"a","content":"the real plan"}]}),
)
.await
.unwrap();
let refused = call(
f.store.clone(),
json!({"items":[{"id":"x","content":"ok"},{"id":"y","content":" "}]}),
)
.await
.unwrap_err();
assert_eq!(
refused.to_string(),
"invalid arguments: item 2 (`y`) has no `content`; a step with nothing to do cannot be \
done or dropped"
);
let read = call(f.store.clone(), json!({})).await.unwrap();
assert!(read.contains("a the real plan"), "{read}");
assert!(!read.contains(" x "), "nothing was written: {read}");
assert!(
read.contains("revision 1"),
"and the revision did not move: {read}"
);
}
#[tokio::test]
async fn an_unknown_status_names_the_word_and_the_ones_to_use() {
let f = fixture();
let refused = call(
f.store.clone(),
json!({"items":[{"id":"a","content":"x","status":"blocked"}]}),
)
.await
.unwrap_err();
assert!(
refused.to_string().contains("`blocked` is not a status"),
"{refused}"
);
assert!(
refused
.to_string()
.contains("`pending`, `in_progress`, `done` or `cancelled`"),
"{refused}"
);
}
#[tokio::test]
async fn an_empty_list_clears_the_plan() {
let f = fixture();
call(
f.store.clone(),
json!({"items":[{"id":"a","content":"one"}]}),
)
.await
.unwrap();
let out = call(f.store.clone(), json!({"items":[]})).await.unwrap();
assert!(out.starts_with("plan 0/0"), "{out}");
assert!(out.contains("(no steps)"), "{out}");
assert!(out.contains("revision 2"), "{out}");
}
#[tokio::test]
async fn a_session_with_no_plan_says_so_rather_than_inventing_one() {
let f = fixture();
let out = call(f.store.clone(), json!({})).await.unwrap();
assert_eq!(
out,
"no plan in this session yet — call `plan` with `items` to write the steps"
);
}
#[tokio::test]
async fn a_phase_is_a_step_and_its_children_name_it() {
let f = fixture();
let out = call(
f.store.clone(),
json!({"items":[
{"id":"writer","content":"the writer cluster","status":"in_progress"},
{"id":"#535","content":"array header ends a section","parent":"writer"}
]}),
)
.await
.unwrap();
assert!(
out.contains("#535 array header ends a section (in writer)"),
"{out}"
);
}
}