Picture a request that sounds small: "Upgrade the HTTP client library in this service and fix whatever breaks." An agent picks it up, edits the manifest, runs the tests, sees forty failures, and starts patching. By step twelve it has changed an unrelated retry helper because a stack trace mentioned it. By step twenty it has forgotten that it already tried pinning the old version. By step thirty-five it is rewriting the same import for the third time, the context window is full of stale test output, and the final message says "all tests pass" even though it only ran the subset that passed.
Nothing in that story is a model-quality problem in the narrow sense. Every step was locally plausible. What failed is the structure around the model: what it was shown, how its intentions were recorded, what it was allowed to remember, and who checked the result. This article takes an agent apart into four organs (perception, planning, memory, execution), explains what each one has to guarantee, and shows how they fail when one is missing.
1. What "Autonomous" Requires: A Loop, Four Organs, and a Budget
Strip away the marketing and an agent is a loop. Observe the world, decide the next action, act, observe the result, repeat until a stop condition fires. A single model call is not an agent, and neither is a fixed pipeline of prompts where a human wrote the order of steps. The word "autonomous" only earns its place when the system chooses its own next step based on what it observed.
That loop needs four capabilities, and it helps to treat them as separate components with separate contracts instead of one big prompt:
- Perception turns raw state (files, command output, web pages, tickets) into a bounded, relevant view the model can reason over.
- Planning turns a goal into an explicit, inspectable sequence of intended steps and decides when to revise it.
- Memory decides what survives between steps, between sessions, and between tasks, and in what form.
- Execution performs actions through tools, inside limits, with results that can be verified and, where possible, undone.
The fifth thing, often forgotten, is a budget: a cap on steps, wall-clock time, tokens and spend, enforced outside the model. A loop without a budget is a while-true with a credit card attached. The budget is also what converts "the agent got confused" from an open-ended incident into a bounded one.
2. Perception: Deciding What the Model Gets to See
Perception is the most underrated organ because it looks like plumbing. The model never sees "the repository" or "the web page." It sees whatever text you serialize into the prompt. Every decision about that serialization is a decision about what the agent can possibly know.
Selection beats volume
The instinct is to give the model more: the whole file, the whole log, the whole page. Long contexts do work, but relevance degrades as the window fills with material that does not bear on the next decision, and every extra token is paid for on every subsequent step of the loop, because the history is re-sent each turn. A useful perception layer is closer to a search engine than to a file reader. It answers "what is the smallest slice of state that lets the model choose the next action well?"
Concretely, that means summarizing test output to the failing test names and first assertion messages instead of pasting two thousand lines; reading a function by symbol instead of reading the file; returning directory listings with sizes and modification times and letting the model ask for contents; and truncating with an explicit marker ("output truncated, 1,840 more lines, use the filter argument") so the model knows information is missing instead of assuming it saw everything.
Structure the observation
Observations that carry structure (exit code, duration, stdout tail, stderr tail, files changed) are easier to reason over and easier to verify than free text. They also make it possible for deterministic code, not the model, to decide things like "the command failed, so do not proceed." Treat the observation format as an API between the world and the model, and version it.
Perception is also the trust boundary
Anything the agent reads can contain instructions: a web page, an issue comment, a README, a log line. The model cannot reliably distinguish "data I was asked to analyze" from "instructions addressed to me." The perception layer is where you label untrusted content, strip what you can, and make sure that content never gains the authority of the system prompt. Privileged actions should never be triggered solely because untrusted text asked for them. We return to this in the execution section, because the real defense is limiting what actions are possible, not hoping the model resists.
3. Planning: Plans as Data, Not as Prose
There are two broad planning styles, and most production agents mix them.
- Interleaved (often called ReAct-style): at each step the model reasons briefly, picks one action, sees the result, and continues. It adapts quickly to surprises and needs no upfront structure, but it has no global view, so it drifts and repeats itself on long tasks.
- Plan then execute: the model first writes a list of steps with expected outcomes, then executes them, revising when reality disagrees. It gives you something to review, to checkpoint and to resume from, at the cost of an upfront step that can be wrong in ways nobody notices until step seven.
The practical compromise is a short explicit plan that is stored as structured data (a list of steps, each with a goal, a success check and a status), executed in an interleaved fashion, and revised on defined triggers. The key is that the plan is an object the surrounding code can read, not a paragraph in the transcript.
Why a plan must be data
When the plan is data, the harness can do things the model cannot do reliably for itself: count steps, detect that step four has been "in progress" for twenty turns, refuse to mark a step done without its success check passing, show the plan to a human for approval before anything irreversible, and resume after a crash by reloading the plan instead of reconstructing it from chat history.
Revision triggers
Replanning on every observation makes the agent thrash; never replanning makes it walk off a cliff. Good triggers are specific: a step's success check failed twice, a tool returned an error class the plan did not anticipate, a precondition the plan assumed turned out false, or the budget crossed a threshold. Everything else continues the current plan.
4. Memory: Working Context, Episodic Records, and Durable Facts
"Memory" covers at least three different things with different lifetimes, and conflating them is the root of many agent bugs.
Working memory
This is the prompt: the current goal, the plan, the most recent observations. It is small, expensive, and rebuilt every turn. The main engineering task is compaction. When history grows, you replace old turns with a summary that preserves decisions, open questions and facts discovered, while dropping raw output. Compaction is lossy by design, so decide in advance what must survive it: the goal, the plan state, constraints the user stated, and anything the agent has already tried and ruled out. The "tried and ruled out" list is what prevents the step-thirty-five loop from the opening scenario.
Episodic memory
This is the record of what happened in this task or past tasks: actions taken, results, decisions and why. It lives outside the prompt, in a log or database, and is queried when needed. Its value is auditability and recovery (what did the agent do before it crashed?) and, secondarily, learning from similar past tasks. Because it is append-only, it is also the thing you read during incident review.
Durable facts
These are stable truths about the user, the team or the system: preferences, conventions, decisions already made. They outlive tasks. They are also the riskiest memory, because a wrong or outdated fact is silently applied forever. Store durable facts sparingly, store them with a source and a date, let them be corrected or deleted, and never store one-off context ("the build is red today") as if it were permanent.
| Memory type | Lifetime | Where it lives | Main risk | Main control |
|---|---|---|---|---|
| Working context | One step to one task | The prompt | Overflow, distraction, lost constraints | Compaction that pins goal, plan and ruled-out attempts |
| Episodic record | One task to months | Append-only log or database | Unbounded growth, noisy retrieval | Structured entries, retention policy, targeted queries |
| Durable facts | Indefinite | Small curated store | Stale or wrong facts applied silently | Source and date on every entry, easy correction, strict write criteria |
5. Execution: Tools, Sandboxes, and Reversibility
Execution is where the agent touches the world, so it is where mistakes cost something. Four properties matter.
Typed, narrow tools
A tool that takes a validated schema ("read file at path," "run test with this filter") is safer and easier for the model to use than a general shell. A general shell is sometimes necessary, but it should be the exception, wrapped in an allow-list or a sandbox. Validate arguments before running, return structured errors the model can act on, and keep each tool's description short and unambiguous, because the description is the model's only documentation.
Isolation
Run the agent's work in a place where a mistake is contained: a separate working copy or branch, a container, a scratch directory, a database with no production credentials. The cheapest high-value version is a dedicated, disposable workspace per task, so two concurrent tasks never share a dirty working tree and a bad run can be thrown away without cleanup. Give the agent the narrowest credentials that let it finish, and treat anything outside its workspace as read-only unless a step explicitly requires otherwise.
Reversibility and approval
Classify actions by whether they can be undone. Reading and editing files in a scratch branch is reversible. Sending a message, deleting data, pushing to a shared branch, spending money and calling external APIs with side effects are not. Reversible actions can run unattended. Irreversible ones should require a gate: a human approval, or at minimum a dry-run step whose output is checked against the plan.
Verification outside the model
The agent saying "done" is a claim, not evidence. The harness should run the test suite, check the exit code, inspect the diff against the plan, and only then mark the step complete. This is the single highest-leverage habit in agent design: the component that does the work must not be the only component that judges it.
6. A Worked Example: The Dependency Upgrade, Step by Step
Return to the opening task and see how the four organs change the outcome. The harness below is intentionally small. It shows the shape, not a framework.
from dataclasses import dataclass, field
import subprocess, time
@dataclass
class Step:
goal: str
check: str # shell command that must exit 0 for the step to count as done
status: str = "todo" # todo | doing | done | failed
attempts: int = 0
@dataclass
class State:
goal: str
plan: list[Step]
ruled_out: list[str] = field(default_factory=list) # survives compaction
steps_used: int = 0
MAX_STEPS, MAX_SECONDS, MAX_ATTEMPTS = 40, 900, 2
def run(cmd: str) -> dict:
p = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=300)
return {"exit": p.returncode, "out": p.stdout[-2000:], "err": p.stderr[-2000:]}
def observe(state: State, last: dict | None) -> str:
done = [s.goal for s in state.plan if s.status == "done"]
todo = [s.goal for s in state.plan if s.status != "done"]
return (f"GOAL: {state.goal}\nDONE: {done}\nREMAINING: {todo}\n"
f"RULED OUT: {state.ruled_out}\nLAST: {last}")
def agent_loop(state: State, propose_action):
start = time.monotonic()
last = None
for step in state.plan:
step.status = "doing"
while step.status == "doing":
if state.steps_used >= MAX_STEPS or time.monotonic() - start > MAX_SECONDS:
return "budget_exhausted"
state.steps_used += 1
action = propose_action(observe(state, last)) # model call: returns a validated tool request
last = run(action["command"]) # execution inside the sandboxed workspace
verdict = run(step.check) # verification is NOT the model's opinion
if verdict["exit"] == 0:
step.status = "done"
else:
step.attempts += 1
state.ruled_out.append(f"{step.goal}: {action['command']} -> failed check")
if step.attempts >= MAX_ATTEMPTS:
step.status = "failed"
return "needs_replan"
return "complete"
Now walk the scenario. The plan, written once and stored, has four steps: bump the version in the manifest (check: the lockfile resolves), update call sites for the renamed API (check: the type checker exits 0), run the unit tests (check: exit 0), and run the integration subset that touches HTTP (check: exit 0). The agent works in a throwaway branch in its own workspace.
When the type checker complains about the unrelated retry helper, the observation shows it as a structured failure tied to step two. The model tries a fix, the check fails again, and the attempt is recorded in the ruled-out list. After the second failed attempt the loop returns needs_replan instead of continuing, which hands control to a planner call (or a human) with the full list of what was tried. The "pin the old version" idea is not retried at step thirty-five, because it is sitting in the ruled-out list that compaction was told to keep.
The final message is not the model's summary. It is assembled from the plan state: which steps passed their checks, which did not, the diff, and the budget used. If the integration subset was never run, the report says so.
7. Failure Modes and When Not to Build an Agent
These are the failures that recur across agent systems, mapped to the organ that should have prevented them.
- Looping on a failing action (planning and memory): no ruled-out list, no attempt cap. Fix with per-step attempt limits and a record of failures that survives compaction.
- Confidently wrong summaries (execution): the model's claim of success is accepted. Fix with independent verification.
- Context rot (perception and memory): raw tool output piles up until the goal is buried. Fix with selective observation and compaction that pins the goal.
- Prompt injection through data (perception and execution): untrusted text redirects the agent. Fix by labeling untrusted content and removing the ability to take privileged actions without a gate.
- Scope creep (planning): the agent fixes things nobody asked about. Fix by diffing the result against the plan and flagging unplanned changes.
- Runaway cost (execution): no budget. Fix with hard caps enforced outside the model.
When not to use an agent
If you can write the steps down in advance and they rarely change, use a workflow: deterministic code with model calls at specific points. It is cheaper, faster and far easier to test. If the cost of one wrong action is high and nobody can review it, an agent is the wrong tool until you have a gate that makes the action reversible. If a single well-formed model call with the right context answers the question, do not add a loop. Autonomy is a cost you pay for open-ended tasks, and it should be justified by openness.
| Approach | Who chooses the next step | Predictability | Handles open-ended tasks | Typical use |
|---|---|---|---|---|
| Single model call | Caller | High | No | Classification, extraction, rewriting |
| Fixed workflow with model steps | Developer, in code | High | Limited | Known pipelines, report generation |
| Interleaved loop | Model, each step | Low to medium | Yes, short tasks | Exploration, debugging |
| Plan, execute, verify | Model, within a stored plan and budget | Medium | Yes, longer tasks | Multi-file changes, research with deliverables |
8. Common Mistakes and a Decision Checklist
Teams tend to repeat the same handful of mistakes when they first build an agent.
- Giving the agent a general shell and a broad credential on day one, then trying to add safety later.
- Storing the plan only inside the conversation, so nothing outside the model can read or enforce it.
- Letting the model decide when it is finished.
- Saving every observation as long-term memory, which turns retrieval into noise.
- Testing only the happy path. Replay recorded failures (a flaky test, a permission error, a malformed tool result) against the planner and executor.
- Measuring only success rate. Track steps per task, cost per task, and the share of runs that ended by hitting a budget, because a rising budget-exhaustion rate is an early warning.
Before shipping an agent into a real workflow, answer these questions:
- Is the task genuinely open-ended, or can it be a workflow?
- Is there a hard cap on steps, time, tokens and spend, enforced outside the model?
- Is the plan stored as data with a success check per step?
- Does compaction pin the goal, the constraints and the ruled-out attempts?
- Does the agent work in an isolated, disposable workspace with the narrowest credentials that suffice?
- Are irreversible actions gated by approval or a verified dry run?
- Does something other than the model verify completion?
- Can you replay a failed run from its log and see why it made each choice?
9. What to Do Monday: Short FAQ
We already have an agent that mostly works. Where do we start? Add a step and time budget with a clean failure exit, then add an independent completion check. Those two changes remove the most expensive failure classes before you touch anything else.
Should we use multiple agents? Only when a single loop's context genuinely cannot hold the work, or when roles need different permissions. Splitting adds coordination cost and new failure modes (lost handoffs, conflicting edits). Start with one loop and one workspace per task.
How much memory should it have? Less than you think. Pin the goal, the plan state and what was ruled out. Add durable facts only when the same correction has been given more than once, and record where each came from.
How do we know it improved? Keep a small set of realistic tasks with known-good outcomes and rerun them after every change to prompts, tools or models. Compare pass rate, steps and cost. Prompt tweaks that feel better in a demo often do not survive that comparison.
Can it ever run fully unattended? Yes, for reversible work inside an isolated workspace with a verifier. For anything else, the honest design is autonomy up to a gate, then a person decides.