Sub topic 14
Putting It Together: A Routine for Long Sessions
Earlier chapters covered the parts of context management one at a time: what fills the window, how to measure it, how to read and run commands narrowly, how to compact, and how to hand off work. This chapter combines them into one routine you can follow during a multi-hour task.
This chapter assumes you have used a coding agent in a terminal or editor and are comfortable with git and the command line. It also assumes you know a token is a unit of text a model reads, and that the model can only take in a limited number of tokens at once.
The routine at a glance
The routine has three kinds of actions. You do some at the start of a task, some continuously while working, and some at checkpoints. At each checkpoint you choose one of three outcomes: keep going, compact, or start a fresh session.
Step 1: Begin with a scoped task and a small prefix
A long session is easier to manage when it is made of tasks that each fit in one context. Before you start, split the work into subtasks that each have a clear finish line, such as "tests for the loader pass" or "docs page updated." A task that ends with something you can verify is a natural place to stop and reset.
Keep your persistent project instructions short and stable. They load at the start of every session, so every line costs tokens each time. A stable prefix also lets the provider's prompt caching reuse the repeated beginning of the conversation. Editing the instructions in the middle of a session can break that reuse, so make instruction changes between sessions.
Then write the plan to a file before you do anything else. The notes file is what lets you reset later without losing work.
# PROGRESS.md
## Goal
Migrate the settings loader from INI to TOML without changing the public API.
## Decisions
- Keep `load_settings()` signature unchanged.
- Use the standard library `tomllib` for parsing (read-only).
## Done
- [x] Added TOML parser path in `config.py`
- [x] Updated unit tests for the loader
## Next
- [ ] Update the docs page for configuration
- [ ] Run the full test suite and fix failures
## Open questions
- Should INI files still be accepted with a deprecation warning?Step 2: Work with narrow reads and capped output
Most context growth during the work phase comes from two sources: file contents and command output. Control both at the point where they enter the conversation.
For code, find the location first and then read only the lines around it. A capped search followed by a line range puts a few dozen lines into the context instead of a whole file.
# Find the definition first, then read only the lines around it
grep -rn "def parse_config" src | head -n 20
sed -n '120,180p' src/config.pyFor test runs, stop at the first failure and keep only the end of the log, where the failure summary appears.
# Keep only the end of a long test run, where the failure summary appears
pytest -x -q 2>&1 | tail -n 30If you build your own tools or wrappers, bound the size of results in code. This helper keeps the start and the end of long output and marks the omitted middle.
def truncate_output(text, max_lines=60, head=20, tail=20):
lines = text.splitlines()
if len(lines) <= max_lines:
return text
omitted = len(lines) - head - tail
return "\n".join(lines[:head] + [f"... {omitted} lines omitted ..."] + lines[-tail:])A noisy investigation, such as scanning many files to answer one question, is a good candidate for a subagent. The subagent does the reading in its own context and returns a short answer. Only that answer enters your main session.
Step 3: Check usage at checkpoints
Do not wait for the window to fill. Check usage at natural boundaries: after finishing a subtask, after a large read, and after a long test run. Most agents have a command or status line that shows how much of the window is used. Use whichever your tool provides.
Usage alone does not tell you everything. Quality matters too. Watch for the symptoms of a crowded context:
- The agent re-asks questions you already answered.
- It contradicts an earlier decision.
- It re-reads files it has already read.
- It forgets conventions from your instructions.
- Edits become less precise, for example touching the wrong function or repeating a rejected approach.
The numbers below are starting points, not rules. The right thresholds depend on your model and tool, so adjust them after a few sessions.
| Situation | Signal | Action |
|---|---|---|
| Healthy | Usage is moderate, agent follows decisions | Keep going |
| Filling up | Usage passes roughly half the window, task is not finished | Plan to compact at the next subtask boundary |
| Crowded | Usage is high, or you see repeated questions or contradictions | Compact now, then verify |
| Wrong direction | Several failed attempts, long dead-end history | Fresh session from the notes file |
| Subtask finished | Verified result, next subtask is unrelated | Update notes, fresh session |
Step 4: Compact with instructions, then verify
Compaction replaces the history with a summary. An unguided summary may drop the reasons behind a decision, which is the information you most need later. Give the compaction an explicit list of what to keep and what to drop.
Summarize this session for continuation. Keep:
1. The overall goal and the current subtask.
2. Decisions made and the reasons for them.
3. Files changed, with a one-line description of each change.
4. Failing tests or errors that are still unresolved.
5. The next three steps.
Drop: exploratory dead ends, full file contents, and raw command output.After compaction, verify the summary before you continue. Compare it with your notes file and check three things:
- Every decision in
PROGRESS.mdappears in the summary, with its reason. - The list of changed files matches
git status. - The next steps match what you intended.
If something is missing, tell the agent directly, or restore it by pointing the agent at the notes file. Because the decisions also live in the file, a lossy summary costs you a correction, not the work.
Step 5: Hand off to a fresh session
A fresh session is the strongest reset. It has an empty history and no stale assumptions. Use it when a subtask is complete, when the agent has gone down a wrong path, or after repeated compactions.
A clean handoff has three parts:
- Update
PROGRESS.mdso it reflects the current state: move finished items to Done, rewrite Next, and record new decisions and open questions. - Commit the working changes, or at least check that
git statusandgit diff --statdescribe the state accurately. The new session can then read the repository as the source of truth for code. - Start the new session with a short instruction such as "Read PROGRESS.md and continue with the first item under Next," rather than pasting the old conversation.
The new session starts with a small, high-quality context: your instructions, one notes file, and whatever it reads for the next step.
A worked example
Suppose you are doing the INI-to-TOML migration over three hours.
- You write
PROGRESS.mdwith the goal and the two decisions, and you split the work into three subtasks: parser, tests, docs. - During the parser subtask, the agent finds the loader with
grep -rnand reads about 60 lines. A test run usespytest -x -q 2>&1 | tail -n 30. - When the parser works, usage is moderate. You tick the item in
PROGRESS.mdand continue to the tests subtask in the same session. - Midway through the tests, the agent asks again whether to keep the
load_settings()signature. That is a degradation symptom. You check usage, see it is high, and compact with the instruction block above. - You compare the summary with the notes file. It dropped the reason for using
tomllib. You add the reason back from the notes. - The tests pass. You commit, update
PROGRESS.md, and start a fresh session for the docs subtask, which needs none of the earlier history.
Common errors
- Writing notes only at the end. If the session crashes or degrades before you write them, the plan is lost. Update the file after each subtask.
- Letting the notes file grow. A notes file that holds a full log becomes a context cost itself. Keep it to the goal, decisions, status, and next steps.
- Compacting without checking. An unverified summary can silently remove a decision.
- Compacting forever. Repeated summaries drift. Switch to a fresh session.
- Starting a fresh session without committing or recording state. The new session cannot tell which changes are intentional.
- Putting temporary instructions in the persistent file. They load into every session and waste space. Put task-specific details in the notes file.
Exercise
Partway through a task, the agent asks you again which parsing library to use, a question you answered an hour ago. Usage is high and you have already compacted once. What should you do, and what should you do first?
Show answer
First update the notes file so it records the decision (the library and the reason), the files changed, and the next steps, and check that the code state matches git. Then start a fresh session that reads the notes file. The repeated question is a degradation symptom, and you have already compacted once, so a second compaction would compound the loss.
Exercise
You compacted a session and want to confirm the summary is safe to continue from. Name three checks.
Show answer
Check that every decision in the notes file appears in the summary along with its reason. Check that the list of changed files matches the output of git status. Check that the next steps match what you planned. If anything is missing, restate it to the agent or point it at the notes file.