Chapter 4 · Long-Task Continuity Management
Chapter goals: Understand why agents "lose the thread" during long tasks, master state persistence techniques, and learn strategies to cope with context anxiety.
4.1 The Cross-Session Dilemma
You ask Claude Code to implement a full feature. It runs for 30 minutes, completes most of the work, but context is about to run out. You open a new session to continue — only to find it doesn't remember what decisions were made last time, why option A was chosen over B, which files were modified, or what the test status was. It spends 15 minutes re-exploring the project and may adopt a method inconsistent with last time.
This is the real dilemma AI coding agents face on cross-session tasks.
4.2 The Context Window Is Not Infinite
The context window is finite. This is not a problem that model upgrades can solve — even if the window expands to 1M tokens, complex tasks will still exhaust it. Agents don't just generate code; they understand codebases, track their own decision history, process tool outputs, and maintain conversation context. All this information grows faster than the window expands.
The deeper problem: the information an agent produces is unevenly important. Intermediate reasoning steps contain the "why" of decisions — why A was chosen over B, why this library over that, why a certain optimization was skipped. The final output only contains the "what" — the code itself. Compression strategies usually preserve the latter but lose the former. The next session sees the code but doesn't know why it was written that way, and may "optimize away" a deliberate design decision.
Anthropic observed an interesting phenomenon in their long-running agent research: when agents sense context is running low, they exhibit "rushed wrap-up" behavior — hurrying to finish current work, skipping verification steps, choosing simple solutions over optimal ones. They call this context anxiety.
4.3 With vs. Without State Persistence
Without state persistence, every new session starts from scratch:
Session 1 (feature half done) → context nearly full → session ends
↓
Session 2 starts over → re-reads folders, re-runs tests, guesses why code is written this way → duplicated work, slow recoveryWith state persistence, the new session picks up quickly:
Session 1 work → PROGRESS.md (done/in-progress/next)
→ DECISIONS.md (why this approach was chosen)
→ Verification records (which tests pass/fail)
→ Git checkpoint (precise repo state)
↓
Session 2 rebuilds → picks up quickly4.4 Core Concepts
| Term | Meaning |
|---|---|
| State Persistence Files | Persistent files that let a new session clearly pick up where the last left off. The most basic forms include progress logs, verification records, and next actions |
| Rebuild Cost | The time a new session needs to reach an executable state. A good harness can compress this from 15 minutes down to 3 |
| Drift | The gap between the agent's understanding and the actual repo state. Each session boundary introduces drift; uncontrolled, it accumulates session by session |
| Context Anxiety | The phenomenon observed by Anthropic — agents exhibit rushed wrap-up behavior when approaching context limits |
| Compaction vs. Reset | Compaction summarizes context within the same session (preserves "what", may lose "why"); reset opens a new session rebuilding from persistent state (clean but depends on artifact completeness) |
4.5 The Cost of Continuity Breaks
Last session spent a large chunk of context budget analyzing three approaches and choosing B. This session's agent doesn't know about that analysis and may re-decide based on incomplete information — possibly even choosing A. Same information, different conclusion, because the decision context is gone.
Worse still is duplicated work. The agent isn't sure whether some work was already done, so it does it again. Or worse — does it halfway, discovers a conflict with the existing implementation, and has to redo it. Without progress records, a new session doesn't know what's already done.
After multiple sessions, the implementation direction may have subtly drifted from the original requirement. Each new session has a slightly different understanding of the project goal. Each deviation accumulates session by session, and the final result may end up far from the original intent.
There's also the verification gap. Last session's verification results (which tests passed, which failed, why) weren't recorded. The new session must re-run all verification to understand the current state. Diagnosing from scratch every session wastes precious context every time.
4.6 State Persistence Practices
The core idea: treat the agent as an engineer whose short-term memory is wiped between sessions. Before it "clocks out," it must write down key information so the next "on-duty" agent can pick up quickly.
Tool 1: Progress File (PROGRESS.md)
The most basic state persistence file:
# Project Progress
## Current State
- Latest commit: abc1234 (feat: add user preferences endpoint)
- Test status: 42/43 passed (test_pagination_edge_case failing)
- Lint: passed
## Done
- [x] User model and database migration
- [x] Basic CRUD endpoints
- [x] Auth middleware integration
## In Progress
- [ ] Pagination feature (90% — edge case test failing)
## Known Issues
- test_pagination_edge_case returns 500 on empty result set
- Need to confirm whether deleted users should appear in the list
## Next Steps
1. Fix pagination edge case bug
2. Add "include deleted users" query parameter
3. Update API documentationTool 2: Decision Log (DECISIONS.md)
Record important design decisions and their rationale. You don't need detailed design docs — just "what decision, why, when":
# Design Decisions
## 2024-01-15: Use Redis cache for user preferences
- Reason: High-frequency reads (every API call), small data volume
- Dismissed alternative: PostgreSQL materialized views (high-frequency changes make maintenance costs unjustifiable)
- Constraints: Cache TTL 5 minutes, invalidate on writeTool 3: Git Commits as Checkpoints
Commit after completing each atomic unit of work. Commit messages should explain what was done and why. This is free, automatically versioned state snapshots.
Tool 4: init.sh or the Harness Initialization Flow
Specify the "clock in" and "clock out"流程 in AGENTS.md:
## Session Start (Clock In)
1. Read PROGRESS.md to understand current state
2. Read DECISIONS.md to understand important decisions
3. Run make check to confirm repo state is consistent
4. Pick up from the "Next Steps" section in PROGRESS.md
## Session End (Clock Out)
1. Update PROGRESS.md
2. Run make check to confirm state consistency
3. Commit all completed workMixed Strategy
Not every task needs a context reset. Short tasks (under 30 minutes) can be completed in one session. Long tasks (across sessions) must use progress files and decision logs to maintain continuity. The判断criterion: if the task needs more than 60% of the window, start preparing for handoff.
4.7 Understanding Context Anxiety in Depth
Anthropic's March 2026 research further revealed the specific manifestations of context anxiety: on Sonnet 4.5, when context approaches the window limit, agents exhibit strong "rushed wrap-up" behavior.
Two coping strategies:
Compaction: summarize context within the same session. Preserve "what", may lose "why". Suitable for short breaks. Reset: open a new session rebuilding from persistent state. Clean but depends on artifact completeness. Suitable for long pauses or when context is extremely tight.
Selection criterion: if the task clearly crosses session boundaries, use reset; if it's just a brief interruption, use compaction.
4.8 Chapter Summary
- Context windows are finite; complex tasks will eventually exhaust them
- State persistence files let new sessions clearly pick up where the last left off
- Rebuild cost is a key metric for measuring harness quality
- Drift accumulates session by session and must be proactively controlled
- Context anxiety causes rushed wrap-up; mitigate with persistence
- PROGRESS.md + DECISIONS.md + git commits + init.sh are the four key tools
🧪 随堂测验
点击你认为正确的选项。答错时会展示正确答案与原因解析。
1. What does "context anxiety" (上下文焦虑) refer to?
2. Which of the following methods CANNOT effectively reduce cross-session drift?
3. What does rebuild cost measure?
4. What is the main difference between compaction and reset?
🛠️ Hands-on Practice
- Create a PROGRESS.md template for a long task (>30 minutes), including current state, done, in progress, known issues, and next steps.
- Run a cross-session experiment: session 1 does half then stops, session 2 reads only PROGRESS.md to pick up — record the rebuild cost.
- Implement the clock-in/clock-out flow in init.sh so the agent automatically reads and writes state files each session.
Next chapter: Control Mechanisms: Preventing Scope Creep and Premature Victory