Cotton code
112 lines · 4.8 KB · RustRaw
//! A session's task list, read out of the agent's own task-tool call.//!//! **The agent's task list is a thing the phone can show, and nothing else in//! this host can see it.** Claude Code writes it with `TodoWrite`, one call//! per change, and the call carries the WHOLE list every time — so the hook//! that fires after that tool is the one place a complete, current list exists//! on this Mac. Cotton note "The project conversation — one standing thread per project" is what the phone//! does with it.//!//! This module is the translation and nothing else: hook JSON in, Cotton's own//! [`Task`] rows out. Pure, so every shape the agent can hand us is a test//! rather than a session on a Mac.//!//! **WHICH TOOL WRITES THE LIST IS THE AGENT'S SETTING, NOT OURS.** Claude//! Code 2.1.280 ships `TodoWrite` and a `TaskCreate`/`TaskUpdate` family, and//! `CLAUDE_CODE_ENABLE_TASKS` decides which one a session gets. Only//! `TodoWrite` is read here, because only `TodoWrite` carries the WHOLE list//! in one call — the Task family writes one task at a time, which is a list//! this host would have to keep rather than one it is handed. A session on the//! Task family mirrors no tasks at all; that is a gap, written down, not a//! half-list nobody can trust.//!//! **THREE THINGS IT NEVER DOES.** It never panics — a hook that crashed the//! turn is worse than a task list nobody saw. It never guesses a status: a//! word this host does not know is a task SKIPPED with a line on stderr, so a//! rename at the agent's end reads as a missing task and a log entry instead//! of as a task quietly filed as open. And it never turns an empty list into//! "no reading" — see [`Event::Tasks`](crate::protocol::Event::Tasks).use serde_json::Value;use crate::protocol::{Task, TaskStatus};/// The tool whose call carries the list, and the `PostToolUse` matcher the/// adapters register for it.////// Claude Code's own name. A matcher is a regex over the tool name, and this/// one is the whole name, so no other tool's `PostToolUse` costs a socket/// round trip.pub const TASKS_TOOL: &str = "TodoWrite";/// The hook event the list arrives on.pub const TASKS_EVENT: &str = "PostToolUse";/// The task list a `PostToolUse` payload carries, or `None` when it carries/// none.////// `None` means "this is not a task-list call" — a payload for another tool,/// or one whose `tool_input.todos` is missing or is not an array. It is NOT/// "the list is empty": that is `Some(vec![])`, and it clears the row.pub fn tasks_from_hook(session_id: &str, payload: &Value) -> Option<Vec<Task>> {    let tool_name = payload.get("tool_name").and_then(Value::as_str);    if tool_name.is_some_and(|name| name != TASKS_TOOL) {        // Matched by the agent, so this is the agent having changed which tool        // it writes its list with — said out loud rather than parsed anyway.        eprintln!(            "cotton-session-host: {session_id}: a {TASKS_EVENT} hook for `{}` reached the task reader, which only reads `{TASKS_TOOL}`",            tool_name.unwrap_or_default()        );        return None;    }    let items = payload.get("tool_input")?.get("todos")?.as_array()?;    let mut tasks = Vec::with_capacity(items.len());    for (index, item) in items.iter().enumerate() {        // SEQ IS THE INDEX IN THE AGENT'S OWN LIST, not the position among the        // tasks that survived this loop: a skipped task leaves a gap, and the        // gap is the truth about what the agent wrote.        let seq = index as u32;        let text = item            .get("content")            .and_then(Value::as_str)            .map(str::trim)            .unwrap_or_default();        if text.is_empty() {            eprintln!(                "cotton-session-host: {session_id}: task {seq} of a {TASKS_TOOL} call has no `content` — skipped"            );            continue;        }        let word = item.get("status").and_then(Value::as_str).unwrap_or_default();        let Some(status) = status_from_word(word) else {            eprintln!(                "cotton-session-host: {session_id}: task {seq} of a {TASKS_TOOL} call says status `{word}`, which this host does not know — skipped"            );            continue;        };        tasks.push(Task {            seq,            text: text.to_string(),            status,        });    }    Some(tasks)}/// Claude Code's word for a status, as Cotton's.////// The ONE place the two vocabularies meet. Anything else answers `None` —/// see this module's own note on why that is a skip and not a default.fn status_from_word(word: &str) -> Option<TaskStatus> {    match word {        "pending" => Some(TaskStatus::Open),        "in_progress" => Some(TaskStatus::Active),        "completed" => Some(TaskStatus::Done),        _ => None,    }}#[cfg(test)]#[path = "tasks_tests.rs"]mod tasks_tests;