Pattern Matrix/White Paper/F4

ADPS Agent Design Pattern White Paper

F4 · Self-Heal Loop

When a deterministic failure signal fires, the agent automatically diagnoses, repairs, verifies, and loops until convergence or a circuit break.

Coordinate Reflection × Loop (cyclic)
Cost Medium-high (diagnosis, isolated repair, full verification, rollback, and hand-off)
Pattern group Reflection patterns
Summary When a deterministic failure signal fires, the agent automatically diagnoses, repairs, verifies, and loops until convergence or a circuit break.

Problem

Failing tests, lint errors, broken builds, and red CI runs provide clear criteria for automated repair. Missing dependencies, misplaced configuration, and local logic errors often follow repeatable diagnostic paths. Engineers still define the allowed scope, release authority, and hand-off path; an agent can perform the repeated diagnosis and verification inside those limits.

Self-Heal Loop lets the agent absorb these signals and close the repair loop automatically: a failure signal fires → diagnose the root cause → generate a fix → apply it → re-verify, and run another round if it is not fixed. It is the form of reflection closest to "agent autonomy," and it is the only mandatory loop in the reflection module. Once a fix fails, the system must either make another bounded attempt or hand the case off. Coding agents and internal repair systems provide practical examples of this structure, but their reported production results should be evaluated from primary sources and reproduced in the local environment.

Classification: Reflection × Loop

  • Vertical axis · Reflection: the agent detects its own errors and repairs them. Self-repair is the most practical application of the reflection mechanism, and it is especially common in software. It does not improve an output that already works; it recovers from a state that is already broken—the agent reads the failure signal, understands it, diagnoses it, and corrects it, and the whole process is a review and correction of its own output.
  • Horizontal axis · Loop: the structure is a forced cycle of detect failure → diagnose → repair → re-test. This loop is structural and mandatory, unlike the optional replay of Generator-Critic—the starting point is "the output is already broken," the loop is the means of recovery, another iteration is required if it is not fixed, and the termination conditions are tests passing, max_iterations bottoming out, or a detected regression triggering a rollback.

Solution and mechanics

A production Self-Heal Loop uses six stages plus three stop controls: Test Fail → Diagnose → Generate Fix → Critic → Atomic Apply → Verify. A failed verification rolls back the current attempt before retry or hand-off.

Before repair, classify the failure and check the permitted change scope:

Failure class Typical signal Default response
Runtime Timeout, dependency error, resource pressure Retry, switch, or degrade within policy
Process Wrong tool order, bad arguments, omitted step Revise the current plan or call
Business Conflicting rules, missing domain knowledge, unmet approval condition Request evidence or hand off; do not infer missing policy
Experience Correct result with excessive wait, weak explanation, broken interaction Feed product and workflow improvement

Each class maps to change_scope and release_authority. Editing a temporary artifact, rerunning a sandbox task, and changing a production rule are different permissions. If the required change exceeds authority, the loop stops and hands over the evidence.

The triple stop mechanism is what upgrades Generator-Critic into Self-Heal; drop any one of them and you risk "breaking the main branch":

  1. max_iterations hard circuit break: cap repair attempts according to task risk and local evaluation. This limits repeated fixes that keep moving the failure.
  2. independent critic verifier: use an independently configured reviewer to inspect the fix. A different model family may reduce shared blind spots, but independence also depends on prompts, evidence, and trace separation. Place verification at the risk points that matter to the workflow.
  3. stability check via signature: compare failure signatures to distinguish progress from a switch to a new problem, and define regression rules for severity, affected scope, performance, security, and coverage.

A layered cascade such as format → lint → build → test runs cheap signals first and reserves expensive checks for changes that pass the earlier gates. The exact layers should match the repository's toolchain.

Online repair and offline release

Online repair suits low-risk, reversible changes with immediate verification, such as correcting arguments in a sandbox, regenerating a temporary artifact, or opening a reviewable pull request. Changes to shared rules, skills, prompts, routing, and production configuration enter an offline process for grouped analysis, replay, impact review, approval, and versioned release. A local incident should not silently become a global policy.

Applicability

  • Domains with explicit acceptance signals, such as code, tests, and CI: Examples include lint fixes, CI repair, and diagnosis of failing tests.
  • A standard capability for coding agents: Aider, Spotify Honk, and GitHub Copilot all treat it as a default feature; it is infrastructure for coding agents.
  • Engineering pipelines with a clearly layered ground-truth signal: a CI with a clean format/lint/build/test layering is what suits self-heal. The more distinct the signals, the more reliable the repair.

Known failure modes

  • Forcing it where there is no deterministic failure signal: subjective judgments such as writing and design have no objective right-or-wrong signal, so use Generator-Critic (F1) rather than Self-Heal. Tasks where the cost of repair exceeds the cost of failure (changing the schema of a production database) belong in the governance module's Approval Gate with human review.
  • Failure drift: Without a stability check, the agent fixes one error and introduces another. Use failure-signature comparison, regression detection, and max_iterations together.
  • Regression cascade: when each round's fix is not an atomic commit, a string of cascading changes leaves the rollback unable to restore the correct state. The defense is per-iteration atomic commits plus the strict constraint "modify only files in the diagnosis."
  • False recovery: the agent changes the test instead of the code, weakening the test so it passes—every metric is green and every problem remains. The defense is for the critic to explicitly review whether "production code or the test was changed," plus a rule that test coverage may not drop.
  • Repairing without the missing knowledge: A model cannot recover an absent business rule, domain fact, or goal definition from a failure signal. Request evidence or hand off to the responsible owner.
  • Wrong diagnosis: Similar failure signatures may have different causes. Preserve original evidence, diagnosis confidence, and alternative hypotheses; high-risk cases need independent review.
  • Writing durable assets without authority: A runtime fix directly changes a shared skill, prompt, or production configuration. Durable changes require offline evaluation, approval, versioning, and rollback.
  • Bottoming out without handing off to a human: "crash if it can't be fixed" is an unacceptable engineering practice. HITL handoff must be a first-class citizen, with an accountable queue owner and a response target set from task risk and the business SLA.

Verification and metrics

  • Self-heal success rate: the proportion of repair attempts that pass the complete validation suite without human intervention. Compare it with the same task set under manual or non-repair baselines.
  • Repair attempts to convergence: record how many attempts successful and failed cases consume. Set the circuit breaker from observed risk, cost, and marginal gain.
  • Regression rate: the proportion of repairs that introduce a new failure or weaken an existing check. Define regression across correctness, security, performance, scope, and coverage.
  • HITL queue latency: measure how long a bottomed-out case waits for human handling. The target follows the operational severity and service commitment of the system.
  • Misdiagnosis rate: Review sampled cases against the final resolution and separate failed repair from an incorrect initial diagnosis.
  • Authority block and hand-off completeness: Track whether the loop stops when change_scope is exceeded and whether the hand-off includes evidence, attempted changes, diff, and rollback state.

Reference implementation

for i in range(MAX_ITERATIONS):           # configured from task risk and evaluation
                diagnosis = diagnose(current_failure)
                if diagnosis.required_scope > change_authority:
                    return handoff("insufficient_authority", evidence, diagnosis)
                fix = generate_fix(diagnosis)         # modify only files in the diagnosis
                critique = cross_family_critic(fix)   # different vendor, breaks self-bias
                if critique.block:
                    return "blocked_by_critic"        # hand off to HITL
                commit = atomic_apply(fix)            # per-iteration atomic commit
                new_failure = verify()                # format/lint/build/test four-tier cascade
                if new_failure is None:
                    return "fixed"
                if is_regression(current_failure, new_failure):   # business-defined regression rules
                    rollback(all applied commits)
                    return "rolled_back_regression"
                current_failure = new_failure
            return "max_iterations_human_handoff"     # bottomed out, hand off to human review
            

The Critic should be independent enough to challenge the repair. Regression rules come from the repository and business domain. Each attempt stays isolated so rollback restores a known state. Durable changes to shared assets and production configuration do not ship directly from the online loop.

Illustrative scenario

Consider a CI repair agent whose first version applies every proposed fix directly, with no independent critic, rollback boundary, or stability check. A failing test can turn into a different error, and later attempts may touch unrelated code while the system still reports that it is making progress. A stronger version places a hard cap on attempts, compares failure signatures, reviews each proposed change independently, runs layered validation, and isolates every attempt for rollback. Cases that do not converge enter an owned human-review queue with the trace and diff attached. Evaluate this design by full-suite acceptance, regression, rollback, and handoff evidence; production outcome claims require an attributed incident record.

Related patterns

  • Generator-Critic (F1): Generator-Critic improves a usable output through a linear review chain; replay is optional. Self-Heal starts from a verified failure and requires a bounded repair loop. Their stop conditions, rollback requirements, and change scope therefore differ.
  • Adversarial Review (collaboration module): the cross-family critic connects here. Rubber Duck's dual-model review is a lightweight version of this idea, and Adversarial Review pushes it to the extreme (multi-agent debate).
  • Iterative Hypothesis (reasoning module): the same Loop lineage; both are an iterative "try—verify—try again" structure.
  • Guardrail Sandwich (action module): the same sandbox lineage. Honk runs the agent in an isolated container with restricted permissions, compressing the blast radius from "production wide open" to "wide open inside the sandbox."

Engineering judgment

Self-Heal Loop applies when failure is explicit, repair is verifiable, rollback is available, and the change falls within delegated authority. Missing evidence, irreversible impact, or a wider change scope requires human handling.

Further reading

Suggested citation: ADPS, F4 Self-Heal Loop, Agent Design Pattern White Paper v0.3, 2026-07-13. Catalog · runnable code catalog · CC BY 4.0

Document status: This is a public review draft. Illustrative scenarios explain the mechanism and are not presented as verified enterprise cases. See the case library for attributed practice. ADPS welcomes case contributions with sources, measurement methods, and publication approval.