Skip to content
jsmanifest logojsmanifest

Claude Code `TodoWrite` and Task Tracking in 2026: How the Built-In Todo System Keeps Long Agents on Rails

Claude Code `TodoWrite` and Task Tracking in 2026: How the Built-In Todo System Keeps Long Agents on Rails

Disclosure: jsmanifest has a financial interest in NoCensor AI and may earn from signups through links in this article.

Claude Code's built-in todo system gives long agent sessions a persistent, structured task list the model reads and writes between tool calls. This post explains how TodoWrite and the Task tools work, when to opt in, and how the underlying pattern keeps autonomous agents honest across hundreds of turns.

Long agent sessions fail in a specific way: the model loses its place. Twenty tool calls into a refactor, the context window fills with intermediate output, and a pending step that was clearly listed at the start quietly disappears. No error, no warning. The agent moves on and ships incomplete work.

An agent starts a multi-step task, context fills up, and a pending step silently drops, ending in failure

Claude Code's todo system addresses this directly. TodoWrite and the Task tools give the agent a persistent, structured state object it reads and writes between tool calls. Every turn, the agent re-anchors to what is pending, what is active, and what is finished. The list is visible in the message stream as structured tool_use blocks, so your application can log activity or render a live progress display without polling.

An agent writes a todo list, re-reads it each turn, and completes all steps before marking work done

Key Takeaways

  • TodoWrite is a structured tool call, not a chat summary. The agent reads and writes it between turns to maintain task state across long sessions.
  • Since Claude Code v2.1.268 (Agent SDK v0.3.268), the Task tools (TaskCreate, TaskGet, TaskUpdate, TaskList) are the default on Opus 4.7, Sonnet 4.6, Haiku 4.5, and earlier models. TodoWrite is the fallback when you set CLAUDE_CODE_ENABLE_TASKS=0.
  • Newer models track multi-step work without a written list. Opt in with CLAUDE_CODE_ENABLE_TODO_TOOLS=1 only when your application reads those tool_use blocks to log or display progress.
  • Each todo item moves through a predictable lifecycle: pending to in_progress to completed or deleted.
  • The pattern of externalizing task state works regardless of which specific tool carries it.

What TodoWrite Actually Is: A Structured State Object, Not a Chat Summary

TodoWrite is a tool call in the same category as Edit or Bash. When Claude calls it, the agent is writing a structured list of items into a slot that persists across turns and that the model can read back on demand. It is not prose written for the developer's benefit. It is working memory the agent uses to plan, re-anchor, and self-audit.

Claude calls TodoWrite like any tool call, writing structured state that persists and is read back each turn

This distinction matters for how you instrument your application. Because every update lands in the message stream as a tool_use block, your code can capture task state without any side channel. Per the Claude Code task tracking documentation, you see each change as a structured tool call, which means a standard message stream handler is enough to build a full progress log.

The agent also receives a nudge after each TodoWrite call: a reminder pointing it toward the next pending item. That nudge keeps the agent from treating the list as write-only bookkeeping and actually using it to sequence work.

TodoWrite structured state diagram

The Three Fields Every Todo Item Carries and How the Agent Uses Them

Each todo item has three core fields: a subject, a status, and an activeForm label. The subject is the human-readable description of the work. The status drives the lifecycle. The activeForm label is what your progress display should show when the item is in flight, because it reflects what the agent is actually doing at that moment rather than the original plan description.

A todo item moves from pending to in_progress, then to completed or deleted

According to the task tracking documentation, the lifecycle is:

  1. Created: the agent adds the item as pending when it identifies the task.
  2. Activated: the agent sets it to in_progress when it begins the work.
  3. Completed: the agent marks it done when the step finishes successfully.
  4. Removed: the agent sets status: "deleted" in a TaskUpdate call for items it no longer needs.

Only one item should be in_progress at a time under normal circumstances. That constraint is what gives the list its diagnostic value: if two items are simultaneously active, something in the sequencing has gone wrong. When you read TaskUpdate blocks from the stream, read the input fields defensively. Claude Code repairs some close-but-incorrect key names before execution (mapping id or task_id to taskId, and active_form to activeForm), but that repair is not reflected in the raw stream your handler sees.

