# What Is the Self-Healing Mechanism in gpt-engineer and How Does It Automatically Fix Code Execution Errors?

> Discover gpt-engineer's self-healing mechanism. Learn how it automatically detects and fixes code execution errors using an LLM feedback loop for autonomous code repair.

- Repository: [Anton Osika/gpt-engineer](https://github.com/AntonOsika/gpt-engineer)
- Tags: deep-dive
- Published: 2026-03-06

---

**gpt-engineer's self-healing mechanism detects runtime failures in generated code, constructs corrective prompts from error outputs, and iteratively repairs the codebase through an autonomous LLM feedback loop until execution succeeds or exhausts the retry limit.**

The gpt-engineer project automates software creation through large language models, but generated code frequently contains runtime errors on initial execution. To solve this, the repository implements a **self-healing mechanism** that transforms execution failures into actionable debugging sessions without requiring manual developer intervention. This system operates as a closed loop between code execution, error analysis, and AI-driven regeneration.

## Core Components of the Self-Healing Mechanism

The architecture relies on three integrated components that switch the standard execution pipeline into a repair-oriented workflow.

### The `self_heal` Orchestration Function

Located in [`gpt_engineer/tools/custom_steps.py`](https://github.com/AntonOsika/gpt-engineer/blob/main/gpt_engineer/tools/custom_steps.py) (lines 40-78), the `self_heal` function serves as the primary controller. It validates the existence of the entry-point file (`ENTRYPOINT_FILE`, typically [`run.sh`](https://github.com/AntonOsika/gpt-engineer/blob/main/run.sh)), manages the execution environment, and implements the retry logic bounded by `MAX_SELF_HEAL_ATTEMPTS` (defaulting to 10 iterations).

### The `--self-heal` CLI Activation Flag

In [`gpt_engineer/applications/cli/main.py`](https://github.com/AntonOsika/gpt-engineer/blob/main/gpt_engineer/applications/cli/main.py) (lines 90-95), the command-line interface exposes a `--self-heal` argument. When provided, the main entry point substitutes the standard `execute_entrypoint` runner with the `self_heal` function, diverting all generated code through the healing pipeline while preserving the rest of the generation workflow.

### The `improve_fn` Repair Pipeline

This component (referenced in [`gpt_engineer/core/default/steps.py`](https://github.com/AntonOsika/gpt-engineer/blob/main/gpt_engineer/core/default/steps.py)) bridges error detection and code regeneration. It wraps the standard AI interaction sequence: accepting the augmented prompt (original specification plus error context), querying the LLM via the `AI` class, and parsing the response into a revised `FilesDict` through `chat_to_files_dict`.

## How the Self-Healing Mechanism Works Step-by-Step

The mechanism follows a deterministic seven-phase cycle to automatically fix code execution errors:

1. **Entry-point validation** – The system verifies that `ENTRYPOINT_FILE` exists within the `FilesDict`. If the entry point is missing, it raises `FileNotFoundError` immediately.

2. **Execution attempt** – The current `BaseExecutionEnv` (defaulting to `DiskExecutionEnv` for local execution or Docker containers) uploads the file set and spawns the entry point using `popen`.

3. **Error detection** – After `communicate()` returns, the exit status is evaluated. Return code `0` indicates success, `2` signals a skip condition, and any other value triggers the healing protocol.

4. **Prompt construction** – The mechanism concatenates `stdout` and `stderr` into a new `Prompt` object containing the original user specification, the observed failure output, and instructions to modify the code to meet requirements.

5. **AI-driven repair** – The `improve_fn` sends this contextual prompt to the LLM, receives corrected code blocks, and translates them back into a `FilesDict` via `chat_to_files_dict`.

6. **Retry loop** – Steps 2 through 5 repeat recursively. Each iteration uses the newly generated file set as the execution target.

7. **Termination** – The loop breaks when execution returns success (exit code 0) or when the attempt counter reaches `MAX_SELF_HEAL_ATTEMPTS`. The final `FilesDict` is returned to the main pipeline.

## Using Self-Healing in Practice

You can leverage this capability either through the command line interface or programmatically within Python applications.

### Enabling Self-Healing via CLI

Activate the mechanism by appending the `--self-heal` flag to your standard gpt-engineer command:

```bash
gpt-engineer . --self-heal

```

*The CLI parser detects the flag, swaps the execution function to `self_heal`, and automatically iterates through repair cycles until the generated program runs without error or hits the attempt limit.*

### Programmatic Implementation

For custom workflows, import and invoke the `self_heal` function directly:

```python
from gpt_engineer.core.ai import AI
from gpt_engineer.core.default.disk_execution_env import DiskExecutionEnv
from gpt_engineer.core.files_dict import FilesDict
from gpt_engineer.core.prompt import Prompt
from gpt_engineer.tools.custom_steps import self_heal
from gpt_engineer.core.preprompts_holder import PrepromptsHolder

# Initialize components

ai = AI(model_name="gpt-4o", temperature=0.1)
exec_env = DiskExecutionEnv()
files = FilesDict({
    "run.sh": "python main.py",
    "main.py": "print('Hello ' + undefined_var)"
})
prompt = Prompt("Create a CLI that prints 'Hello World'")

# Execute with self-healing

healed_files = self_heal(
    ai=ai,
    execution_env=exec_env,
    files=files,
    prompt=prompt,
    preprompts_holder=PrepromptsHolder()
)

# healed_files now contains the corrected code

```

*This example intentionally includes an undefined variable. The `self_heal` function will catch the `NameError`, prompt the LLM to fix it, and return a corrected `FilesDict` where `undefined_var` is properly defined.*

## Configuration and Execution Limits

The **self-healing mechanism** includes several configurable parameters that control its behavior. The `MAX_SELF_HEAL_ATTEMPTS` constant (default 10) prevents infinite loops by capping repair iterations. The system relies on the `ENTRYPOINT_FILE` environment configuration to identify which script triggers execution—typically [`run.sh`](https://github.com/AntonOsika/gpt-engineer/blob/main/run.sh) in the generated project root.

Execution occurs within a `BaseExecutionEnv` abstraction, allowing you to implement custom sandboxing. By default, `DiskExecutionEnv` provides local filesystem isolation, though Docker-based environments can be substituted for enhanced security during the automatic fix cycles.

## Summary

- **Autonomous error recovery**: The mechanism captures runtime `stdout` and `stderr`, feeding failures back to the LLM as corrective context without manual debugging.
- **Three-component architecture**: The `self_heal` function (orchestration), `--self-heal` CLI flag (activation), and `improve_fn` (regeneration pipeline) work together to create the healing workflow.
- **Configurable retry logic**: The system attempts repairs up to `MAX_SELF_HEAL_ATTEMPTS` times before returning the final result, preventing infinite loops.
- **Flexible integration**: Available both as a CLI flag for standard usage and as a Python function (`self_heal` in [`custom_steps.py`](https://github.com/AntonOsika/gpt-engineer/blob/main/custom_steps.py)) for embedded applications.
- **Environment agnostic**: Functions with any `BaseExecutionEnv` implementation, supporting local disk, Docker containers, or custom sandboxed environments.

## Frequently Asked Questions

### How does gpt-engineer detect that code needs healing?

The system monitors the return code of the entry-point process executed via `BaseExecutionEnv.popen()`. Return codes other than `0` (success) or `2` (execution skip) are interpreted as failures, triggering the prompt construction and LLM repair sequence in `self_heal`.

### Can I customize the maximum number of self-healing attempts?

Yes. The `MAX_SELF_HEAL_ATTEMPTS` parameter controls the retry limit and defaults to 10 iterations. When calling `self_heal` programmatically, you can modify the source constant or implement wrapper logic to enforce different limits based on your use case.

### What types of execution errors can the self-healing mechanism fix?

The mechanism handles any runtime error that produces stderr output, including syntax errors, `NameError`, `ImportError`, and logic bugs causing non-zero exit codes. However, it cannot repair specification misunderstandings—if the LLM consistently misinterprets requirements, the healed code may still fail to meet user intent despite executing without runtime errors.

### How do I enable self-healing when using gpt-engineer programmatically?

Import `self_heal` from `gpt_engineer.tools.custom_steps` and pass it your `AI` instance, `execution_env`, `FilesDict`, and `Prompt` objects. Call the function instead of standard execution methods to activate the automatic repair loop within your Python application.