# How LoopX Handles Goal Recovery and State Repair: A Technical Deep Dive

> Discover how LoopX handles goal recovery and state repair. Learn about its three-layer system using turn envelopes, repair hints, and the loopx-self-repair skill for deterministic fixes.

- Repository: [huangruiteng/loopx](https://github.com/huangruiteng/loopx)
- Tags: deep-dive
- Published: 2026-08-07

---

**LoopX treats every autonomous turn as a bounded transaction that concludes with either validated progress, repair required, or re-plan required, using a three-layer system involving turn envelopes, repair hints, and the loopx-self-repair skill to deterministically fix stale projections and capability drift.**

The huangruiteng/loopx repository implements a sophisticated framework for autonomous agent execution where **goal recovery and state repair** are first-class architectural concerns. Rather than simply aborting failed operations, LoopX wraps every turn within a transactional envelope capable of self-diagnosing inconsistencies and triggering targeted remediation.

## The Three-Layer Recovery Architecture

LoopX organizes its recovery mechanism into three tightly-coupled layers that progress from detection to remediation.

### Turn Execution Layer and Transactional Envelopes

At the core of **LoopX goal recovery** lies the turn execution layer defined in [`loopx/turn_execution.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/turn_execution.py). Each autonomous turn operates within a **turn envelope** containing the goal ID, current projection of the goal state, and critical flags such as `self_repair_allowed`.

When validation fails due to stale projections or capability drift, the envelope records `recovery_kind = "repair_required"`. This deterministic classification—complemented by `"replan_required"` or `"validated_progress"`—enables the system to categorize every outcome without ambiguity. As demonstrated in [`tests/test_loopx_turn_transaction.py`](https://github.com/huangruiteng/loopx/blob/main/tests/test_loopx_turn_transaction.py) (lines 248-259), the payload structure explicitly sets this field when forward progress becomes impossible.

### Self-Repair Hint Generation

Following a `repair_required` classification, the **control-plane** generates structured repair hints that specify both the problem and solution mechanism. The framework provides specialized hint factories for different failure modes:

- **`build_runtime_capability_user_gate_repair_hint`**: Handles capability-gate violations, producing hints with triggers like `runtime_capability_user_gate_overreach` (see [`tests/control_plane/test_user_gate_lane_progress.py`](https://github.com/huangruiteng/loopx/blob/main/tests/control_plane/test_user_gate_lane_progress.py) lines 286-293).
- **`build_required_decision_scope_repair_hint`**: Repairs projection drift in the decision-scope layer, referenced in [`tests/control_plane/test_decision_scope_consistency.py`](https://github.com/huangruiteng/loopx/blob/main/tests/control_plane/test_decision_scope_consistency.py) (lines 104-119).

Each hint contains a `trigger` identifying the root cause, an `effective_action` (such as `todo_decision_scope_projection_repair`), and an `allowed` boolean indicating whether autonomous repair is permitted.

### Self-Repair Execution via the LoopX-Self-Repair Skill

The [`skills/loopx-self-repair/SKILL.md`](https://github.com/huangruiteng/loopx/blob/main/skills/loopx-self-repair/SKILL.md) implements the final recovery layer, consuming repair hints to materialize missing or stale projections. This skill guarantees **exact-once semantics** by tracking effects through the envelope's `effects` dictionary.

According to [`tests/test_loopx_turn_transaction.py`](https://github.com/huangruiteng/loopx/blob/main/tests/test_loopx_turn_transaction.py) (lines 276-277), the system only commits a repaired turn when `state_written = True` and quota consumption has been recorded, preventing duplicate state changes during recovery.

## Key Recovery Mechanisms in LoopX

Several architectural features ensure reliable **state repair** across distributed execution contexts:

- **Deterministic recovery kind**: Every turn envelope includes the `recovery_kind` field, providing unambiguous classification of turn outcomes as shown in [`tests/test_loopx_turn_executor.py`](https://github.com/huangruiteng/loopx/blob/main/tests/test_loopx_turn_executor.py) (line 369).

- **Self-repair gating**: The boolean `self_repair_allowed` flag (defaulting to `True` per [`tests/test_turn_envelope.py`](https://github.com/huangruiteng/loopx/blob/main/tests/test_turn_envelope.py) lines 61-63) allows per-goal disabling of autonomous fixes when manual intervention is preferred.

- **Repair delta contract**: Successful repairs attach a `repair_delta_contract` to the goal's state file, enabling downstream components to reason about changes. This contract follows the schema `{"schema_version": "repair_delta_contract_v0", "delta_present": True}` as illustrated in [`tests/test_state_refresh_projections.py`](https://github.com/huangruiteng/loopx/blob/main/tests/test_state_refresh_projections.py) (lines 7-8).

- **Capability-aware hints**: Repair hints include the originating capability in the `trigger` field, ensuring the repair step targets the correct subsystem rather than applying blanket fixes.

- **Idempotent effect tracking**: The `effects` dictionary tracks `state_written` and `quota_spent` status, ensuring repairs execute exactly once even under retry scenarios.

## Practical Implementation Examples

The following patterns demonstrate how to implement **LoopX goal recovery** in production code:

```python

# Building a turn envelope that signals repair requirements

envelope = {
    "goal_id": "my-goal",
    "self_repair_allowed": True,
    "recovery_kind": "repair_required",
    "effects": {"state_written": False, "quota_spent": False},
}

# Generating a repair hint from the control-plane

repair_hint = loopx.control_plane.repair_hint_factory(envelope)

```

When processing capability violations or projection drift, the hint factory creates structured repair instructions:

```python

# Example repair hint for decision-scope projection drift

repair_hint = {
    "trigger": "runtime_capability_user_gate_overreach",
    "effective_action": "todo_decision_scope_projection_repair",
    "allowed": True
}

```

The self-repair skill applies these hints idempotently:

```python
def apply_self_repair(hint):
    """Apply repair hints with exact-once guarantees."""
    if hint["effective_action"] == "todo_decision_scope_projection_repair":
        # Recompute and update the missing projection

        project_state["decision_scope"] = recompute_scope(...)
        # Mark repair as consumed to prevent reapplication

        hint["allowed"] = False
    return hint

# Re-execute the goal with repaired state

loopx.run_goal("my-goal", envelope=envelope)

```

## Summary

LoopX implements **goal recovery and state repair** through a transactional, three-layer architecture:

- **Turn envelopes** in [`loopx/turn_execution.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/turn_execution.py) encapsulate execution state with explicit `recovery_kind` classification and `self_repair_allowed` gating.
- **Repair hints** generated by the control-plane provide structured, capability-aware instructions for fixing specific failure modes like projection drift or capability-gate violations.
- **Exact-once semantics** via the `loopx-self-repair` skill ensure state changes occur only once, tracked through `effects` monitoring and `repair_delta_contract` attachments.

## Frequently Asked Questions

### What triggers a "repair_required" status in LoopX?

A turn receives `recovery_kind = "repair_required"` when the turn envelope detects that the current projection is stale or a capability has drifted from its expected state. This classification occurs in [`loopx/turn_execution.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/turn_execution.py) when validation determines that forward progress is impossible without first correcting the inconsistent state, as tested in [`tests/test_loopx_turn_transaction.py`](https://github.com/huangruiteng/loopx/blob/main/tests/test_loopx_turn_transaction.py).

### How does LoopX prevent duplicate state changes during recovery?

The framework implements **exact-once semantics** through the `effects` dictionary tracked in the turn envelope. Before committing a repair, the system verifies that `state_written` is `True` and `quota_spent` has been recorded, as validated in [`tests/test_loopx_turn_transaction.py`](https://github.com/huangruiteng/loopx/blob/main/tests/test_loopx_turn_transaction.py) (lines 276-277). This idempotent tracking prevents duplicate writes even if the repair operation retries due to network timeouts.

### Can autonomous repair be disabled for specific goals?

Yes. The `self_repair_allowed` boolean flag in the turn envelope controls whether the control-plane may automatically generate and apply repair hints. Setting this to `False` forces manual intervention, allowing operators to review failures before attempting state fixes, as demonstrated in [`tests/test_turn_envelope.py`](https://github.com/huangruiteng/loopx/blob/main/tests/test_turn_envelope.py) (lines 61-63).

### What information does a repair delta contract contain?

The `repair_delta_contract` attached after successful repairs includes a `schema_version` (typically `"repair_delta_contract_v0"`) and a `delta_present` boolean. This metadata, shown in [`tests/test_state_refresh_projections.py`](https://github.com/huangruiteng/loopx/blob/main/tests/test_state_refresh_projections.py), enables downstream components to understand what changed during recovery without reprocessing the entire state history.