← All posts

Why I Deleted My Ad-Hoc Loop Engine and Modeled Agent Rework as Append-Only Attempts

Strip away the UI and every coding agent boils down to the same five lines:

while (model emits tool_call):
  result = execute(tool_call)
  messages.push(result)

That inner agent loop shines during interactive debugging: hand it a repo and a failing test, and it greps, edits, and re-runs until green. The moment you run it unattended overnight (nightly CI fixes, dependency audits, maker-checker PRs), four cracks open at once: no hard budget ceiling, self-review blind spots, no durable pause point for human approval, and an unreadable chat transcript whenever a retry crashes mid-flight.

Early in CrewDesk, I followed the obvious instinct and built a standalone Loop subsystem (LOOP.md, loopStep, loop-generator / loop-verifier, and .workflows/loop.js metadata write-backs).

After running it in practice, I deleted the entire subsystem. This post explains how that file-driven loop broke and why modeling rework as append-only attempts on an acyclic DAG turned out far cleaner.

From inner agent loops to an acyclic declarative workflow engine with budgeted rework edges, append-only SQLite attempt ledgers, and shared Git worktrees

1. Four Ways the Standalone Loop Subsystem Failed

The building blocks of outer loops (cron scheduling, isolated worktrees, maker-checker separation, persisted state) were right. Wrapping them in file-mutating while loops was the mistake:

  1. Control-plane state mixed with the model's scratchpad. Having an agent update LOOP.md or script metadata to advance iterations meant one dropped field or malformed edit broke the state machine.
  2. Competing schedulers fighting over one worktree. Maintaining a Loop engine beside Agent Team and Workflow created duplicate locks, duplicate schedulers, and split approval paths.
  3. Silent zombie loops. Without consecutive-failure circuit breakers or a unified inbox, a broken branch could burn tokens all night or stall silently behind a stale lock.
  4. No audit trail for rework. Wrapping retries in a script while erased basic postmortem facts: how many rounds ran, what diff round 1 produced, why it was rejected, and who authorized round 3.

2. The Core Split: Acyclic Forward Topology, Append-Only Attempts

Instead of allowing arbitrary cycles in the workflow DSL, I separated inner exploration from outer control:

  • Inside a node: keep the full inner agent loop so workers can inspect code, run commands, and iterate freely.
  • Outside a node: enforce a strictly acyclic declarative DAG (packages/workflow, where topoSort throws GraphCycleError on any forward cycle) backed by a SQLite execution ledger.

Rework ("verification failed → send back to fixer") is modeled via ADR 0042: what re-enters is the execution ledger (new attempt rows), never the graph topology.

Every kind: "rework" edge obeys four rules enforced in code:

  1. Parse-time budget enforcement. A rework edge must point to a forward-reachable upstream node (descendantsOf(def, edge.to).has(edge.from)) and must declare budget: { maxAttempts, onExhausted: "fail" | "human" }. Unbounded cycles fail validation before a single run starts.
  2. Append-only attempts and downstream superseding. Triggering rework marks the target node and all downstream rows superseded (preserved verbatim for audit), appends a new workflow_node_run row, and injects structured { attempt, rework: { from, reason } } into the next prompt.
  3. Zero hidden loop state — crash and resume cleanly. deriveRework() derives pending retries straight from SQLite history rows, so a process restart preserves attempt counts and rejection reasons without in-memory state.
  4. Budget exhaustion turns into a synthetic human gate (${nodeId}#budget). Past maxAttempts + granted, "fail" terminates cleanly with the last error; "human" pauses and sends prior diffs and failure reasons to the operator inbox to grant one extra round or reject.

3. Four Quiet Details That Keep Unattended Loops Safe

  1. 13-operator JSON-Logic subset, zero eval(). Edge conditions allow only var, ==, !=, >, >=, <=, <, in, and, or, not, 3-arg if, and !!. Outgoing edges evaluate once on node completion and freeze into routed_to so historical routing never drifts.
  2. One shared Git worktree for Maker and Checker. Giving each node its own worktree prevented the verifier from seeing the fixer's diff. Sharing one isolated worktree across a workflow execution keeps contexts strictly separate without forcing yolo permission bypasses.
  3. Parallel execution, deterministic serial persistence. Ready waves run concurrently via Promise.allSettled for speed, then commit in deterministic wave order with join: "any" or join: "all".
  4. Sandboxed scripts and 3-strike cron circuit breakers. Deterministic script nodes stay disabled by default and run without network or .env access when enabled; scheduled triggers trip a circuit breaker after 3 consecutive failures and alert the room.

Here is the core edge and budget structure of a validated nightly CI fix-and-verify workflow (parseWorkflow() in @chengchenccc/workflow):

{
  "id": "nightly-ci-triage-and-fix",
  "triggers": [{ "type": "cron", "cron": "0 3 * * *", "enabled": true }],
  "concurrencyPolicy": "forbid",
  "edges": [
    { "from": "start", "to": "fix_failure" },
    { "from": "fix_failure", "to": "verify_fix" },
    {
      "from": "verify_fix",
      "to": "fix_failure",
      "kind": "rework",
      "when": { "==": [{ "var": "passed" }, false] },
      "budget": { "maxAttempts": 2, "onExhausted": "human" }
    },
    {
      "from": "verify_fix",
      "to": "human_signoff",
      "when": { "==": [{ "var": "passed" }, true] }
    },
    {
      "from": "human_signoff",
      "to": "fix_failure",
      "kind": "rework",
      "when": { "==": [{ "var": "decision" }, "revise"] },
      "budget": { "maxAttempts": 3, "onExhausted": "human" }
    }
  ]
}

4. Where This Pattern Stops Fitting

Cramming every task into a declarative DAG is just as bad as running unbounded scripts. Acyclic workflows fit repeatable Closed Loops with concrete acceptance criteria:

  • One-off refactors and live debugging belong in an interactive CLI agent loop.
  • Ambiguous exploration belongs in an Open Loop coordinator until the path stabilizes (see Open Loop vs. Closed Loop).

At the infrastructure layer, CrewDesk's engine currently targets single-host SQLite (BEGIN IMMEDIATE for concurrency locks). If you need thousands of concurrent executions across multiple workers, you would swap the storage and queue layer — while keeping the exact same domain model: acyclic forward graphs, mandatory rework budgets, and append-only attempt rows.


Related Reading & ADRs:

Want to try it on your own machine?

Both CrewDesk and oma are MIT open source — run locally on Bun + SQLite in two commands.