# How LoopX Handles Peer-Agent Task Coordination and Handoff: A Deep Dive into Multi-Agent Orchestration

> Discover how LoopX orchestrates multi-agent systems with peer-agent task coordination and structured handoffs. Learn about its explicit gates, budgets, and audit trails for seamless collaboration.

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

---

**LoopX enables multi-agent collaboration through a goal-level peer-task coordination policy and a structured handoff subsystem with explicit gates, budgets, and audit trails.**

LoopX is an open-source orchestration framework that allows multiple peer agents to collaborate on shared goals. Its architecture separates **coordination policy** (who leads) from **handoff mechanics** (how control transfers), giving operators fine-grained control over distributed task execution. According to the LoopX source code in `huangruiteng/loopx`, these two subsystems work together to route tasks to peer lanes safely and observably.

---

## Peer-Agent Task Coordination in LoopX

LoopX implements peer-agent task coordination through goal-level configuration that designates a **coordinator agent** for specific objectives. This policy-driven approach lets runtime schedulers decide when to route tasks away from the default host lane.

### Declaring a Coordinator in Goal Configuration

A goal declares its coordination policy via YAML front-matter. The `peer_task_coordination` dictionary specifies which registered agent has coordination authority:

```yaml

# goal/my-goal-id.yaml

peer_task_coordination:
  coordinator_agent_id: peer-agent-42  # must exist in normalize_registered_agents

```

The value assigned to `coordinator_agent_id` must correspond to an agent previously registered through the system's agent registry.

### Normalization and Validation in orchestration.py

The function `compact_peer_task_coordination_policy` in [`loopx/orchestration.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/orchestration.py) processes this policy at load time:

- Extracts `coordinator_agent_id` from the goal's `peer_task_coordination` dictionary
- Validates the ID against `normalize_registered_agents`
- Returns `None` if validation fails, disabling peer coordination
- Sets `"enabled": True` when a valid coordinator exists

This enabled flag signals the runtime scheduler that tasks for this goal may be routed to peer lanes instead of remaining on the host lane.

### Runtime Capability Admission

Even with a valid coordinator, actual task routing depends on **per-turn capability admission**. The scheduler evaluates:

- The goal's orchestration mode
- Allowed domains for the current turn
- Any active **explore-harness** settings

Only when all admission criteria pass does a peer lane receive task delivery rights.

### Status Server API for Coordinator Visibility

The status server exposes coordinator state through REST endpoints defined in [`loopx/status_server.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/status_server.py). Two fields control external access:

| Field | Purpose |
|-------|---------|
| `peer_task_coordinator` | Query current coordinator agent ID |
| `clear_peer_task_coordinator` | Reset/clear coordinator assignment |

These endpoints enable monitoring tools and external orchestrators to observe or intervene in running goal coordination.

---

## Handoff Subsystem: Safe Transfer of Control

When responsibility must move between agents, LoopX uses a **structured handoff workflow** composed of discrete todo types. This design separates policy definition from enforcement and auditing.

### Core Handoff Components

LoopX defines four primary handoff primitives across `loopx/control_plane/todos/` and `loopx/control_plane/handoff/`:

