Agent orchestration

AI Agent State Machines: Working, Waiting, Failed, and Done

An agent can finish a turn while the task is still wrong. A state machine becomes useful when its transitions describe evidence and ownership, so working, waiting, failed, and done lead to different, reliable actions.

AI-assisted technical guide with linked primary sources. Examples are illustrative unless stated otherwise. How these guides are made.

Give every status an operational meaning

A useful state tells someone what can happen next. In a proposed coding-task model, working means the current attempt can make progress without a new human decision; waiting means it needs a specified external event; ready_for_review means an artifact is available but acceptance is unresolved. Reserve done for accepted work under your task contract.

This vocabulary is a design recommendation, not a universal provider protocol. A coding tool’s completed turn may correspond to your review state rather than your done state. Write the mapping explicitly instead of copying labels between systems. The W3C SCXML specification provides a formal vocabulary for event-driven transitions, hierarchical states, and final states; your application still defines what those states mean.

Keep cancellation separate from failure. An operator can cancel correct work because priorities changed. Likewise, keep waiting for approval separate from waiting for a slow external build, even if the interface initially groups both under waiting.

Store evidence alongside the label

Do not represent an attempt as a bare string. A practical record includes task ID, attempt ID, state version, current state, reason, owner, last observed event, observation time, and relevant artifact references. Waiting additionally needs a blocker and an expected response; review needs an immutable revision or artifact identifier.

Keep finite control states separate from growing task data. Stately’s state documentation distinguishes a state’s value from its context. Applied here, the branch name and approval question belong in context rather than creating new states such as waiting_for_invoice_branch_approval.

Persist a short explanation for every consequential transition. An operator should be able to answer “why is this waiting?” without reconstructing an entire conversation. Avoid placing private prompts or credentials in generic status records.

Define transitions before writing the dashboard

The following is an illustrative transition contract for a task runner. It deliberately treats a proposed result and an accepted result as different events.

Suggested task-attempt transition rules
Current stateEvent and conditionNext state
queuedWorker claims the current leaseworking
workingAgent supplies a concrete unresolved questionwaiting
waitingMatching response arrives for this question and versionworking
workingResult references a reviewable revision and check evidenceready_for_review
ready_for_reviewReviewer accepts the referenced revisiondone
ready_for_reviewReviewer requests a scoped changeworking
working or waitingAttempt cannot continue and records the reasonfailed
Any active stateCancellation is requestedcanceling
cancelingOwned work has stopped or been reconciledcanceled

Do not jump directly to canceled when a stop request is sent. A tool may still be applying a change. The acknowledgment and reconciliation determine when the interface can safely describe the attempt as stopped.

Guard events against stale or incompatible state

A delayed approval must not resume an unrelated question. Require the response to match task ID, attempt ID, question ID, and expected state version. Reject or quarantine an event that belongs to an older attempt. Record duplicate event IDs so redelivery does not repeat a transition or side effect.

Stately’s guard documentation describes conditions that enable a transition, and recommends pure, synchronous guards. Keep your acceptance predicate similarly straightforward: compare identifiers and already-established evidence. Run expensive verification separately, then deliver its result as an event carrying the revision it checked.

# Illustrative transition predicate, not a framework API
accept_response = (
    state == "waiting"
    and event.attempt_id == record.attempt_id
    and event.question_id == record.question_id
    and event.expected_version == record.version
)

In a shared store, apply the version check and state update atomically. Checking a version in memory and writing later still leaves room for two workers to accept conflicting events.

Separate process liveness from task progress

A live process does not establish useful progress, and a silent process does not establish failure. A worker can be alive while waiting for input, retrying a bad tool request, or executing a long test. Treat process health, semantic task state, and observation freshness as separate dimensions.

For a local monitor, show a last-observed timestamp and an unavailable or stale condition when evidence disappears. Do not transform missing telemetry into done. For a task runner, use explicit leases and deadlines to decide who may recover abandoned work; a heartbeat timeout should first trigger reconciliation rather than an automatic duplicate write.

Tracing helps explain where execution time went. OpenTelemetry’s trace concepts describe spans, events, and span status. A successful tool span is evidence about that operation, not proof that an entire coding task satisfied its acceptance criteria. Preserve that boundary when deriving dashboard state.

Walk through a real-shaped coding task

Consider an illustrative task: add CSV export while preserving tenant authorization. Attempt A starts working against revision R1. It asks whether archived invoices belong in the export and moves to waiting with question Q1. The human answers Q1 against the recorded state version, so A resumes.

