Building a Self-Healing Software Factory with Coding Agents: Persistent Tasks & Automated Repair
This article details how to build a software factory using coding agents by persisting tasks after commit, automating check-and-repair loops, handling human intervention, and scaling concurrency, drawing on real-world practices from archdev and Runway to outline a minimal architecture of a worker, persistent task store, and executor.
Too Long; Didn't Read
Reuse existing agents and CI to run a check-failure repair loop once. A single worker, a persistent task store, and an executor are enough to start this pipeline.
Record goals, commits, and each run separately. The same code can be re-run; a fix produces a new commit. On recovery, the system must know which task to pick up and which code version to check.
Handle restarts, version changes, and human waits before scaling concurrency. With traceable execution logs, you can see whether to add workers, tune CI, or improve review.
Task Boundaries
Start with a well-scoped task to see what happens from intake to delivery. Example: fix an export endpoint that returns 500 on empty results.
Goal: Fix export endpoint returning 500 when result is empty
Expected: Return 200 with CSV headers only
Unchanged: Existing auth logic, non-empty export format
Verification: Add empty-result test, re-run existing export and auth tests
Deliverable: A PR that passes required repo checks, ready for human mergeThis specification tells the agent what to change, what to preserve, and how to verify. Calvin Grunewald's archdev uses a Task DAG where each task is independently verifiable and maps to one PR for traceability. Dependencies between tasks (e.g., Task A modifies an interface, Task B consumes it) must define when a dependency is satisfied — whether the new code is merged to main or provided via a specific commit.
Persistent Execution
After the coding agent produces a commit, the terminal session ends but downstream work (CI, review, conflict resolution) must continue. Calvin splits this into:
Overseer — stays in the terminal to understand goals, decompose tasks, coordinate workers, and review worker output.
Worker — runs in an isolated Git worktree to implement changes.
Daemon — background process that takes over after archdev push, runs the repo's configured pipeline (checks, fixes, PR updates) in a temporary worktree, and pushes to GitHub.
The handoff turns "committed" into a durable to-do item. The frontend need not stay open; the executor can still find work. For a custom system, keep this separation but shrink scope: reuse existing agent CLIs and CI, add a local task store for state, and an executor that prepares directories, invokes the agent, runs checks, and follows up on PRs. Build task input and result viewing first; a rich Overseer UI can come later.
Storage revolves around four record types:
Task — Goal, acceptance criteria, dependencies, current progress, linked PR
Job — Repository, pending commit SHA, pipeline and config version
Run — Linked Task or Job, run number, executor, start/end time, exit reason, log location
Check Result — Commit SHA, baseline, check command, rule version, outcome
For the export task: the Task remains "fix empty-result behavior". Implementation runs link to the Task. Worker emits commit a1; executor logs a check Job. A test timeout adds another Run to the same Job. After fix commit b2, a new check Job is created for the new SHA. Identical repo, pipeline, config, and baseline notifications collapse into one Job; retries add Run records. Environment changes are recorded so later diffs explain divergent results.
A standalone Daemon isn't the only option. CI or hosted workflows can also drive continuous execution. OpenAI's Harness Engineering describes a loop of self-review, specialized review, edit, and feedback response until merge. The key is defining which component keeps receiving events, reading state, and advancing work after the interactive session ends.
Check and Repair
With durable to-dos, the manual "tests failed, please fix" handoff disappears. First pipeline for the export task:
Pick up task, prepare work directory
↓
Invoke agent to implement, record commit SHA
↓
Run repo checks, save results
├─ Lint/test failure: save evidence, fix, then check new commit
├─ Execution blocked: record cause, retry or wait by type
└─ Checks pass: create/update PR, follow remote CI and reviewBoth model work (diagnose, edit) and program work (launch commands, collect exit codes, record timeouts, failed tests) occur. The Daemon can also call models; background flow isn't purely deterministic.
Agent selection can center on this loop. Non-interactive entry points for major CLIs:
Gemini CLI : gemini -p "task" --output-format json — JSON includes answer and usage; stream-json emits tool calls, results, final state line by line
OpenCode : opencode run "task" — Defaults to shared background service; session, config, tool execution managed by service — distinguish command exit from service lifecycle
Cursor Agent : agent -p "task" --output-format json — Print mode respects permission config; unapproved actions are rejected; executor must recognize such outcomes
GitHub Copilot CLI : copilot -p "task" — Supports --allow-tool, --deny-tool for permissions; exits after task, convenient for per-run logging
These solve "how to call an agent from code". Non-interactive mode ≠ full permissions. Configure auth, workdir, pin version, model, project instructions, and permissions; validate behavior with a known task. Start with the tool your team already knows.
Wrap the agent CLI in a thin adapter. Each invocation receives task description and workdir; executor enforces timeout and budget, collects session ID, exit code, timeout flag, log path, and usage. After exit, read actual commits and diffs from Git to verify a commit was produced and no uncommitted changes remain. CLI success ≠ test success.
Tools with event streams can log progress incrementally; single-output tools work per-run. On timeout, a Supervisor kills the process and records the cause. For products like OpenCode where a background service runs tools, verify whether client exit cancels the server-side task; wire cancellation and timeout handling into the adapter.
At the CI stage, repair input must be concrete: include original acceptance criteria, current SHA, failing command, exit code, relevant logs. For long logs, send the failing segment plus full log location. When a new worker takes over, include previous attempts to avoid re-guessing.
After PR creation, v1 can poll CI and review status by PR number. When handling a feedback item, record the check run or comment ID and the PR head at that moment. On next poll, if the same feedback appears, you know it's already addressed; new commits trigger re-evaluation of outstanding issues. Poll interval can back off during idle periods.
Runway's first step was continuous PR follow-up: fix tests, respond to reviews, handle rebases. In a sample of 100 merged PRs from early November, 78 had zero human commits. This still includes human review but shows feeding feedback back to the originating task eliminates a class of manual follow-up.
Repair needs stopping conditions: per-run timeout, max repair rounds, total task budget — encoded in repo rules. If the same error recurs without progress, save evidence and escalate to human.
Some failures aren't code-fixable: dependency download failures, test infra flakes, intermittent test instability. Calvin's config identifies certain infra logs. Executor can schedule limited retries, store next_retry_at, re-queue on expiry. Use exponential backoff with jitter to avoid thundering herds; honor Retry-After headers within remaining budget. After restart, schedule by saved time — no process sits waiting. When cause is unclear, save diagnosis first, then decide on code repair.
Claim and Recovery
Calvin hit process-management issues: tasks paused without notification, orphaned child processes, model silence mistaken for worker death. He assigned a dedicated Supervisor per child-process group to monitor, restart, and reap. On stop, clean the entire process group so test/tool children don't leak resources. Model state and worker health are now displayed separately.
Durable task store answers "what's left"; Supervisor answers "how are processes doing". Recovery needs both.
Claim logic: select a pending Job, mark it running, assign a run number — all in one DB transaction with a state check. Two simultaneous triggers must not both succeed. Check-then-write races allow another executor to steal the job.
Proposed initial Job state machine (not archdev's actual enum):
Normal check: queued → running → passed / failed
Transient fault: running → retry_wait → queued
Commit update: old incomplete Job → superseded, new SHA → new Job
Human wait: Task → waiting_human, resume after answer written backpassedmeans this check Job met configured conditions. Task merge-readiness still aggregates remote CI, review, and acceptance for the current SHA. Code-induced failed triggers repair and a new commit; transient faults follow retry rules. Superseded Jobs keep late results for history but don't advance the current task.
Even a single executor faces claim races: scheduled poll and manual trigger may fire together; restart may encounter stale child processes. Before re-claiming, verify whether the old execution is still alive; decide to clean up or adopt.
With multiple executors, use leases: a worker holds a lease for a period, renews periodically; expiry allows another to take over. Each hand-off generates a new run number; on result write-back, verify the run number is still current, rejecting stale overwrites. Calvin mentioned cloud task leases but didn't detail the full protocol — these are implementation gaps to fill.
Lease expiry only means the system permits takeover; the old process may still run. A DB write rejection doesn't stop it from calling GitHub. Therefore, before any push, comment, or merge, re-verify task ownership and current version; route critical remote operations through the executor using the provider's conditional or idempotency mechanisms.
Classic race: GitHub creates PR successfully, executor crashes before saving PR number. On restart, DB still says "PR creation incomplete"; retry creates a duplicate. Starter fix: stable branch name and task identifier. Before retry, query existing PR by repo, head branch, and task ID; if state matches, reuse. Serialize create requests per task. "Check first" still races under multi-executor contention. External actions aren't transactional with local DB; handle retries per operation.
Runway also mandates idempotent external actions. They saw multiple agents fight over the same work, cancelling each other's replicas, leaving none. Durable to-dos don't auto-solve duplicate execution and interference.
Runtime isolation has similar boundaries. Git worktrees isolate HEAD and index but share some repo data and default config. They separate code directories; app ports, databases, and background services need separate arrangement.
OpenAI's practice spins up a full app per worktree with temporary logging, metrics, and tracing. The export task's integration tests need isolated ports, isolated test data, and resource cleanup logged in the run record. Task ID and run number in logs let you correlate agent, test, and app logs for a failure.
Earlier analysis of Codex Sandbox showed process-permission boundaries. Here, worker credentials and database access are part of the runtime environment design. Worktree handles Git directory isolation; file and network permissions are enforced by the actual execution environment.
Approval per Commit
Assume the executor recovers and the export task passes tests. Which code version actually passed?
Runway's retrospective revealed two failure modes: reviewer approved, but agent kept pushing new commits to the PR; checks blocked merge, yet a tool overrode and merged anyway. They now require re-verifying conditions on the exact commit being merged.
Using illustrative SHAs:
b2's results describe b2. At c3, which checks re-run and which approvals carry over depends on the new version and repo rules. The executor cannot keep a forever-valid "tests passed" flag on the Task.
Check records tied to commit SHA, baseline, and rule version make this auditable. Old results are retained; new commit enters check, delivery status updates accordingly. Wait for pending CI. A required check that never ran must be judged per repo policy — not by counting green badges. Records can also store toolchain version, dependency lockfile hash, test environment ID, and full log location. When the same commit yields different results in two environments, these fields enable debugging.
Calvin's continue_on_error: true highlights another nuance: lint, test, or policy failures can still proceed to review and repair so the agent gets a chance to fix. Final deliverability requires a separate verification of all mandatory conditions. The published config snippet doesn't show the final gate; don't assume archdev has a pass-through hole.
Design your executor to separate "what to fix next" (read failure evidence) from "can we ship now" (verify current version satisfies all required conditions).
GitHub provides some guards: branch protection can dismiss stale approvals, require re-approval on new pushes, enforce up-to-date branches via strict status checks, or use merge queues to validate the latest base plus queued changes. All need repo-specific configuration.
Future auto-merge will face a check-then-act gap: executor verifies head is c3, but before the merge request fires, PR updates to d4. GitHub CLI's gh pr merge --match-head-commit <SHA> constrains the expected head; repo check and approval rules still apply. V1 keeps human merge, but it's worth handing over the current SHA and its results cleanly.
Policy Replay
Once the pipeline runs, models, prompts, and review criteria will evolve. Can a cheaper model work? Does writing a failing test first yield more stable fixes? Compare using existing tasks.
Calvin separates Mechanism (Daemon: responds to Git hooks, claims Jobs, runs pipelines, records state) from Policy (repo's archdev.json: maps events to pipelines, defines prompts and models per step). His config routes branch updates, PR feedback, rebase conflicts to different pipelines. Failed check logs feed the repair step; after fix, commit and review. The pipeline runner is relatively stable; each repo configures its own commands, models, and review rules.
In your system, check commands, repair models, review rules, budgets, and human-intervention triggers go into version control. Each Job pins the config version it used, preventing mid-queue config changes from mixing rules across steps. Re-checks explicitly run against the new version.
This connects to earlier Review Gate practice: if a PR modifies check rules, don't use the modified rules to judge itself. Executor reads rules from a trusted baseline or approved config; rule upgrades get their own review before applying to subsequent tasks. Otherwise a broken export task could delete the empty-result check and show "passed".
With rules pinned, replay becomes practical. Calvin archives historical PR issues, the PR head at the time, and reference fixes; re-runs repair steps in a sandbox; an independent scorer verifies fix correctness and regressions.
One disclosed comparison had only 19 cases. A counter-example: cheaper model had lower per-fix cost but in a case that should have been rejected, it deleted a shared wrapper function flagged by review. The review comment disappeared, and the required functionality vanished with it.
Thus the export task's "auth unchanged, non-empty format unchanged" become replay criteria. Evaluate both: empty result correct? original behavior preserved? Swap model or prompt, run same input batch, compare — see what cost savings actually buy.
Reviewers need similar evaluation. Runway gives reviewers plan, diff, and context for back-and-forth with the implementer; Calvin uses independent multi-agent adversarial review. Extra roles add another defect-detection pass; quality still hinges on whether raised issues are valid and fixes don't regress.
This historical corpus only covers known issues. New failures encountered in production can be added with their code, environment, and rule version. Future policy changes then have a concrete regression suite.
Human Intervention
Technical problems can be debugged automatically; product decisions, credentials, or costs may need a human. Task state must accommodate waiting.
Calvin initially asked in chat. Later found Overseer had paused tasks 67 times without notifying him. Even when he answered, the next worker only saw task name and description — not the answer.
He moved questions into the Task: store pause type, reason, specific question, suggested answer. Human reply writes back as a comment; task reopens; next worker loads the answer with the task.
For the export task, suppose investigation reveals a caller depends on the old 500. A product decision is needed: migrate that caller too? Executor saves current commit, completed checks, and the question; releases the process; waits for answer; other tasks proceed.
At least three steps: Persist the question first, then notify human ; Answer links to the specific question; On resume, inject the answer into the next round's input . Notification failures retry; duplicate replies detected to avoid double-triggering repair. Storing only in chat history doesn't guarantee the next worker reads it.
Conditions change during wait. Human agreed to a specific plan; by reply time the plan may have changed. Cost and resource conditions may shift. Before resuming, read current task and verify the answer still applies.
Framework resume behavior matters. LangGraph docs: with persistent checkpoints, interrupt() saves state and waits for input; on resume, the interrupted node re-executes from start. If resources were created before the prompt, they may be created again. When using such frameworks, separate prompting from external writes; deduplicate potentially re-run actions.
Human-intervention scope differs between the two practices. Calvin reserves six categories for himself: credentials, cost, production infra (including merge), irreversible ops, product decisions, and tasks explicitly requiring his approval. Runway routes by PR risk: migrations, auth, secrets, CI and deploy configs still need owner approval.
Runway started with AI and human approving in parallel, logging disagreements, then gradually allowed AI-only approval. In their core API repo, median wait for first approval dropped from 2.3 hours (September) to ~5 minutes (mid-November). This shortens approval latency; total lead time still includes implementation and checks.
Your system can start by saving AI suggestions, observing divergence from human judgment, then incrementally adjusting permissions. Just capturing what needs a human and recording it already eliminates much terminal-blocking wait.
Concurrency Scaling
Only after one task sustains end-to-end can you see where time goes.
Calvin hit local compute limits; two machines weren't enough; moving to cloud. More workers consume more build, test, and review resources. Queue holds waiting work; capacity must be provisioned separately.
If CI is the bottleneck, adjust CI granularity. Kun Chen (credited by Calvin) described on X: each branch does a lightweight build + lint first; branches are batched into a single PR that runs heavy CI. One active PR per person per repo; subsequent branches wait for next batch. He reports daily PRs dropped from ~200 to ~30 while delivery increased. This is a single data point but shows task granularity, CI batching, and PR granularity can be tuned independently. Batching reduces duplicate checks at the cost of larger review and failure-blast radius.
Using GitHub Actions directly requires attention to its queuing rules. Same concurrency group defaults to one pending run; new runs replace old. queue: max now supports up to 100 waiting runs; excess are cancelled.
Replacing an old commit's checks with a new one on the same PR is often desired. Different business tasks cancelling each other loses work. Executor must detect cancellation reason and decide: reschedule, keep waiting, or abandon because a newer version exists. Business tasks remain in your own queue; don't conflate pipeline wait state with complete task record.
If review is slow, see which comments repeat and which approvals stall. If conflicts are slow, revisit task decomposition and dependencies. If environment startup is slow, consider pre-warming and reuse. Adding workers solves only some problems; others need targeted fixes.
Watch measurement definitions. Runway reports 38% of October merged PRs advanced by cloud agents — metric is PR count. Kun's batching shows PR count changes with delivery mode. For your system, measure: task start-to-merge-ready time, human handoffs count, repair rounds, resource consumption.
The earlier Task, Job, and Run records now pay off. A slow task: did it wait in queue 30 min? Environment startup 10 min? Same issue repaired 5 times? Split timings to know where to improve next.
Minimal Architecture
Back to the export task. Starter architecture fits in a few components: one existing Coding Agent, one persistent task store, one executor, plus the repo's existing CI. Input: goal and acceptance criteria. Output: commit, check results, merge-ready PR. Human decides final merge.
Build in three phases: 1. Executor in a workdir calls agent, runs checks, feeds failure back — complete one repair loop. 2. Persist every run; handle interrupt/restart, duplicate triggers, external action retries. 3. Hook PR feedback and human answers so tasks resume after waiting.
Validate with deliberate interruptions:
Close frontend session — does the submitted commit continue checking?
Interrupt after PR creation but before saving PR number — on resume, does it detect existing PR?
Push another commit after tests pass — does delivery state re-wait for corresponding checks?
Task pauses for human answer — on resume, does it load the answer and prior progress?
Once these behaviors are stable, add task graphs, parallel workers, auto-approval, or deployment pipelines on a solid foundation.
This year we've traced from Harness to Project, focusing on how environment, conventions, and cross-session state persist. Building your own software factory takes that line one step further: let tasks continue after the session ends, recover from failures, and pause cleanly when humans are needed. Get one real task through this loop first; then, based on where it spent time and broke, decide what to add next.
References
Calvin Grunewald, A Look Inside the Factory (https://thebuildingmachine.com/p/a-look-inside-the-factory)
Calvin Grunewald, Architecture Long-form X Post (https://x.com/CalvinGrunewald/status/2123472779559436533)
Alejandro Alvarez / Runway, Building a Software Factory (https://runway.com/news/engineering/building-a-software-factory)
Kun Chen, Batched Branches & CI Architecture X Post (https://x.com/kunchenguid/status/2123985561551778151)
OpenAI, Harness Engineering (https://openai.com/zh-Hans-CN/index/harness-engineering/)
Google, Gemini CLI Headless Mode Reference (https://geminicli.com/docs/cli/headless/)
OpenCode, CLI Intro (https://opencode.ai/docs/cli/)
Cursor, Using Headless CLI (https://cursor.com/docs/cli/headless)
GitHub, GitHub Copilot CLI (https://docs.github.com/en/copilot/concepts/copilot-surfaces/copilot-cli)
Git, git-worktree (https://git-scm.com/docs/git-worktree)
GitHub Docs, About Protected Branches (https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/about-protected-branches)
GitHub CLI, gh pr merge (https://cli.github.com/manual/gh_pr_merge)
GitHub Docs, Control Workflow Concurrency (https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/control-workflow-concurrency)
LangGraph, Interrupts (https://docs.langchain.com/oss/python/langgraph/interrupts)
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
