# Architecture

## System boundary

UltraPi runs inside the Pi Coding Agent extension process. It does not run as a separate server and does not own a model account. Pi supplies the session, tool surface, model registry, project trust signal, and interactive UI. UltraPi supplies routing, lifecycle control, local state, and the delegated-worker protocol.

```text
User
  -> Pi Coding Agent
       -> /ultra or ultra_dispatch
            -> UltraController
                 -> preflight + routing + budget/model policy
                 -> direct root work
                    or pi-agents delegated flow
                         -> scoped workers in an isolated worktree
                 -> verification + terminal result
                 -> sanitized telemetry and optional local raw vault
```

The extension entry point is `src/index.ts`. At startup it removes competing orchestration tools from the root tool list and exposes `ultra_dispatch` as the sole root orchestration entry point. A delegated child only enforces its selected profile; it does not become another orchestration root.

## Main components

| Area | Responsibility |
| --- | --- |
| `src/index.ts` | Installs commands, the `ultra_dispatch` tool, lifecycle hooks, model switching, and root-turn guards. |
| `src/controller/` | Classifies requests, routes topology, owns the run state machine, budgets, recovery, verification, and terminal presentation. |
| `src/backends/pi-agents-backend.ts` | Bridges Pi events to `pi-agents`, builds bounded flows, and runs delegated workers in subprocesses. |
| `src/workflows/` | Defines direct, scout, swarm, deep, repair, and War Room topology primitives. |
| `src/security/` | Enforces profile/model policy, worker scope, guarded commands, protected paths, and telemetry redaction. |
| `src/telemetry/` | Records append-only events, metrics, exports, and the rebuildable SQLite projection. |
| `src/experiments/` | Creates immutable config challengers, assigns reviewed experiments, and applies stop-loss rules. |

## Run lifecycle

1. **Receive and preflight.** The controller validates the task, obtains or infers a safe acceptance command for changes/fixes, reads context pressure, and checks the selected profile, model availability, worktree state, and budget admission.
2. **Classify and route.** `task-shape.ts` derives scope, risk, coupling, uncertainty, and independent units. `routing.ts` selects the smallest topology that fits. Hard-risk and repeated-failure gates can override a proposed lower topology.
3. **Constrain execution.** The controller creates an envelope with an explicit goal, path scope, exclusions, evidence target, privacy profile, output contract, and optional acceptance command.
4. **Execute.** Direct work stays with the root. Delegated work uses `pi-agents` in a worktree. Scouts are read-only; writers receive a bounded scope and a structured result contract.
5. **Verify and settle.** The controller records tool/model events, validates delegated output, runs the acceptance command when present, recognizes repeated failure fingerprints, and ends the run as completed, blocked, cancelled, failed, or budget-exhausted.
6. **Record.** Sanitized analytics are append-only JSONL. Detailed task text and traces, when enabled, are encrypted in a local raw vault and are excluded from exports.

## Execution topologies

### Direct

`direct` is for a known, local, low-risk task. No delegated worker is started. The root receives the routing result and, if supplied, the acceptance command that the controller will verify after the root turn.

### Scout

`scout` starts read-only evidence gathering along three fixed lenses: execution/data flow, tests and invariants, and the nearest working analogue. The controller fits the accepted facts into the root envelope. Material disagreement can escalate synthesis to the arbitration model.

### Swarm

`swarm` first gathers the same bounded evidence in parallel, then starts a single writer in a dedicated worktree — parallel reconnaissance, sequential writing. This deliberately avoids parallel writers editing the same repository: acceptance runs against one worktree, so two writers would produce a combination that nothing verified. `src/worktrees/parallel-writers.ts` implements the only variant that keeps that guarantee — disjoint scopes in separate worktrees, handed back unmerged — but no topology dispatches it. The writer receives only accepted/fitted facts and the explicit scope envelope.

### Deep

`deep` is the escalation path for high coupling, high risk, repeated failures, or a task that needs a more capable bounded writer. For a “first proven result” request, two read-only candidates race to reproduce the issue or find a working path; the first proven candidate feeds the writer.

### War Room

`warroom` is for live cross-agent dependency or intentional adversarial review. `lead`, `flow`, and `invariants` are read-only members — a fixed three, because each is a distinct lens rather than a seat. A member that posts a `request` or `blocker` summons a specialist for that gap, up to `warRoom.maxSpecialists` (default 2), bounded overall by `piAgentsBudgets.maxAgents`. They exchange one typed blackboard event at a time—hypothesis, evidence, challenge, confirmation, request, blocker, or controller-only decision—within member, round, and token caps. A writer is started only after the board converges or collapses.

War Room is disabled for automatic selection by default (`warRoom.autoEnabled` is `false`), so a live cross-agent dependency escalates to `deep` instead; an explicit `warroom` request is the only way in. An explicit request raises its own round cap from two to three, and the effective limit is the lower of that and `warRoom.maxRounds` — which defaults to `2`, so the third round needs `maxRounds` raised to `3`.

## Worker boundaries

Delegated work is bounded by both prompt contract and runtime controls:

- No recursive orchestration: `maxDepth` is `1` and child sessions do not receive root orchestration tools.
- Scouts only receive read-only tools and cannot edit files or run acceptance commands.
- Writers receive a declared path scope, a dedicated worktree, scoped read/write tools, and `guarded_bash` for limited commands.
- Every worker must return a validated structured result: status, facts, hypotheses, unknowns, verification evidence, and attribution for decisions/changes.
- The controller—not a worker—remains authoritative for acceptance verification and terminal state.

The project trust flag and extension permissions are not an operating-system sandbox. Use a container or VM for unattended writers when OS-level isolation matters.

## Routing and model policy

Routing favours direct execution for known low-risk local work. It chooses scouts for uncertainty, swarm for independent units without writer overlap, and deep for high risk, high coupling, repeated failures, disagreement, or cross-agent dependency. High context pressure blocks wide swarm fan-out.

Profiles are fail-closed:

- The private profile only permits the configured private model roster.
- The free profile requires a discovered compatible free-model roster; its launcher refuses to run when that roster is unavailable.
- A required model switch that cannot be resolved is recorded as blocked rather than silently using an unapproved model.

## Local state and telemetry

Runtime state lives below `<PI_CODING_AGENT_DIR>/ultrapi/`. It includes immutable config versions, a champion pointer, run ledgers, event JSONL, experiment records, and optional encrypted raw-vault records. The SQLite database is a rebuildable projection of sanitized analytics, not the source of truth.

The repository deliberately excludes all runtime state. See [Privacy](./PRIVACY.md) for export rules and [Configuration](./CONFIGURATION.md) for the config lifecycle.

## Deliberate limits

- The extension cannot prove a real provider, production system, or multi-user outcome without running that outcome.
- Budget/cost values are estimates from the configured price catalogue and Pi usage events.
- Routing regret and experiment recommendations are review inputs, not autonomous configuration changes.
- The extension reduces delegation risk; it does not make an untrusted repository safe to execute.
