Give your coding agent a state machine

By

Tagged: AI

Build a small JavaScript state machine for a coding agent, with explicit transitions, a retry limit, a useful event log, and tests.

A coding agent can easily get stuck fixing its own fixes. It edits a file, runs the tests, hits a failure, and tries another patch. Come back an hour later and it’s still going in circles.

You can ask the model in your prompt to stop after two tries, or you can enforce that cap in the code that drives it. Let’s build the second version in JavaScript.

We’ll map out the stages of a small coding task, lock down which events are allowed to move it forward, and halt the loop once it runs out of retries. To keep things focused, we’ll simulate the events instead of calling a model or modifying files on disk. What we’re writing here is the controller you’d wrap around those calls.

Give each stage a name

A state machine keeps track of where a process is right now and which events are allowed to move it somewhere else. If you want a refresher on the basics, I covered them in Finite State Machines.

For our coding loop, we’ll use six states: planning, editing, testing, recovery, done, and stopped.

In planning, you pin down a bounded task and the check that proves it before any code gets touched (that approach is spec-driven development). From there, editing creates a patch, testing runs the checks to get an observed result, and recovery decides whether the agent has another try left.

Fig 1 · 1/7A coding loop with two attempts
Plan the bounded task

The model can suggest a patch, while your own code runs the test command and reports whether it passed or failed. Even when an agent only touches local files, a convincing explanation of why a fix works shouldn’t be able to move the run into done.

Here’s how those states and events connect:

Which event can finish the runA patch moves to testing; only a pass from the test runner moves the run to done, while failures go through bounded recovery.PATCH_READYPASS from test runnerFAIL or ERRORRETRY with attempt leftSTOP or no attempt lefteditingtestingdonerecoverystopped

Write the transition function

Create a folder named agent-loop and save this file as machine.mjs:

export function transition(run, event) {
  const next = {
    planning: { PLAN_READY: 'editing', ERROR: 'stopped' },
    editing: { PATCH_READY: 'testing', ERROR: 'recovery' },
    testing: { PASS: 'done', FAIL: 'recovery', ERROR: 'recovery' },
    recovery: { RETRY: 'editing', STOP: 'stopped' },
    done: {},
    stopped: {}
  }[run.state]?.[event]

  if (!next) {
    throw new Error(`Cannot handle ${event} in ${run.state}`)
  }

  const state = next === 'editing' && run.attempts >= 2
    ? 'stopped'
    : next

  return {
    state,
    attempts: run.attempts + Number(state === 'editing')
  }
}

export function createRun() {
  let current = { state: 'planning', attempts: 0 }
  const events = []

  return {
    send(event) {
      const next = transition(current, event)
      events.push({ event, from: current.state, ...next })
      current = next
      return { ...current }
    },
    get log() {
      return structuredClone(events)
    }
  }
}

The transition table defines every valid move. If anything sends PASS while the machine is still in editing, it throws an error right away because editing has no PASS entry.

We only bump the attempt count when entering editing. Planning doesn’t use up a try, and once the second editing pass is done, asking for a retry sends the machine to stopped instead.

The ERROR event handles broken operations, like a model endpoint that isn’t responding or a test command that couldn’t launch. In this small example, a planning error stops the run immediately while editing and testing errors go through recovery. In a larger app, you’d likely split those failures up when they need different handling.

Follow one failed attempt

Next, create run.mjs right beside machine.mjs to simulate a run where the first test fails and the second patch fixes it:

import { createRun } from './machine.mjs'

const run = createRun()

for (const event of [
  'PLAN_READY',
  'PATCH_READY',
  'FAIL',
  'RETRY',
  'PATCH_READY',
  'PASS'
]) {
  console.log(event, run.send(event))
}

console.log(JSON.stringify(run.log, null, 2))

Run it using a recent version of Node.js:

node run.mjs

You’ll end up in done after two attempts, with a log tracing every step along the way, including the failed test and the retry. If an invalid event slips in, both the current state and the log stay untouched, so the caller can report the problem without corrupting the run.

When you wire this into a real runner, entering editing triggers your patch step, and entering testing runs a fixed test command, captures its output, and sends back PASS, FAIL, or ERROR. Keep those side effects outside transition() so you can test your state rules locally without paying for model calls.

Check the paths that should stop

A happy-path run won’t tell you if the limits hold up when things go sideways. Save these tests as machine.test.mjs to check the failure paths too:

import test from 'node:test'
import assert from 'node:assert/strict'
import { createRun } from './machine.mjs'

test('rejects success before testing', () => {
  const run = createRun()
  run.send('PLAN_READY')
  assert.throws(() => run.send('PASS'), /Cannot handle/)
  assert.equal(run.log.length, 1)
})

test('stops after two failed attempts', () => {
  const run = createRun()
  for (const event of [
    'PLAN_READY', 'PATCH_READY', 'FAIL', 'RETRY',
    'PATCH_READY', 'FAIL', 'RETRY'
  ]) run.send(event)

  assert.equal(run.log.at(-1).state, 'stopped')
  assert.equal(run.log.at(-1).attempts, 2)
  assert.throws(() => run.send('RETRY'), /Cannot handle/)
})

Run them with node --test to make sure a run can’t skip testing or keep retrying forever.

Recovering after an interruption

Right now, the event log only lives in memory and vanishes as soon as the process exits.

For durable runs, save each event with a run ID alongside the patch, test output, and repository revision it points to. When a crashed process restarts, inspect the working directory before resuming so you catch any half-written files or changes that no longer match the last recorded test run.

Pay extra attention if the process dies during testing. Record that the check was interrupted, rerun the tests against whatever is currently on disk, and pick the next event from that fresh result. Timeouts work the same way: your runner has to enforce the deadline and report the timeout back to the machine, since the state machine itself can’t kill a hanging command.

Here we’re only capping editing attempts. If you also want to limit how long a run can take or how much you spend on model calls, put a separate wall-clock or cost budget around them.

Once an agent can publish changes, delete data, or spend money, you need another layer of protection, which I covered in handling irreversible agent actions. This loop solves the smaller everyday problem first: when a coding task fails its tests twice, stop and hand the remaining work back to you.

Want me to talk about your product? You can sponsor this site.

Related posts about ai: