Applies one mutation to the session todo list and returns a text summary plus the full phase/task state.
Source
- Entry:
packages/coding-agent/src/tools/todo.ts - Model-facing prompt:
packages/coding-agent/src/prompts/tools/todo.md - Key collaborators:
packages/coding-agent/src/tools/index.tsโ registers tool, exposes session hooks, gates availability.packages/coding-agent/src/modes/controllers/event-controller.tsโ updates the visible todo UI on tool completion.packages/coding-agent/src/session/agent-session.tsโ stores cached phases, strips done/dropped tasks on session resume, emits failure reminders.packages/coding-agent/src/modes/controllers/todo-command-controller.tsโ/todocommand path, custom-entry persistence, transcript reminder injection.packages/coding-agent/src/tools/render-utils.tsโ collapsed-preview cap for renderer trees.
Inputs
The params object is a single op โ the discriminator and its fields live at the top level (no ops array wrapper).
| Op | Required fields | Optional fields | Effect |
|---|---|---|---|
init | list or flat items | phase (names the phase for the flat items form; defaults to Tasks) | Replaces the entire list โ with list, uses the given phases; with a flat items array, synthesizes one phase. Every new task starts pending before normalization. |
start | task | None | Marks one task in_progress; any other in_progress task is demoted to pending. |
done | task or phase or neither | None | Marks the target task, phase, or all tasks completed. |
drop | task or phase or neither | None | Marks the target task, phase, or all tasks abandoned. |
rm | task or phase or neither | None | Removes the target task, clears the phaseโs task list, or clears all task lists. |
append | phase, items | None | Appends new pending tasks to a phase; creates the phase if missing. |
view | None | None | Echoes the current list. A view call is read-only: no normalization, no state write. |
Fields
| Field | Type | Required | Description |
|---|---|---|---|
op | `โinit" | "start" | "done" |
list | { phase: string; items: string[] }[] | For init (unless a flat items list is given) | Full replacement payload. Each items array has minItems: 1. |
task | string | For start; for task-targeted done/drop/rm | Exact task content match. |
phase | string | For append; for phase-targeted done/drop/rm; optional for a flat init | Exact phase name match, except append lazily creates a missing phase and a flat init synthesizes one (default Tasks). |
items | string[] | For append; or as a flat init payload | Tasks to append, or the full task list for a flat init. minItems: 1. |
Outputs
The tool returns a single-shot AgentToolResult:
content: one text part containing the summary fromformatSummary(...).- Empty final state with no errors:
Todo list cleared.(Todo list is empty.for a pure-viewcall). - Non-empty final state: remaining-item list, current phase progress, then a per-phase tree.
- If the op produced validation/runtime errors, the summary starts with
Errors: ...and the result is markedisError: true; the mutation is discarded โ the returned and persisted state stay at the pre-call list.
- Empty final state with no errors:
details:phases: TodoPhase[]storage: "session" | "memory"completedTasks?: TodoCompletionTransition[]when a task changed from non-completed tocompletedduring the call
TodoPhase / TodoItem state model:
TodoPhase:{ name: string, tasks: TodoItem[] }TodoItem:{ content: string, status: "pending" | "in_progress" | "completed" | "abandoned" }
The TUI renderer (todoToolRenderer) merges call and result into one transcript block and renders phases as a tree. Collapsed transcript previews cap tree items at PREVIEW_LIMITS.COLLAPSED_ITEMS (8).
Flow
TodoTool.execute(...)clones the current cached phases fromsession.getTodoPhases?.() ?? [](packages/coding-agent/src/tools/todo.ts).applyParams(...)applies the single op (params) withapplyEntry(...).- Each op mutates the working phase array:
initPhases(...)rebuilds the list from scratch.startresolves a task by exactcontent, demotes every otherin_progresstask topending, then marks the targetin_progress.done/dropusegetTaskTargets(...)to target one task, one phase, or every task.rmremoves one task, clears one phaseโstasks, or clears all phasesโ task arrays.appendItems(...)resolves or creates the target phase and pushes newpendingtasks unless the same task content already exists anywhere.
- Missing task/phase references are recorded in an
errorsarray byresolveTaskOrError(...)/resolvePhaseOrError(...); any error discards the opโs mutations at the end. - After the op,
normalizeInProgressTask(...)enforces the single-active-task invariant:- if multiple tasks are
in_progress, only the first stays active and the rest becomepending; - if none are
in_progress, the firstpendingtask in phase/task order is auto-promoted toin_progress.
- if multiple tasks are
execute(...)stores the updated phases withsession.setTodoPhases?.(...)only when the op produced no errors and was not aview; a failed op is discarded (persisting a half-applied mutation would make the natural retry hit โalready existsโ).storageis"session"whensession.getSessionFile()exists, else"memory".getCompletionTransitions(...)compares the previous and updated phases (skipped for failed orviewcalls); newly completed tasks are returned indetails.completedTasks.- The agent runtime also watches
todotool results inpackages/coding-agent/src/session/agent-session.ts; successful results refresh cached todos, failed results inject a hidden next-turn reminder telling the model that todo progress is not visible until it retries. - The event controller updates the visible todo UI from
result.details.phaseson success, or shows a warning on error (packages/coding-agent/src/modes/controllers/event-controller.ts).
Modes / Variants
State transitions
| Current status | start | done | drop | rm | append |
|---|---|---|---|---|---|
pending | in_progress on target | completed | abandoned | Removed | New tasks enter as pending |
in_progress | Target stays in_progress; non-target active tasks become pending | completed | abandoned | Removed | No status change |
completed | Can be set back to in_progress if targeted | Stays completed | Becomes abandoned if targeted | Removed | No status change |
abandoned | Can be set back to in_progress if targeted | Becomes completed if targeted | Stays abandoned | Removed | No status change |
Normalization then re-applies the single-active-task rule after the op runs.
Op targeting rules
done,drop,rm:taskset: affect one exact-content task.- else
phaseset: affect every task in that exact-name phase. - else: affect every task in every phase.
appendis the only op that creates a missing phase.initdiscards previous phases entirely.
Markdown round-trip helpers
The same file also exposes non-tool helpers used by /todo:
phasesToMarkdown(...)serializes phases as headings plus checklist items ([ ],[/],[x],[-]).markdownToPhases(...)parses that format, defaults orphan tasks into aTodosphase, accepts>as anin_progressmarker and~asabandoned, and runs the same normalization step.
Side Effects
- Filesystem
- None in the tool itself.
- Session state (transcript, memory, jobs, checkpoints, registries)
- Mutates the session todo cache through
setTodoPhases. storagereports whether the session has a backing session file, but the tool does not append a custom session entry itself.- Successful tool-result messages carry
details.phases;getLatestTodoPhasesFromEntries(...)can reconstruct state later from those transcript entries. - Failed
todoresults causeagent-sessionto enqueue a hidden next-turn reminder (customType: "todo-error-reminder").
- Mutates the session todo cache through
- User-visible prompts / interactive UI
- Transcript block is rendered by
todoToolRendererand merged with the call line. event-controllerupdates the visible todo panel from successful results.- On error,
event-controllershowsTodo update failed...; the visible panel may stay stale until a later successful call.
- Transcript block is rendered by
- Background work / cancellation
- Session-level auto-clear of
completed/abandonedtasks was removed (the timer mutated canonical phases between tool calls); the TUI todo widget still clears closed entries aftertasks.todoClearDelay(display-only,packages/coding-agent/src/modes/interactive-mode.ts).
- Session-level auto-clear of
Limits & Caps
init.list: applies to a single op (todoSchema). The params object carries exactly one op.init.list[*].items:minItems: 1.append.items:minItems: 1.- Renderer collapsed preview:
PREVIEW_LIMITS.COLLAPSED_ITEMS = 8(packages/coding-agent/src/tools/render-utils.ts). - Auto-clear delay:
tasks.todoClearDelaydefault60seconds;< 0disables auto-clear,0clears immediately. Display-only โ applied by the TUI widget (packages/coding-agent/src/modes/interactive-mode.ts); the setting is inert at the session level. - Tool execution mode:
concurrency = "exclusive",strict = true,loadMode = "discoverable".
Errors
- Ordinary bad op payloads are accumulated as human-readable strings in
errors; the result is markedisError: trueand the mutation is discarded โ the returned and persisted state stay at the pre-call list. - Error strings come from the helpers in
packages/coding-agent/src/tools/todo.ts, including:Missing list for init operationMissing task contentDuplicate phase "..." in init list/Duplicate task "..." in init listTask "..." not foundwith an extra empty-list hint when applicable, or a hint that tasks are referenced by content (nottask-NIDs) when the missing content looks like an IDMissing phase namePhase "..." not foundMissing phase name for append operationMissing items for append operationTask "..." already exists
- A
todocall carries a single op; any error in it discards every mutation the op made. - Runtime-level tool failure is handled outside the tool body:
agent-sessioninjects a hidden reminder and the event controller warns the user that visible progress may be stale. - Idempotency is op-specific:
initis a full replacement; replaying the same payload yields the same state.start,done, anddropare effectively idempotent on an existing target state, butstartalso demotes any other active task.rmis not idempotent for targeted removals: the second call errors because the task or phase is gone.appendis not idempotent: duplicate task content is rejected withTask "..." already exists; theappendop validates up front, so an op with any duplicate appends nothing.
Notes
- Task lookup is exact string equality inside the tool. The model-facing prompt says task content and phase names are identifiers and should stay unique;
appendenforces task uniqueness globally, andinitrejects duplicate phase names and duplicate task contents in its payload. findTaskByContent(...)returns the first matching task across phases. Duplicate task contents make later targeted ops ambiguous.normalizeInProgressTask(...)runs once after the op, not mid-op. A single op (e.g.init) can build an intermediate invalid state and rely on final normalization.storage: "session"means the session has a session-file backing; it does not mean this tool wrote a durable custom entry.- Reload persistence differs by path:
- plain
todocalls survive in transcript tool-result details; /todocommand edits additionally appendcustomType: "user_todo_edit"entries and inject a visible-to-model<system-reminder>developer message describing the manual edit.
- plain
- On session resume,
AgentSession.#syncTodoPhasesFromBranch()stripscompletedandabandonedtasks before restoring the cached list. The/todocommand works around that by reading the latest transcript/custom-entry state so historical done/dropped tasks still appear to the user. - Tool availability is gated by
todo.enabled, and the registry excludes it whenincludeYieldis enabled (packages/coding-agent/src/tools/index.ts). - Subagents do not inherit
todo;packages/coding-agent/src/task/executor.tsfilters it out as a parent-owned tool.