TodoWrite in Practice: Tracing a Multi-Step Refactor From Plan to Done

The following TypeScript example opts a session into the task tools with CLAUDE_CODE_ENABLE_TODO_TOOLS=1, watches the message stream for TaskCreate and TaskUpdate blocks, and maintains a live map of tasks keyed by ID. It follows the shape described in the task tracking documentation for the "Display progress in real time" pattern.

import { query, type Message } from "@anthropic-ai/claude-code";
 
interface TaskItem {
  id: string;
  subject: string;
  status: string;
  activeForm?: string;
}
 
class TaskTracker {
  private tasks = new Map<string, TaskItem>();
  private pendingCreate = new Map<string, string>(); // tool_use_id -> subject
 
  handleToolUse(block: { id: string; name: string; input: Record<string, unknown> }) {
    if (block.name === "TaskCreate") {
      const subject = (block.input.subject ?? block.input.title ?? "") as string;
      this.pendingCreate.set(block.id, subject);
    }
 
    if (block.name === "TaskUpdate") {
      // Read defensively: Claude Code repairs key names before execution,
      // but the raw stream may carry the pre-repair names.
      const taskId = (
        block.input.taskId ??
        block.input.task_id ??
        block.input.id
      ) as string | undefined;
      const status = block.input.status as string | undefined;
      const activeForm = (
        block.input.activeForm ?? block.input.active_form
      ) as string | undefined;
 
      if (taskId && this.tasks.has(taskId)) {
        const task = this.tasks.get(taskId)!;
        if (status) task.status = status;
        if (activeForm) task.activeForm = activeForm;
        this.render();
      }
    }
  }
 
  handleToolResult(
    toolUseId: string,
    result: Record<string, unknown> | undefined
  ) {
    const subject = this.pendingCreate.get(toolUseId);
    if (subject == null) return;
    this.pendingCreate.delete(toolUseId);
 
    // The assigned task ID arrives in the tool_use_result of the
    // tool_result block paired with the TaskCreate call.
    const taskId = (result as { task?: { id?: string } })?.task?.id;
    if (taskId) {
      this.tasks.set(taskId, { id: taskId, subject, status: "pending" });
      this.render();
    }
  }
 
  render() {
    const completed = [...this.tasks.values()].filter(
      (t) => t.status === "completed"
    ).length;
    const inProgress = [...this.tasks.values()].filter(
      (t) => t.status === "in_progress"
    );
 
    console.clear();
    console.log(`Tasks: ${completed}/${this.tasks.size} completed`);
    for (const task of inProgress) {
      console.log(`  > ${task.activeForm ?? task.subject}`);
    }
  }
}
 
async function runWithProgress(prompt: string) {
  const tracker = new TaskTracker();
 
  try {
    for await (const message of query({
      prompt,
      options: {
        permissionMode: "acceptEdits",
        env: {
          ...process.env,
          CLAUDE_CODE_ENABLE_TODO_TOOLS: "1",
        },
      },
    })) {
      if (message.type === "assistant") {
        for (const block of message.message.content) {
          if (block.type === "tool_use") {
            tracker.handleToolUse(
              block as { id: string; name: string; input: Record<string, unknown> }
            );
          }
        }
      }
 
      if (message.type === "user") {
        for (const block of message.message.content) {
          if (
            block.type === "tool_result" &&
            typeof block === "object" &&
            "tool_use_id" in block
          ) {
            const b = block as {
              tool_use_id: string;
              tool_use_result?: Record<string, unknown>;
            };
            tracker.handleToolResult(b.tool_use_id, b.tool_use_result);
          }
        }
      }
    }
  } catch (err: unknown) {
    if (
      err instanceof Error &&
      err.message.includes("Reached maximum number of turns")
    ) {
      console.error("Session hit turn limit — partial output may be available.");
    } else {
      throw err;
    }
  }
}
 
runWithProgress(
  "Refactor the AuthService: extract token validation to a separate class, " +
  "add unit tests for each public method, and update the README."
);

