Shawn MaybushENGINEERING WORKBENCH

State Machines vs. The Autonomous Loop Trap: Designing Deterministic Agent Lifecycles


In Part 1, we looked at why deterministic tool contracts and bounded file primitives beat begging an LLM with adjectives. In Part 2, we looked at how to keep the active context window small, cache-pinned, and stratified across turns.

Both of those solve single-turn precision and memory economics. Neither solves what happens when you hand an agent a multi-step goal and walk away.

For the past two years, the default recipe for agent autonomy has been the ReAct while loop: give a model a goal, put thought -> tool -> observation inside while (!done), and let it run until it declares victory or hits max_iterations.

In real engineering work, an open-ended autonomous loop is not a feature. It is an uninterruptible retry spiral with an API key attached.


1. The War Story: Debugging Colony From Inside the Box

Early in building Colony, I kept running into a frustrating failure mode whenever I talked to the agent about a bug in Colony itself.

Colony runs agents inside strict operating boundaries: an agent has tools for the workspace and containerized extensions, not access to the host daemon’s Go source code or the frontend application codebase. When a platform bug happened, the agent literally had no way to read the underlying source, diagnose the root cause, or patch it.

Yet when I described what broke, the agent didn’t stop and say, “That lives outside my boundary—I can’t see or fix it.”

Instead, its autonomous loop kicked into high gear. Driven by completion bias, it scoured everything it could reach: reading unrelated workspace files, inspecting logs, testing speculative workarounds, and spinning up background tasks to try to fix something it had zero visibility into. Worse, I had no clean way to pause the loop, tap the agent on the shoulder mid-flight, or tell it to stop chasing a ghost without nuking the entire session.

That experience forced a fundamental rethink of how Colony runs work across time:

An agent that does not know how to yield, ask, or stop is not autonomous. It is trapped in a loop you cannot steer.


2. Four Mechanical Failure Modes of Naive while (true) Loops

When you wire an agent runtime around an unbounded loop instead of a formal lifecycle, four failures show up immediately:

  1. Boundary Blindness & Completion Bias: Language models are optimized to resolve the prompt in front of them. When an agent hits a missing credential, an ambiguous requirement, or an inaccessible codebase, a naive loop treats that wall as a puzzle to brute-force rather than a boundary to report.
  2. Sunk-Cost Speculation: Once an agent spends ten turns digging down a wrong hypothesis, its working context is saturated with partial findings from that path. Instead of stepping back, it doubles down—making larger guesses to justify the turns already spent.
  3. The Wait-or-Kill Binary: A synchronous, opaque agent loop gives the human operator only two controls: wait helplessly while it burns tokens, or Ctrl+C the process and lose every intermediate step. There is no clean pause, clarify, or course-correct primitive.
  4. Failure Laundering: If a human-aborted run, a missing user decision, and a network crash all exit through the same generic "failed" handler, downstream orchestrators cannot tell whether to retry, escalate, or leave it alone.

The fix is not a cleverer system prompt telling the agent “be careful and don’t loop.” The fix is replacing the while (true) loop with an explicit task state machine.


3. Formal Task Lifecycles: Explicit States, Intentional Yields

In Colony, background work is modeled as a first-class Task record—not a hidden thread running an opaque loop. Every task moves through a strict seven-state vocabulary enforced at the tool boundary (update_task rejects any status outside this set):

                       ┌───────────────────────────┐
                       │          PENDING          │
                       │    (Queued for pickup)    │
                       └─────────────┬─────────────┘
                                     │ dispatcher picks up
                                     ▼
                       ┌───────────────────────────┐
           ┌───────────┤        IN_PROGRESS        ├───────────┐
           │           └──────┬─────────────┬──────┘           │
           │                  │             │                  │
needs user │    delegates     │             │ user calls       │
answer     │    parallel work │             │ stop_task        │
           ▼                  ▼             │                  ▼
┌──────────────────┐ ┌──────────────────┐   │       ┌──────────────────┐
│  AWAITING_INPUT  │ │AWAITING_SUBTASKS │   │       │    CANCELLED     │
│ (Zero token burn │ │(Event-driven     │   │       │ (Deliberate stop,│
│  until answered) │ │ wake on children)│   │       │  never retried)  │
└────────┬─────────┘ └────────┬─────────┘   │       └──────────────────┘
         │                    │             │
         │ answer_task        │ all child   ├──────────────────┐
         └──────► PENDING     │ tasks done  │                  │
                              └─────► IN_PROGRESS              │
                                            │                  │
                                  work done │                  │ exhausted
                                            ▼                  ▼
                                 ┌──────────────────┐ ┌──────────────────┐
                                 │    COMPLETED     │ │      FAILED      │
                                 │ (Artifact/result)│ │ (Blocker stated) │
                                 └──────────────────┘ └──────────────────┘

Three design decisions make this state machine behave completely differently from a ReAct loop:

1. Nothing Sequences This For You

There is no hidden dependency graph, no magic approval queue, and no automatic workflow engine pushing the agent to the next step. Each task owns its own transitions:

2. AWAITING_INPUT Is a Superpower, Not a Failure

In a naive loop, stopping to ask a question feels like failure, so models hallucinate a plausible parameter and keep going. That single guess then propagates downstream as settled fact.