The agent produces revision R2 with serializer checks, then enters ready_for_review. The reviewer finds that the endpoint does not exercise the intended authorization path. The task returns to working with that finding; the earlier turn completion remains in history but no longer describes the current task state.

Attempt A then crashes. Reconciliation inspects the worktree and preserves R2 rather than discarding it. Attempt B receives a checkpoint and a new attempt ID. A delayed completion message from A is retained for diagnosis but cannot mark B done. B produces R3, the relevant checks cover R3, and a reviewer accepts R3. Only then does this contract enter done.

The example demonstrates why task identity, execution identity, and artifact identity all matter. One green indicator cannot carry those distinctions safely.

Test the events that break optimistic designs

Start with event-sequence tests rather than screenshots. Send the same approval twice; deliver completion before a late working update; restart after persisting a result but before acknowledging its event; cancel while a tool is in flight. Check that stale events cannot reverse an accepted outcome or authorize a new attempt.

Define terminal-state behavior deliberately. A final state should not silently reopen because an old worker emits progress. If an accepted task needs more work, create a new task or an explicitly modeled reopen operation with fresh ownership. Record failed attempts without erasing the task’s recoverable artifacts.

State machines clarify control flow but do not make remote effects transactional. If cancellation races with an external write, inspect the external result and record whether compensation is needed. “Canceled” must not imply that every previous effect was undone.

Apply the model when watching local agents

You can use the same distinctions without building a runner. Maintain working, needs-a-decision, and review queues, and check actual output before promoting work to accepted. Purrvio’s Mac preview helps keep supported local coding sessions visible, with the richest session support for Claude Code and Codex.

Purrvio reads supported local session records and processes without installing agent hooks. It provides visibility and supported terminal navigation; it does not enforce this proposed state machine, verify acceptance criteria, or recover a distributed queue. Navigation supports Ghostty and Terminal.app; direct replies require Ghostty and Automation permission.

If attention across local sessions is your bottleneck, try the free Mac preview. It supports macOS 13+ on Apple silicon and Intel. The locally signed preview is not Apple-notarized; read the installation notes before launching it.

Review the state contract with this checklist

  • Define the next permitted action and required evidence for each state.
  • Separate waiting reasons, review readiness, acceptance, cancellation, and failure.
  • Carry task, attempt, event, and artifact identifiers across transitions.
  • Version state updates and reject stale responses atomically.
  • Display observation freshness without pretending missing data is success.
  • Test duplicates, reordered messages, crashes, and cancellation races.
  • Require acceptance evidence to reference the exact revision under review.

Begin with the smallest vocabulary that supports these decisions. Add hierarchy when it removes ambiguity; avoid multiplying labels that never change an operator’s next action.

Frequently asked questions

Is an agent process exiting successfully enough to mark a task done?

No. A successful exit describes process termination. Task acceptance should reference the intended artifact, required checks, and the acceptance decision for that revision.

Should missing status updates automatically mean failed?

Treat missing updates as stale or unavailable evidence first. A task runner can then reconcile leases and external effects before deciding whether an attempt failed and whether retrying is safe.

Can Purrvio enforce a custom agent state machine?

Purrvio provides visibility into supported local coding sessions and navigation to supported terminals. Custom orchestration transitions, task ownership, and completion verification remain responsibilities of your workflow or runner.

Sources and further reading

Primary references checked for this guide on 10 November 2026. Documentation can change; confirm version-specific behavior before using commands in a production workflow.

  1. W3C SCXML Recommendation

    Formal reference for event-driven transitions, hierarchical state configurations, and final-state semantics.

  2. Stately: State

    Distinguishes finite state values, context data, and state snapshots; used as a modeling reference rather than a version-specific API tutorial.

  3. Stately: Guards

    Explains guarded transitions and pure synchronous predicates, supporting the proposed event-validation boundary.

  4. OpenTelemetry: Traces

    Defines spans, events, and span status; informs the distinction between operation evidence and task acceptance.

Download Purrvio.

Free Mac preview. No account or API keys.

This locally signed preview isn’t Apple-notarized. macOS may block the first launch.

Download free preview ↗

3.2 MB ZIP · Apple silicon and Intel · macOS 13.0+

Read installation steps

One email before you go.

I’ll send a short setup note and reply if you hit a snag. No spam, unsubscribe anytime.