A few points to call out. The env option in TypeScript replaces the subprocess environment entirely, so spreading ...process.env is necessary to keep inherited variables. The assigned task ID is not available in the TaskCreate input block. It arrives later, in the tool_use_result field on the tool_result block that pairs with that TaskCreate call by tool_use_id. Matching those two blocks is what lets the tracker correlate subsequent TaskUpdate calls back to the original subject.

If you only want a log of task activity and do not need to correlate updates back to creates, the simpler "Monitor todo changes" shape from the documentation works: print a line on every TaskCreate input and another on every TaskUpdate input, without maintaining a map.

// Minimal log-only variant
for await (const message of query({ prompt, options: { env: { ...process.env, CLAUDE_CODE_ENABLE_TODO_TOOLS: "1" } } })) {
  if (message.type !== "assistant") continue;
  for (const block of message.message.content) {
    if (block.type !== "tool_use") continue;
    if (block.name === "TaskCreate") {
      console.log(`+ ${(block.input as { subject?: string }).subject ?? "(unnamed)"}`);
    }
    if (block.name === "TaskUpdate") {
      const input = block.input as { taskId?: string; task_id?: string; id?: string; status?: string };
      const id = input.taskId ?? input.task_id ?? input.id ?? "?";
      console.log(`~ ${id} -> ${input.status ?? "unknown"}`);
    }
  }
}

This variant cannot match updates back to their creates because the + lines do not include the assigned IDs, but it is enough for a simple audit trail or a CI step that just needs to confirm work completed.

For long-running autonomous sessions, also consider how checkpoints and state restoration interact with the task list. If a session is restored from a checkpoint, the task tools reconstruct their state from the message history, so the tracker your application maintains should be rebuilt from the stream replay.

Agent task tracker rendering live progress

TodoWrite vs the Task Tool: Which to Reach For and When

Since Claude Code v2.1.268 (Agent SDK v0.3.268), two distinct tool sets handle task tracking, and which one runs depends on configuration.

A decision card branches to the Task tools or the legacy TodoWrite based on the CLAUDE_CODE_ENABLE_TASKS flag

DimensionTask tools (TaskCreate / TaskUpdate / etc.)TodoWrite (legacy fallback)
AvailabilityDefault on Opus 4.7, Sonnet 4.6, Haiku 4.5, and earlierActive when CLAUDE_CODE_ENABLE_TASKS=0
Item identityEach item gets an assigned ID; updates correlate by IDNo persistent IDs; list is rewritten wholesale
Stream shapeSeparate TaskCreate and TaskUpdate blocksSingle TodoWrite block per update
activeForm labelPresent on in-progress items for displayNot available
ID correlationRequires pairing tool_result to tool_use by tool_use_idNot applicable
Lifecycle granularitypending, in_progress, completed, deletedStatuses in the written list

The Task tools are the right default for any application that renders a progress display, because the assigned IDs let you match updates to their original creates. TodoWrite is simpler: one call rewrites the entire list, so there is no correlation step. Use it when the session runs on an older model and your application only needs to know the current list state at any point in time, not the full history of transitions.

Subagents inherit whatever tools the parent session has. Per the task tool availability documentation, a subagent has the task-tracking tools only when your session has them, regardless of which model the subagent runs. The same constraint applies to in-process agent team teammates. For split-pane teammates, the inheritance rules are different and worth reviewing before you rely on task tracking in a multi-agent setup. This interplay is worth understanding alongside CI-integrated agentic review workflows, where subagents are common.

What Changed in 2026: Opt-In Flags, the Task System Upgrade, and the Legacy Fallback

As of Claude Code v2.1.268 (Agent SDK v0.3.268), newer models track multi-step work without a written checklist, and the tools' definitions take up context that is no longer justified by default. The task tool availability documentation states that on every model that is not Opus 4.7, Sonnet 4.6, Haiku 4.5, or an earlier model, Claude Code leaves the task-tracking tools out unless you opt in.

A session checks the model and flags, then enables the Task tools, falls back to TodoWrite, or skips tracking

Three ways to opt a session into the tools on a newer model:

  • Set CLAUDE_CODE_ENABLE_TODO_TOOLS=1 in the env option. In TypeScript, spread ...process.env alongside this because env replaces the subprocess environment. In Python, env is merged on top of the inherited environment, so spreading is not required.
  • Name one of the tools in allowedTools (TypeScript) or allowed_tools (Python).
  • List the tools explicitly in the tools option, which restricts the session's built-in tools to the ones it names.

If you point pathToClaudeCodeExecutable (TypeScript) or cli_path (Python) at your own Claude Code install rather than the bundled binary, you get whichever defaults that install provides. To confirm what is actually available in a running session, check which tools are available rather than inferring from the model name. The CLAUDE_CODE_ENABLE_TASKS=0 flag is the specific switch that keeps task tracking active but reverts to the simpler TodoWrite tool, dropping the full Task tool suite. This is relevant when your existing stream handler was written against the TodoWrite shape and you are not ready to migrate it to the ID-correlation pattern.

Managing costs is a related concern when opting into additional tools on long sessions. The tool definitions and reminders add context, which adds tokens. The cost control guidance for production agents covers how to account for that overhead.

Frequently Asked Questions

What is the difference between TodoWrite and TaskCreate in Claude Code?

TodoWrite is the legacy single-call tool that rewrites the entire task list in one block. TaskCreate is part of the newer Task tool suite (also including TaskGet, TaskUpdate, and TaskList) that gives each item a persistent ID and reports creation and updates as separate stream events. The Task tools are the default on Opus 4.7, Sonnet 4.6, and Haiku 4.5; TodoWrite becomes active when you set CLAUDE_CODE_ENABLE_TASKS=0.

When should a session opt into the task-tracking tools in 2026?

Opt in when your application reads the tool_use blocks in the message stream to log task activity or render a progress display. On newer models that are not Opus 4.7, Sonnet 4.6, or Haiku 4.5, the tools are off by default because those models track multi-step work internally. Set CLAUDE_CODE_ENABLE_TODO_TOOLS=1 in the env option to enable them without restricting any other tools.

Why should TaskUpdate input fields be read defensively?

Claude Code repairs some close-but-incorrect key names before it executes the tool call, mapping id or task_id to taskId and active_form to activeForm. That repair does not appear in the raw stream your handler sees. Reading both the canonical and pre-repair key names guards against receiving the unreleased variant.

How do subagents inherit the task-tracking tools?

A subagent has the task-tracking tools only when the parent session has them. The model the subagent runs on does not determine this. For in-process agent team teammates, the same rule applies. Split-pane teammates are separate processes and inherit --tools lists and deny rules, but not --allowedTools, so their task tool availability depends on that narrower set.

Can the task list be rebuilt after a session is restored from a checkpoint?

The Task tools reconstruct their state from the message history when a session resumes. Any application-side tracker should replay the stream from the restored point to rebuild its own map of task IDs and statuses.

Externalizing Task State: Why the Underlying Pattern Outlives Any Specific Tool

TodoWrite as a named tool will change. The Task suite will evolve. Newer models will continue to reduce the need for explicit written tracking as internal planning improves. What stays constant is the pressure that causes long agent sessions to fail: the context window is finite, intermediate outputs are noisy, and the model's attention is not uniformly distributed across a long history.

Externalizing task state into a structured, persistent, re-readable object is the response to that pressure. Whether the object is a TaskCreate call, a TodoWrite call, a custom tool backed by a database, or a file the agent reads and rewrites directly, the effect is the same. The agent has a canonical record of what is left to do that does not degrade as the conversation grows. When you build agent workflows that run for more than a handful of turns, that canonical record is not optional infrastructure. It is the difference between a session that reliably finishes its work and one that confidently ships a partial result.

The specific opt-in flags and default behaviors documented here apply to Claude Code v2.1.268 and later, with the TypeScript Agent SDK from v0.3.268. Check the task tracking documentation and tool availability reference for your installed version before assuming defaults.

Sources