# pi-amq

A [pi](https://github.com/badlogic/pi-mono) extension that uses
[AMQ](https://github.com/avivsinai/agent-message-queue) as its durable
messaging data plane, plus a worker runtime for model-driven multi-agent
coordination.

- **Transport**: crash-safe agent-to-agent mail (Maildir, receipts, DLQ) made
  native inside a pi session — priority-aware context injection, per-envelope
  channel guidance, receiver lease, send-only delegates.
- **Worker runtime**: atomic capabilities (`spawn_worker`, `list_workers`,
  `collect`, `cancel`, `steer`, `revise_contract`) with hard governance
  (budgets, leases, Gate facts, append-only ledger). Coordination strategy
  belongs to the model; patterns ship as advisory prompt guidance, not engine
  primitives. Explicit lifecycle maintenance is available through the
  dry-run-first `cleanup_runs` tool and `/pi-amq-cleanup` command; read-only
  `workflow_doctor` and `/pi-amq-doctor` report ledger, process, lease, session,
  and disk faults without executing repairs. Every run also owns one private
  shared artifact directory that is injected into each worker contract for
  exact-path file handoffs. RPC contracts may also carry bounded directional
  `message_worker:<workerId-or-role>` grants. The child-only peer tool routes
  through the supervisor, waits for the recipient inference boundary, and
  records one correlated audit fact in both endpoint projections without
  adding a driver orchestration verb. RPC children also receive the built-in
  `wait_for_input` fact tool: `{reason, correlation}` is generation-fenced in
  the Ledger, and only exact-correlated steer, revision, or peer delivery wakes
  `blocked`; prose, silence, and stall observations do not.

Use `/pi-amq-guide [topic]` in pi, or the model-visible `guide` tool, for bounded
version-matched excerpts covering `overview`, `tools`, `contracts`, `gate`,
`budgets`, `fleetview`, `mail`, and `troubleshooting`.

Design: [docs/design.md](docs/design.md) — the authoritative contract for
implementation. Every debated decision carries a `(debate: ...)` provenance
note. [docs/contracts/](docs/contracts) maps that contract to owners,
implementation files, and fault-sensitive tests
([transport](docs/contracts/transport.md),
[worker runtime](docs/contracts/worker-runtime.md),
[operations](docs/contracts/operations.md)); the maps add no rules, and any
conflict resolves to `docs/design.md`. Findings that were investigated and
deliberately not acted on, with their reopen conditions, are recorded in
[docs/contracts/deferred-findings.md](docs/contracts/deferred-findings.md).

## Principle

> Agent owns strategy; harness owns truth.

The extension keeps messages durable and invariants enforced. Everything else
is the model's business.

## Status

The implemented transport slice now includes verified existing bindings,
fenced receiver lease, recoverable inbox pump, priority delivery, typed tools,
operator commands, guidance, presence, and a transport-side FleetView
projection, including confirmed first-run roster bootstrap. The governed
WorkerRuntime W1-W4 now includes the isolated run ledger,
generation-fenced supervisor and worker-session leases, exact send-only child
launch contracts, supervised JSON/RPC pi subprocesses, hard runtime budgets,
process-group cancellation, restart reconciliation without automatic replay,
six typed model-visible worker tools, worker and run Gate tables, immutable contract
revision delivery at inference boundaries, model-catalog guidance, and visible
running-only stall facts. Old terminal run state can be inspected and removed
only through explicit, audited, supervisor-fenced cleanup. The child JSONL protocol has a structured 4 MiB
per-line ceiling, a 128 KiB stderr tail, split-UTF-8/final-line tolerance, and
uses `agent_settled` as the next-inference boundary. FleetView now renders authoritative worker rows and
live session tails, supports generation-fenced RPC steer and `x,x` cancellation,
and blocks fresh-session replacement while workers are active, ambiguous, or
detached. Successful sibling completions are grouped into quiet UI notices;
failed, paused, and ambiguous workers notify immediately and individually. Run
and worker budgets use explicit `limited(value)`/`unlimited`
declarations; unlimited run dimensions require TUI confirmation and are never
inherited by worker contracts. Worker tools remain available when AMQ transport
is dormant. Full worker-session takeover remains a later phase. The package
also ships an advisory `coordination-patterns` skill for existing AMQ peers and
local supervised workers.

The TUI launch gate defaults `confirm_spawns` to `multi-worker-only`: concurrent
multi-worker proposals receive one editable preview before any worker intent is
ledgered, while a single worker proceeds directly. Accepted human edits are
persisted as contract provenance; Esc and required headless confirmation are
mutation-free.

Automatic fresh-session delivery requires pi >= 0.84.2 and runs end to end:
authorized requests replace the current session via a hidden command dispatch,
`ctx.waitForIdle()`/`ctx.newSession`, and a verified kickoff projection. Pi
persists a fresh session's file lazily, so the projection may briefly be
visible only in-memory; the journal commits the target session immediately and
records `injected` once the projection is disk-visible. A cancelled
replacement, a command dispatch that never completes, or a kickoff missing
from both the in-memory session and disk leaves the request pending with
visible `/amq ingest` guidance instead; see
[§17.1](docs/design.md#171-fresh-session-automation-compatibility-amendment).

## Verification

Two suites, one boundary.

- `npm test` is the **repository suite**. It compiles `test/**/*.ts` and runs
  `.test-dist/test/*.test.js` against the source tree in this checkout.
- `npm run test:package` is the **consumer-artifact gate**. It packs the real
  npm tarball, extracts it into a staged `node_modules/pi-amq` tree, and loads
  that extracted copy through the stock pi `--extension` seam, asserting the
  registered tool surface, that `guide` resolves `docs/operator-guide.md` from
  the extracted package root, and that the packaged manifest ships the documents
  it promises.

The pi-amq extension under test is loaded only from the extracted tarball, so a
path missing from `package.json#files` fails the gate. The repository still
supplies the test-only probe extension and the already-resolved dependency tree
the staged package links against. Staging extracts the tarball; it does not run
npm's installer, so npm's own resolution, lifecycle scripts, and peer-dependency
handling are out of scope. Every probe runs with `HOME` and
`PI_CODING_AGENT_DIR` inside its staged workspace, so the gate never touches the
caller's `~/.pi` runtime state.

The gate is fail-closed: it needs a stock `pi` binary on `PATH` or at
`PI_AMQ_TEST_PI_BINARY`, and without one it **fails** with a missing-binary
diagnostic instead of reporting success on skipped cases. The manifest case does
not need `pi` and stays independently runnable.

Neither suite ships. `package.json#files` omits `test` and `tsconfig.test.json`
on purpose: a consumer installs the runtime surface, not the harness that
verifies it. `test:package` is the check that keeps that omission honest,
because it only ever sees what a consumer receives.

The reproducible live AMQ flow is in
[`scripts/demo-two-terminal.sh`](scripts/demo-two-terminal.sh), with a
normalized transcript in [`docs/demo-transcript.md`](docs/demo-transcript.md).
The fault-sensitive zero-AMQ worker-team demonstration is case 37 in
[`test/workflow-run-store.test.ts`](test/workflow-run-store.test.ts).
