Sub topic 2
What state has to survive
A long-running task stops at some point, whether the context window fills, the process crashes, or a person ends the session. The next run can only continue if the right facts were saved outside the agent's memory. This chapter defines which facts those are, so later chapters can cover how to store them.
This chapter assumes you can read basic Python, know how an agent calls tools in a loop, and can read JSON and Markdown files. It also assumes you know that a process loses its memory when it exits.
State is what the next run needs
State is the set of facts a fresh run needs in order to continue correctly. It is not a log of everything that happened. A log records the past, and state answers the question "what must I know to act now?"
A useful test for any piece of information is to imagine the agent restarting with only the saved files. Ask whether it would make a wrong move without that fact. If it would, the fact is state. If the agent could cheaply and reliably work the fact out again, it is not state.
The categories of state
Most long-running tasks need the same few kinds of state. The table lists them with an example and the failure you get when one is missing.
| Category | Example | If it is lost |
|---|---|---|
| Goal and success criteria | "All pages under docs/ build without warnings" | The agent finishes something nearby, or never knows it is done |
| Inputs and parameters | Source path, date range, target environment | The agent guesses, and may run against the wrong target |
| Plan and step list | fetch, transform, validate, publish | Work is re-planned differently, and old progress no longer lines up |
| Completed steps | `["fetch", "transform"]` | Finished work is repeated |
| Side effects performed | "Uploaded 2023-01 to 2023-06" | Emails, uploads, or payments happen twice |
| Artifacts and their locations | `out/2023-01.csv` | Outputs are regenerated or not found |
| Decisions and reasons | "Keep old URLs; add redirects" | A settled question gets reopened, or reversed without notice |
| Open problems | "Gallery shortcode has no equivalent" | Known blockers are rediscovered slowly |
| Next action | "Convert shortcodes starting at setup.md" | The agent spends its first minutes working out where it was |
Two of these are easy to overlook: side effects and decisions.
Side effects
A side effect is any change outside the task's own files, such as a sent message, a database write, an uploaded file, or a deployment. Completed steps tell you which steps finished. They do not always tell you how far a half-finished step got. If a step uploads 50 files and crashes after 30, the step is not in the completed list, but 30 uploads already happened. Record side effects at the finest grain you can safely repeat or undo.
Decisions and reasons
A decision without a reason is fragile. If the file says only "use redirects," a later agent may see a cleaner option and switch, breaking the earlier work. If it says "use redirects because external sites link to the old URLs," the later agent can judge whether that reason still holds.
What does not need to survive
Saving everything is a failure mode of its own. It makes the state file long, slow to read, and full of stale detail. These items usually do not need to be saved:
- Raw tool output that can be fetched again, such as a directory listing.
- Intermediate reasoning that led to a decision. Keep the decision and its reason, not the whole chain.
- Values that are cheap to recompute and may have changed, such as the current time or the size of a growing file.
- Conversation phrasing, apologies, and acknowledgements.
A fact that can change while the task is stopped is a special case. For example, "the branch has 3 commits" may be wrong by the next run. Save it only as a claim to check, not as a truth. Chapter 9 covers checking saved state against reality. For now, label such facts clearly as observed at a point in time.
Machine state and human state
State serves two readers. A program reads it to decide what to skip, and a person (or another agent) reads it to understand the task. These readers want different formats.
- Machine state is structured and strict, such as JSON with fixed field names. It holds the completed list, counters, IDs, and file paths. Code can load it without interpretation.
- Human state is prose and checklists, such as Markdown. It holds the goal, the reasoning behind decisions, open questions, and the next action.
Keep both, and avoid duplicating the same fact in both places by hand, because copies drift apart. A good rule is that each fact has one home. Counters and lists of finished IDs live in the machine file. Reasons and plans live in the progress file.
A concrete state record
The following Python defines a small state record that covers the categories above. It can be saved as JSON and loaded back. The next chapters show how to write such a record safely, so here the focus is on its shape.
import json
from dataclasses import dataclass, field, asdict
@dataclass
class TaskState:
goal: str
inputs: dict
steps: list
completed: list = field(default_factory=list)
side_effects: list = field(default_factory=list)
artifacts: dict = field(default_factory=dict)
decisions: list = field(default_factory=list)
open_problems: list = field(default_factory=list)
def next_step(self):
for name in self.steps:
if name not in self.completed:
return name
return None
def decide(self, choice, reason):
self.decisions.append({"choice": choice, "reason": reason})
def to_json(self):
return json.dumps(asdict(self), indent=2)
@classmethod
def from_json(cls, text):
return cls(**json.loads(text))
state = TaskState(
goal="Export monthly payments for 2023",
inputs={"year": 2023, "target": "staging"},
steps=["export", "verify", "upload"],
)
state.completed.append("export")
state.artifacts["export"] = "out/2023-01.csv"
state.decide("export one file per month", "uploads fail above 50 MB")
restored = TaskState.from_json(state.to_json())
print(restored.next_step())
print(restored.decisions[0]["reason"])Running it prints verify and then uploads fail above 50 MB. The restored object knows what is left to do and why an earlier choice was made. It holds no scratch reasoning and no raw tool output.
Notice that next_step is derived from steps and completed. It is not stored as a separate field. Storing a derived value creates a second copy that can disagree with the first, so derive what you can. The progress file in the later chapter does store a "next action" in prose, because there it carries judgment that no formula can produce, such as "start at setup.md because the earlier files are done."
Choosing the grain of recorded facts
How finely you record state controls how much work you lose on a crash. Recording "export is done" after a 3-hour step means a crash at hour 2 loses 2 hours. Recording each month as it finishes loses at most one month. Finer records cost more writes and more state to keep consistent.
A practical rule is to record at the size of work you can afford to repeat. If repeating 10 minutes of work is acceptable, a record every 10 minutes is enough. The next chapter, on decomposition, shows how to cut a task so those boundaries fall in natural places.
Common errors
- Saving only the completed list. The agent knows what finished but not why choices were made, so it reopens decisions.
- Saving plans but not parameters. The step list is saved, but the date range and target are not. A restart then uses defaults, which may be wrong.
- Treating a half-done step as not started. The step is not in the completed list, so it reruns and repeats the side effects that already happened.
- Storing derived values. A saved "remaining count" disagrees with the real list after a manual edit.
- Saving secrets. Tokens and passwords do not belong in state files that may be shared or handed off. Save the name of the secret or where to get it, not its value.
- Saving unlabeled observations. A note that says "the queue is empty" reads as fact, but it was true only when written.
Exercise
An agent is moving 200 customer records to a new system. It processes them in order and has finished 120. It saved the list of completed steps, but the "move records" step is one step in that list and not yet marked complete. The process crashes. Name two pieces of state it should have saved so a restart does not duplicate work, and say what each prevents.
Show answer
First, a record of side effects at a finer grain, such as the IDs of the records already moved (or a count and the last moved ID). This prevents the restart from moving the first 120 records again and creating duplicates. Second, the inputs and parameters, such as the source, target system, and ordering rule. This prevents the restart from using different defaults, which would make the saved progress meaningless. The decision to process in order, with its reason, is also useful, since the last moved ID only makes sense if the order is fixed.
Exercise
A progress file contains the line "The build currently has 4 failing tests." Why is this risky as state, and how would you rewrite it?
Show answer
The count can change while the task is stopped, for example if someone fixes a test, so a later run may trust a wrong number. Rewrite it as a dated observation that must be checked, for example "At the end of session 2, 4 tests were failing (see test-report.txt). Re-run the tests before relying on this." Better still, save only the command to run and let the next run measure it.