In Colony, AWAITING_INPUT is a first-class yield state. The moment continuing becomes guesswork—or crosses an environment boundary only the operator can resolve—the agent records what it tried, what state the work is in, and the exact question in message, then halts. Token burn drops to zero. When the user answers, answer_task moves the task back to PENDING and the worker resumes cleanly with full context.

3. CANCELLED vs. FAILED, and AWAITING_SUBTASKS vs. Polling


4. Mid-Flight Steering and Card-First Inspection

State machines also fix the wait-or-kill dilemma while a task is actively running.

Steering Live Work Without Killing It

Suppose a background specialist is five minutes into an investigation and you realize it is looking at the wrong file—or you just merged a PR that makes half its plan obsolete. Killing and restarting throws away everything it has already discovered.

Colony supports non-destructive mid-flight steering: calling answer_task(task_id, message) on an IN_PROGRESS task queues the user’s message directly into the running worker’s next step. The agent sees “not that file” or “PR #2213 is already merged” before its next tool call and pivots cleanly in-flight.

Task Cards Before Raw Logs

Just as Part 2 argued for lazy-hydrating cold memory rather than dumping raw transcripts into the prompt, coordinator agents should never read raw background execution logs by default:

Inspection PrimitivePurposeContext Cost
list_tasksFleet snapshot: IDs, owners, statuses, queue depth vs. concurrency capTiny
get_task_details(task_id)The task card: prompt, status, compact result, pending question, recent steps, failure countSmall & fixed
read_task_logs(task_id, failures_only=true)Filtered diagnostic slice extracting only failed steps and tool remediation hintsBounded
read_task_logs(task_id, offset, limit)Paginated verbatim trace for deep post-mortemsExplicit slice

By separating the Task Card from the Execution Log, a coordinator can orchestrate ten background tasks without inheriting ten agents’ worth of intermediate noise.


5. Team Boundaries: Ownership, Outcomes, and Capability Routing

Once multiple specialists share a workspace, a second loop trap appears: cross-domain meddling.

If your FrontendEngineer builds canvas widgets under workspace/widgets/, your Architect builds containerized extensions under workspace/extensions/, and your AgentBuilder authors skills and personas, what happens when the Architect spots a one-line bug in a React widget?

If every agent holds edit_file, a helpful frontier model will happily patch the widget itself. And it will usually look like it worked—until you discover it violated three layout, theme-sync, or state conventions documented only in FrontendEngineer’s own skills.

Being Able to Edit a File Is Not Owning It

To keep specialists from stepping on each other’s conventions—or bouncing the same task back and forth in delegation ping-pong—Colony pairs the task state machine with four strict teamwork invariants:

  1. Area Ownership Includes Repairs: Even when something is already built and merely broken, its owner owns the fix. Non-owners are explicitly instructed not to guess fixes against skills they haven’t read; instead, read the fault just enough to diagnose it accurately, then hand a crisp diagnosis to the owner.
  2. State Outcomes, Not Implementations: A delegation brief states what the result must achieve and what must be true of it—leaving directory layout, naming, and tooling choices to the specialist’s own skills. The only exception is a detail the human user explicitly specified, which must be passed through and attributed to the user so the downstream specialist doesn’t mistake an arbitrary guess for a hard requirement.
  3. Capability-Aware Routing (delegates: true | false) + Temporary Workers: Not every subagent should be able to spawn subagents. Exposing a delegates capability flag on the live team roster (list_subagents) tells a coordinator immediately who can absorb a cross-domain outcome and fan it out (Orchestrator, Architect, FrontendEngineer, CadEngineer) versus single-slice specialists who need their piece carved out up front. Meanwhile, context-heavy legwork where you only need the conclusion—reading twenty files or sifting a massive log—goes to an unnamed temporary worker: fresh context, same base tools, zero delegation or scheduling rights.
  4. Loop Prevention on Delegation Chains: A delegated task records the chain it came down. An agent can delegate a smaller, distinct sub-piece, but is forbidden from passing the same task straight back up or sideways in a cycle.

Summary: Make Stopping and Asking First-Class Transitions

Autonomous loops break down when runtimes treat keep going as the only valid behavior until final completion. Reliable multi-agent systems replace open-ended loops with explicit control planes:

  1. Enforce hard boundaries early. When a failure lives outside an agent’s environment—like host daemon code it cannot read—stopping and reporting the boundary beats burning 40 turns guessing.
  2. Replace while (true) with a formal state machine. Give tasks explicit yield states (AWAITING_INPUT, AWAITING_SUBTASKS) and distinct terminal outcomes (COMPLETED, FAILED, CANCELLED).
  3. Steer in-flight instead of restarting from scratch. Inject user corrections into running tasks at the next step boundary, and inspect compact task cards before paging failure-filtered logs.
  4. Separate capability from ownership. Holding edit_file doesn’t mean owning every subsystem. Diagnose cleanly, hand off to the specialist whose skills govern that area, and delegate testable outcomes rather than line-by-line micromanagement.

In Part 4, we will move down to the execution boundary itself: Sandboxing, Container Runtimes & Hardware Bridges—how dual-workspace storage (workspace/ vs. files/), rootless OCI workshops (exec_in_container and run_in_container), and real physics/hardware bridges let agents build and verify physical systems without ever putting the host at risk.

← Back to Lab Notes