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.
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:
- Control-plane state mixed with the model's scratchpad. Having an agent update
LOOP.mdor script metadata to advance iterations meant one dropped field or malformed edit broke the state machine. - Competing schedulers fighting over one worktree. Maintaining a
Loopengine besideAgent TeamandWorkflowcreated duplicate locks, duplicate schedulers, and split approval paths. - 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.
- No audit trail for rework. Wrapping retries in a script
whileerased 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, wheretopoSortthrowsGraphCycleErroron 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:
- Parse-time budget enforcement. A rework edge must point to a forward-reachable upstream node (
descendantsOf(def, edge.to).has(edge.from)) and must declarebudget: { maxAttempts, onExhausted: "fail" | "human" }. Unbounded cycles fail validation before a single run starts. - Append-only attempts and downstream superseding. Triggering rework marks the target node and all downstream rows
superseded(preserved verbatim for audit), appends a newworkflow_node_runrow, and injects structured{ attempt, rework: { from, reason } }into the next prompt. - 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. - Budget exhaustion turns into a synthetic human gate (
${nodeId}#budget). PastmaxAttempts + granted,"fail"terminates cleanly with the last error;"human"pauses and sends prior diffs and failure reasons to the operator inbox tograntone extra round orreject.
3. Four Quiet Details That Keep Unattended Loops Safe
- 13-operator JSON-Logic subset, zero
eval(). Edge conditions allow onlyvar,==,!=,>,>=,<=,<,in,and,or,not, 3-argif, and!!. Outgoing edges evaluate once on node completion and freeze intorouted_toso historical routing never drifts. - 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
yolopermission bypasses. - Parallel execution, deterministic serial persistence. Ready waves run concurrently via
Promise.allSettledfor speed, then commit in deterministic wave order withjoin: "any"orjoin: "all". - Sandboxed scripts and 3-strike cron circuit breakers. Deterministic
scriptnodes stay disabled by default and run without network or.envaccess 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: