Level 3 路 Loop Engineering

Run Parallel Agents Without Corrupting Code or State

Parallel agents are only useful when each worker has isolated code and state, independent context, and a verification path that promotes one synthesized result instead of merging chaos.

Start With Isolation, Not Prompts

The central mistake in parallel agent work is treating concurrency as a prompting problem. It is a state problem. If two agents can write the same files, mutate the same database, share a long conversation, or inherit the same mistaken premise, parallelism mostly multiplies damage. The harness has to make corruption structurally hard before the first model call happens.

Use one Git worktree per agent, one branch per attempt, one dependency cache boundary where practical, and one database branch per worker. For Postgres, that usually means a Neon-style branch, a cloned local database, or a schema-per-agent convention with strict connection strings injected by the harness. The agent should never decide its own target branch or database. The orchestrator assigns `WORKTREE_PATH`, `GIT_BRANCH`, `DATABASE_URL`, test command, budget, and success rubric as immutable inputs.

This is also where you prevent context anchoring. Do not fan out from a large, messy chat transcript. Fan out from a compact task packet: goal, relevant files, constraints, known failing tests, acceptance checks, and forbidden changes. If research produced uncertainty, preserve it as explicit open questions, not conversational residue. Parallel agents should disagree because they explored different hypotheses, not because they inherited different accidental context.

Separate Search From Writes

Once isolation exists, decide which agents are allowed to change code. A reliable pattern is `research -> plan -> implement`, with fresh contexts between phases. Research agents inspect independently and return evidence: files, line references, failure modes, commands run, confidence, and proposed intervention. They should not make broad edits. The synthesizer then chooses a small number of implementation attempts to launch in separate worktrees.

For large codebases, run fan-out review passes before implementation. Assign bounded lenses such as authorization, data integrity, performance, migration safety, frontend regressions, and test coverage. Require findings to include exact locations and a reproducible check, then dedupe and rank them. This avoids the common failure where ten agents all patch the first obvious bug while missing the systemic one.

Write agents need narrower authority than review agents. Give each implementation worker a precise goal prompt, acceptance tests, and a maximum change surface. Expensive frontier models are best spent here when the plan is coherent and the blast radius is high. Use cheaper or faster models for classification, grep-heavy reconnaissance, summarization, and low-risk fix attempts. The routing rule is simple: pay for judgment at branch points and for execution where reversibility is low; save money on bounded mechanical work.

Verify Adversarially, Then Compete

After parallel implementation, do not ask each agent whether it succeeded. Self-review is biased toward the path it already took. Verification should be a separate phase with fresh context and read-only access to candidate branches. Give verifier agents the original rubric, the diff, test output, screenshots or logs where relevant, and a mandate to disprove success. Their job is not to be fair; it is to find contract violations, hidden coupling, untested paths, data migration hazards, and places where the patch satisfies the visible test while breaking the product intent.

For ambiguous choices, use tournament selection instead of scoring a full list in one context. Pair candidate A against candidate B with an isolated judge, then pair the winner against C, or run multiple bracket orders when the decision is high value. Head-to-head comparison reduces list-position bias and makes tradeoffs concrete: smaller diff versus more complete fix, better architecture versus lower migration risk, faster patch versus stronger tests.

The promotion rule should be deterministic. A candidate must pass the repository test suite, satisfy task-specific checks, survive adversarial review above a confidence threshold, and beat alternatives on a written rubric. If none pass, synthesize the verifier findings into a new task packet and relaunch a smaller round. Avoid letting the original implementation agent repair its own work in the same context unless the issue is trivial. Fresh repair contexts reduce sunk-cost behavior.

Synthesize One Result

Parallelism creates many partial truths. The harness needs a synthesis step that produces one branch, one migration path, one PR description, and one audit trail. Do not merge competing worktrees mechanically. Have a synthesizer inspect the winning candidate, pull in narrowly scoped improvements from losing candidates when they are independently justified, and rerun verification after every integration. This is where you turn exploration into a coherent patch.

For stateful systems, synthesis must include database reconciliation. If workers used branched databases, compare schema diffs, generated migrations, seed changes, and data assumptions. Reject candidates that only pass because their branch contains silent manual state. Require migrations to run from a clean base and from a realistic snapshot. Long autonomous loops should record every command, model, token spend, branch, database branch, test result, and verifier verdict in external state, not chat memory.

That external state is what makes overnight work resumable. Store loop status in Postgres or another durable system: task id, stage, assigned worker, model, cost ceiling, artifact paths, current verdict, and next action. The agent can reason, but the harness owns the lifecycle. If the process crashes, the next run should know whether it is waiting on tests, verification, synthesis, or human approval without replaying a 200k-token conversation.

Control Budget By Controlling Shape

Cost control is not mainly about choosing a cheaper model. It is about preventing unbounded workflow shape. Cap fan-out width, context size, retry count, verifier count, and promotion rounds. Batch agents only when prerequisites are met. Stop early when candidates converge on the same patch or when adversarial review finds a shared blocker that requires a new plan rather than more attempts.

Use flagship models for high-information-density moments: architecture selection, cross-file migrations, subtle bug repair, synthesis, and final adversarial review. Use smaller models for routing, log triage, file inventory, duplicate detection, and rubric formatting. If a model is scarce or expensive, never spend it discovering what a cheaper model can collect. Spend it deciding what to do with the collected evidence.

The result is not a swarm. It is a controlled promotion pipeline. Worktrees prevent code conflicts, database branches prevent state conflicts, fresh contexts prevent anchoring, adversarial verifiers prevent self-preference, tournaments prevent naive ranking, and synthesis prevents fragmented output. Parallel agents become reliable when the harness treats every model call as a replaceable worker inside a deterministic system.

Key takeaways

  • Give every write-capable agent its own Git worktree, branch, and database branch before parallel execution starts.
  • Fan out research and review broadly, but keep broad code changes behind a supervised implementation and synthesis stage.
  • Use fresh-context adversarial verifiers to disprove candidate success against the original rubric.
  • Select among candidate branches with tournament comparisons, then promote through deterministic checks rather than agent confidence.
  • Track loop state, artifacts, verdicts, and cost in external storage so long runs are resumable without chat history.
  • Control spend by capping workflow shape and reserving frontier models for planning, synthesis, and high-risk implementation.