A coding agent working on a long task will happily read a 3,500-line controller file to check one method signature. Then it pastes in the full build log. By step twelve the context window holds more noise than instructions. API bills climb. Each response takes longer.

Worse still, unconstrained agents frequently produce what engineers call false greens. The agent reports that all acceptance criteria are met and tests pass, yet a quick check reveals that a runtime edge case was quietly skipped or an interface invariant was stubbed out.

Reading agent transcripts by hand after a long run eats an evening. Sitting at the keyboard babysitting prompt after prompt defeats the purpose of automation, triggering the exact team fatigue I explored in The Psychology of Automation Friction. Ideally, we want to set our agents to work in the morning, spend time in the garden or go for a chill run and a walk in the park, then come back to review verified output.

Getting to that calm autonomy requires a working feedback loop. Prompting an agent to reflect on its own execution trace costs next to nothing, just a few hundred tokens. That short check powers the entire mechanism.

The agent writes a short retrospective when each task ends. Now and then it reviews a batch of them to find repeated waste. In my workflow, pairing per-task notes with periodic reviews cut prompt context overhead by roughly 65% while keeping runs fast. I like the retro part. It turns one-off debugging sessions into lasting guardrails.


The Anatomy of Context Window Bloat

Context growth in autonomous coding workflows usually comes from a few repeated tool habits. With no constraints, agents default to collecting as much data as possible:

Typical Context Window Accumulation

Unconstrained Agent
Init
System prompt and initial user request ~8,000 tokens
Step 1
Read full 3,500-line controller file ~22,000 tokens
Step 2
Execute full build and ingest compiler log ~35,000 tokens
Step 3
Read full 2,100-line utility module ~44,000 tokens
Step 4
Re-run full test suite after single edit ~58,000 tokens
Steps 5 to 11: Unpruned tool outputs stack
Step 12
Context saturation degrades recall and attention > 120,000 tokens

Pulling a whole file into context for a three-line method signature costs thousands of tokens that stay in the transcript until the task ends. Running the full test suite after a one-line edit adds thousands more. Over a dozen steps, the payloads stack up and dilute the agent’s attention.


Stage 1: The Per-Task Self-Retrospective

The first piece is an automated end-of-task summary. When a task finishes, the agent appends a short record to a persistent log file such as retrospectives/YYYY-MM-DD-task-log.md.

The prompt asks for numbers. Free-form reflection tends to produce vague prose. The agent reports how many tool calls and round-trips the task needed, and which files it viewed in full versus as targeted line slices. It also notes whether false greens occurred during the run, along with the steps where input tokens spiked.

A typical retrospective entry takes the following markdown structure:

### Retrospective: 2026-09-28: Add Auth Middleware

- **Total Steps:** 14
- **Tool Invocations:** 22 (11 view_file, 5 run_command, 6 edit_file)
- **Token Spikes:** 
  - Step 3: `view_file` loaded `server/router.go` (4,200 lines) -> +16k tokens.
  - Step 8: `run_command` captured full `go test ./...` output -> +12k tokens.
- **Identified Inefficiency:** Full file view was unnecessary; only lines 120–165 were needed for middleware signature context.
- **Verification & Invariants:** Unit tests green, but initial run produced a false green on JWT expiration until an explicit boundary test was added in Step 10.

Writing this log costs few tokens at the end of a run, and the agent still has the whole trajectory in view while it writes.


Stage 2: Batch Synthesis and Rule Generation

A pile of retrospective logs only helps once something changes in the system because of them.

After 5 or 6 entries accumulate, the agent runs a batch review. It reads the recent entries, looks for habits that show up more than once, and proposes rule changes.

Closed-Loop Rule Synthesis Architecture

Self-Retrospective Loop
Task Run 1 Log

Token spikes and file view counts

Task Run 2 Log

Test runs and repeated commands

Task Run 3 Log

Compiler output and large payloads

↓
Cadence: 5 to 6 Task Runs

Agent Batch Synthesis

Scans accumulated retrospective logs to isolate recurring token waste patterns.

↓
Derived Operating Rules
✓
Grep & Targeted Line Slicing
Open exact line ranges instead of loading full multi-thousand-line files.
✓
Deferred Compilation & Testing
Batch multi-file edits before executing full builds or test suites.
✓
Explicit Invariant Tests
Catch false greens and verify boundary conditions before completing tasks.
↓
Configuration Persistence
Update AGENTS.md / System Instructions

New constraints immediately guide tool usage in subsequent runs without manual oversight.

The review inspects the trace through a few questions. Which tool calls added the largest token increments? Did a vague initial lookup force a second file read before the multi-file edit was finished? Where did the agent misread an interface contract?

The agent turns its findings into instructions and writes them to its operating configuration, usually an AGENTS.md file.


Practical Constraints Derived from Log Analysis

In my workflow, three main patterns emerged from the retrospective traces. Fixing them paid off quickly.

1. Targeted Code Inspection Over Full-File Reads

The logs showed multi-thousand-line files read in full to inspect a single helper function.

The resulting rule: search with grep or symbol lookup first, then open only the needed line range with StartLine and EndLine. Read a whole file only when actively restructuring it.

2. Deferred Compilation and Verification

In multi-file refactors, the agent ran a full test suite after each single edit, and each run appended pages of stdout and stderr to the context.

The resulting rule: finish the related edits across the sub-system first, then compile and test once.

3. Autonomy via Guardrails and Catching False Greens

When an agent says something works and it does not, you run a postmortem on the trace. Find why it thought it was green. Then update the tool configuration or add a targeted CI test case so that failure cannot repeat.

Strong static analysis and CI pipelines are increasingly important. With solid guardrails in place, agents run autonomously, separating operational traces from core domain logic just like CQRS for LLM Agents. Finding that boundary is an ongoing balance that you define while building a product.


Operational Results

With the new rules in place, average prompt context size across multi-step tasks dropped by about 65%. Per-step latency fell as the payloads shrank.

API spending also settled. Complex features no longer produced the occasional cost spike from a runaway context loop. Smaller context windows left the core instructions easier for the model to follow during long sessions.


Implementing Self-Retrospectives in Your Workflow

To deploy this mechanism in your own setup, add the following prompt snippet to your agent’s post-task completion routine:

Upon completing the requested task, append a brief entry to `retrospectives/log.md`:
1. Record total steps, tool call counts, and notable token spikes.
2. Note any tool usage that introduced redundant context into the window.
3. Check for false greens: did any test report success while missing a critical edge case?
4. If `retrospectives/log.md` contains 5 or more entries, inspect the batch, extract common inefficiencies, and recommend updates to `AGENTS.md`.

Once the agent reads its own metrics, the refinement loop runs on its own at very low token cost. Tracking context size and runtime invariants like any other engineering metric lets the agent keep working autonomously without constant babysitting.