**`handoff_mode`** ([`handoff_mode.py`](https://github.com/huangruiteng/loopx/blob/main/handoff_mode.py))

Defines the policy governing how handoffs may occur. Modes include:
- **Soft claim**: Coordinator requests control without exclusive lease
- **Hard lease**: Exclusive control with lease enforcement
- **Legacy**: Backward-compatible behavior for older goals

**`handoff_gate`** ([`handoff_gate.py`](https://github.com/huangruiteng/loopx/blob/main/handoff_gate.py))

Acts as a runtime checkpoint that blocks or permits handoffs based on:
- Current `handoff_mode` setting
- Active leases held by other agents
- Pending handoff requests in queue

**`handoff_note`** ([`handoff_note.py`](https://github.com/huangruiteng/loopx/blob/main/handoff_note.py))

Stores immutable metadata for each handoff request:
- Unique handoff ID
- Authoring agent
- Rationale/justification text

**`handoff_runs`** ([`handoff_runs.py`](https://github.com/huangruiteng/loopx/blob/main/handoff_runs.py))

Maintains execution history across turns, recording:
- When handoffs were observed
- Application timestamps
- Rejection reasons and codes

### Handoff Budget Protection

The [`loopx/handoff_budget.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/handoff_budget.py) module enforces rate limits on handoffs per goal per time window. This prevents **thrashing scenarios** where rapid agent switching destabilizes execution. Budget consumption is checked before any gate opens.

### Per-Turn Handoff Decision Flow

Each scheduling turn executes this validation sequence:

1. Retrieve current `handoff_mode` for the goal
2. Check `handoff_gate` status against active leases
3. Verify remaining budget in `handoff_budget`
4. If all checks pass, allow coordinator to claim task
5. Create `handoff_note` with request metadata
6. Log execution to `handoff_runs` for audit trail

---

## Practical Examples: Managing Peer Coordination and Handoffs

### Querying and Resetting the Coordinator

```python
import requests

# Query current coordinator

resp = requests.get(
    "http://localhost:8000/api/v1/goal/my-goal-id",
    params={"fields": "peer_task_coordinator"}
)
print(resp.json()["peer_task_coordinator"])

# Output: "peer-agent-42"

# Clear coordinator (disables peer coordination for this goal)

requests.post(
    "http://localhost:8000/api/v1/goal/my-goal-id",
    json={"clear_peer_task_coordinator": True}
)

```

### Changing Handoff Mode via CLI

The [`loopx/cli_commands/handoff_mode.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/cli_commands/handoff_mode.py) module provides command-line control:

```bash

# Enable hard lease mode for exclusive coordinator control

loopx handoff-mode set --goal-id my-goal-id --mode hard_lease

```

This command updates the goal's `handoff_mode` field and automatically creates a `handoff_note` documenting the policy change.

### Inspecting Handoff History

```python
import json
from pathlib import Path

# Load persistent handoff run records

runs_path = Path("state/goal/my-goal-id/handoff_runs.json")
runs = json.load(runs_path.open())

# Examine latest handoff execution

print(runs[-1])

# Shows: observation time, application status, rejection details if blocked

```

---

## Key Source Files for Peer-Agent Coordination

| Component | Location |
|-----------|----------|
| Orchestration and policy normalization | [`loopx/orchestration.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/orchestration.py) |
| Status server API endpoints | [`loopx/status_server.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/status_server.py) |
| Handoff mode definitions | [`loopx/control_plane/todos/handoff_mode.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/todos/handoff_mode.py) |
| Handoff gate enforcement | [`loopx/control_plane/todos/handoff_gate.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/todos/handoff_gate.py) |
| Handoff note schema | [`loopx/control_plane/todos/handoff_note.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/todos/handoff_note.py) |
| Execution history tracking | [`loopx/control_plane/handoff/handoff_runs.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/handoff/handoff_runs.py) |
| Budget enforcement | [`loopx/handoff_budget.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/handoff_budget.py) |
| CLI command implementation | [`loopx/cli_commands/handoff_mode.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/cli_commands/handoff_mode.py) |

---

## Summary

- **Peer-agent task coordination** in LoopX uses goal-level YAML configuration validated by `compact_peer_task_coordination_policy`, with runtime exposure through the status server API
- **Handoff safety** depends on four coordinated primitives: `handoff_mode` (policy), `handoff_gate` (enforcement), `handoff_note` (provenance), and `handoff_runs` (audit history)
- **Rate protection** via [`handoff_budget.py`](https://github.com/huangruiteng/loopx/blob/main/handoff_budget.py) prevents coordination thrashing
- **Declarative controls** allow operators to query, modify, and reset coordinator state without restarting goals
- **Complete traceability** ensures every handoff decision is observable for debugging and compliance

---

## Frequently Asked Questions

### How does LoopX validate that a coordinator agent is legitimate?

LoopX validates coordinator eligibility through `normalize_registered_agents` in [`loopx/orchestration.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/orchestration.py). The `compact_peer_task_coordination_policy` function returns `None` if the `coordinator_agent_id` from the goal's `peer_task_coordination` dictionary does not match a registered agent, effectively disabling peer coordination for that goal.

### What happens when a handoff exceeds the budget limit?

The [`handoff_budget.py`](https://github.com/huangruiteng/loopx/blob/main/handoff_budget.py) module tracks consumption per goal per time window. When a handoff would exceed the configured limit, the `handoff_gate` remains closed regardless of mode settings, and the handoff is rejected with a budget-exceeded status recorded in `handoff_runs`.

### Can multiple peers coordinate the same goal simultaneously?

No. LoopX enforces **single-coordinator semantics**: only one `coordinator_agent_id` may be active per goal. External tools can change coordinators atomically via the status server API, but the runtime treats handoffs as exclusive transfers rather than shared control.

### Where does LoopX store handoff execution history?

Handoff run records persist to `state/goal/<goal-id>/handoff_runs.json` via the [`handoff_runs.py`](https://github.com/huangruiteng/loopx/blob/main/handoff_runs.py) module. Each entry captures observation timestamps, application outcomes, and rejection rationales, enabling post-hoc analysis of coordination decisions across a goal's lifetime.