# Client contract kit

What a client (the macOS toolbox, a web page, a script) needs to read the
pipeline's state and start or answer a run without a terminal conversation.
Nothing in here is a UI and nothing here runs on its own.

| File                       | What it is                                                                          |
| -------------------------- | ----------------------------------------------------------------------------------- |
| `manifest.json`            | Every surface: its CLI invocation, its HTTP route, its schema and version.          |
| `../schemas/*.schema.json` | The schemas. The kit points at them; it never copies them.                          |
| `types/index.d.ts`         | TypeScript declarations generated from those schemas by `build.mjs`.                |
| `fixtures/*.json`          | Real producer output for every state a client renders, generated by `build.mjs`.    |
| `frozen/toolbox.json`      | The fields the macOS toolbox decodes today, held by `test/toolbox-compat.test.mjs`. |
| `CHANGELOG.md`             | What changed in the contract, by contract version.                                  |

`node pipeline/contract/build.mjs --write` regenerates the types and fixtures;
`--check` fails on drift. `npm pack` runs `--write` first, so a published kit
always matches its schemas.

From the npm package: `@mmerterden/multi-agent-pipeline/contract` resolves to
the types (and to `manifest.json` at runtime), `/contract/*` to any kit file
and `/schemas/*` to a schema.

## Two carriers, one contract

Every surface is reachable two ways, and for the same input both print the
same bytes (`test/contract-parity.test.mjs`):

1. **CLI.** The scripts under `pipeline/scripts/` (installed: `~/.claude/scripts/`)
   print JSON on stdout. `--redact` drops every field a schema marks
   `x-sensitivity: local`.
2. **HTTP.** `contract-server.mjs`, started on demand with `/multi-agent:serve`
   or by the client itself. Routes are in `manifest.json`; `?redact=1` is
   `--redact`.

| Surface                                                                         | CLI                                                                                                   | HTTP                                                |
| ------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | --------------------------------------------------- |
| Runs                                                                            | `runs-index.mjs --json [--group G] [--redact]`                                                        | `GET /v1/runs`                                      |
| One run                                                                         | `runs-index.mjs --json --task-id ID`                                                                  | `GET /v1/runs/{id}`                                 |
| Commands                                                                        | `commands.mjs --json`                                                                                 | `GET /v1/commands`                                  |
| Skill catalog: commands, plugin skills, routines (local only)                   | `skill-catalog.mjs --json [--repo P]`                                                                 | `GET /v1/skills`                                    |
| Run questions                                                                   | `launch-request.mjs questions`                                                                        | `GET /v1/questions`                                 |
| Assigned issues                                                                 | `issues.mjs --json [--source S] [--project K] [--max N]`                                              | `GET /v1/issues`                                    |
| Worktrees                                                                       | `worktrees.mjs --json [--measure] [--redact]`                                                         | `GET /v1/worktrees`                                 |
| Launch shape                                                                    | `launch-request.mjs spec`                                                                             | `GET /v1/launch-spec`                               |
| Launch repositories                                                             | `launch-request.mjs repos [--redact] [--all]`                                                         | `GET /v1/repos[?all=1]`                             |
| Add a launch repository (two steps; the route also requires a git checkout)     | `launch-request.mjs register-repo <path>`                                                             | `POST /v1/repos`                                    |
| Remove a registered repository (two steps)                                      | -                                                                                                     | `DELETE /v1/repos/{id}`                             |
| Office jobs                                                                     | `job-launch.mjs list`                                                                                 | `GET /v1/jobs`                                      |
| Start an office job (two steps)                                                 | -                                                                                                     | `POST /v1/jobs`                                     |
| Start a run                                                                     | write the request file, then `launch-request.mjs plan FILE --repo P --session-id U`                   | `POST /v1/launch?repo=P`                            |
| Answer a question                                                               | `answer-question.mjs STATE --question Q --answer IDS`                                                 | `POST /v1/runs/{id}/answer`                         |
| A run's log                                                                     | `run-log.mjs ID [--tail N]` (1-2000, default 200)                                                     | `GET /v1/runs/{id}/log?tail=N`                      |
| Resume a run                                                                    | `launch-request.mjs resume --task-id ID --repo P --session-id U [--autopilot]`                        | `POST /v1/runs/{id}/resume`                         |
| Kill a run (two steps)                                                          | `run-kill.mjs preview ID`, then `run-kill.mjs apply ID`                                               | `POST /v1/runs/{id}/kill`                           |
| Garbage-collect (two steps)                                                     | `gc-plan.mjs preview [--scope S,...]`, then `gc-plan.mjs apply < items`                               | `POST /v1/gc`                                       |
| Autopilot status                                                                | `autopilot-control.mjs status`                                                                        | `GET /v1/autopilot`                                 |
| Autopilot off                                                                   | `autopilot-control.mjs off [--now]`                                                                   | `POST /v1/autopilot/off`                            |
| Autopilot on (two steps)                                                        | `autopilot-control.mjs on-preview --repo R...`, then `on --repo R... [--configure-only]`              | `POST /v1/autopilot/on`                             |
| Steer a run (two steps on the server)                                           | `steer-run.mjs STATE --text T`                                                                        | `POST /v1/runs/{id}/steer`                          |
| Agent activity                                                                  | `activity-snapshot.mjs --json`                                                                        | `GET /v1/activity`, `GET /v1/activity/stream` (SSE) |
| An agent's chat                                                                 | `activity-snapshot.mjs chat SESSION [AGENT] [--before N] [--limit N]`                                 | `GET /v1/agents/{sessionId}/{agentId}/chat`         |
| Cost ledger                                                                     | `office-ledger.mjs --json`                                                                            | `GET /v1/ledger`                                    |
| Machine resources                                                               | `system-status.mjs --json`                                                                            | `GET /v1/system`                                    |
| Key cabinet (names and verdicts, never values)                                  | `office-credentials.mjs --json [--probe]`                                                             | `GET /v1/credentials`                               |
| Institutional memory                                                            | `office-memory.mjs --json`                                                                            | `GET /v1/memory`                                    |
| Server room: sessions, today per model, health lights (local only)              | `office-server-room.mjs --json`                                                                       | `GET /v1/server-room`                               |
| MCP health: calls, failures and last failure per server and tool (local only)  | `mcp-health.mjs --json`                                                                               | `GET /v1/mcp-health`                                |
| Memory archive: decisions, security notes, learnings, graph report (local only) | `office-archive.mjs --json`                                                                           | `GET /v1/archive`                                   |
| Prune old run logs (two steps)                                                  | `office-prune.mjs preview\|apply N --json`                                                            | `POST /v1/prune-logs`                               |
| Disk space: measure, then the ticked categories (two steps, local only)         | `disk-cleaner.mjs --dry-run\|--apply --json [--only=ids]`                                             | `POST /v1/disk-clean`                               |
| Office settings                                                                 | `office-settings.mjs --json`                                                                          | `GET /v1/settings`                                  |
| Change one setting (two steps)                                                  | `office-settings.mjs set SETTING VALUE --json`                                                        | `POST /v1/settings`                                 |
| What a run produced                                                             | `run-results.mjs ID --json`                                                                           | `GET /v1/runs/{id}/results`                         |
| One screenshot                                                                  | `run-results.mjs ID --evidence NAME`                                                                  | `GET /v1/runs/{id}/evidence/{name}`                 |
| Post a review verdict (two steps)                                               | `work-items.mjs verdict ID [--post]`                                                                  | `POST /v1/runs/{id}/review-verdict`                 |
| An issue's maturity                                                             | `work-items.mjs maturity KEY`                                                                         | `GET /v1/issues/{key}/maturity`                     |
| Open pull requests                                                              | `work-items.mjs prs`                                                                                  | `GET /v1/prs`                                       |
| How far each open pull request reaches in its repository's graph                | `work-items.mjs reach`                                                                                | `GET /v1/prs/reach`                                 |
| Toolkit MCP tools                                                               | `toolkit-tools.mjs list`                                                                              | `GET /v1/tools`                                     |
| Call an allowed toolkit tool (read-only, no location argument)                  | `toolkit-tools.mjs call NAME JSON`                                                                    | `POST /v1/tools/{name}/call`                        |
| A Confluence page, a Crashlytics issue, a Figma frame                           | `service-read.mjs confluence\|crashlytics\|figma ...`                                                 | `GET /v1/services/{confluence,crashlytics,figma}`   |
| Pending host permission prompts                                                 | (none can be read yet)                                                                                | `GET /v1/permissions`                               |
| Routines                                                                        | `routine-registry.mjs list --json`                                                                    | `GET /v1/routines`                                  |
| Remove a routine (two steps)                                                    | `routine-registry.mjs remove --name N`                                                                | `DELETE /v1/routines/{name}`                        |
| Routines other members shared (local only)                                      | `routine-share.mjs browse`                                                                            | `GET /v1/routines/shared`                           |
| One shared routine with its body (local only)                                   | `routine-share.mjs fetch --id ID`                                                                     | `GET /v1/routines/shared/{id}`                      |
| Import a shared routine (two steps)                                             | `routine-share.mjs import --id ID --sha S [--as N]`                                                   | `POST /v1/routines/shared/{id}/import`              |
| A repo's stacks                                                                 | `stack-toggle.mjs status --repo P --json`                                                             | `GET /v1/stack?repo=R`                              |
| Set a repo's stacks (two steps)                                                 | `stack-toggle.mjs set --repo P STACK... --json`                                                       | `POST /v1/stack`                                    |

Every surface in `manifest.json` carries `remote` (the scope a remote carrier
would require: `read`, `answer`, `launch`, or `local-only` for anything that
widens what runs on this machine (autopilot on, stack, routine removal and
import, kill, gc, prune, settings) and for a read that stays on this machine for privacy
(credentials, memory, settings)) and `risk` (the confirmation tier: `read`, `low`, `high`). Locally the
bearer token is the only credential; nothing enforces the tags yet. They are
there so a later carrier reuses these routes without redefining them.

Starting a run is the client's act. `POST /v1/launch` validates the
request, writes it (0600) and returns the argv, environment and working
directory from `launch.json`; spawn the argv without a shell. The office panel
is a client that starts its own: `POST /v1/jobs` (two steps, `local-only`)
starts a job from `schemas/office-jobs.json` in the background after the
unattended profile, workspace trust and sandbox checks. Besides that the only
`claude` the server runs is `claude stop`, for a kill. `launch.json` is marked `verified: false` until a live launch trial, so
treat the shape as provisional.

The run starts with no permission prompts, so its input is held to a shape: a
Jira key, a GitHub issue URL, `repo#N`, `#N`, or a Jira URL on the configured
host passes as it is; free text becomes one quoted argument; a
newline, a control character, a leading `-` or a first token that is a pipeline
op or mode keyword is refused (`launch-request.schema.json`). `repo` must be a
configured autopilot repo or one registered with
`launch-request.mjs register-repo <path>`, else `403 repo-not-allowed`.

Every plan starts claude with `--settings` naming the unattended permission
profile (`~/.claude/multi-agent-unattended.settings.json`). The profile is
opt-in and only the installer writes it, so without it `POST /v1/launch` and
`POST /v1/runs/{id}/resume` answer `409 unattended-profile-missing`, whose
`remedy` names the install command; the server never writes the file. The
repository must also be one Claude Code trusts: when its config
(`~/.claude.json`, `projects[<repo root>].hasTrustDialogAccepted`) says it is
not, both routes answer `409 workspace-not-trusted`, whose `remedy` is to open
Claude Code once there and accept the trust prompt (`cd <repo> && claude`).
Trust of a parent folder does not count. A config that cannot be read
concludes nothing and the launch proceeds; the server never writes it. The
prompt is claude's positional argument: `--bg` starts a background session,
prints its id and returns, and refuses `--print`.

`mode: "background"` with `kind: "development"` or `"analysis"` starts
`/multi-agent <input>` or `/multi-agent:analysis <input>` unattended without
autopilot: a picker the request did not answer is not defaulted, the run parks
on it as a `pendingQuestion`, and the client answers it like any other.
Resuming is the client's act too: `POST /v1/runs/{id}/resume` returns the plan
(`mode: "resume"`, no request file) for a run recorded under the unattended log
root, `409 not-resumable` for any other, a finished or a killed one, and `409
run-active` while its session runs.

Kill, gc, autopilot on, a stack change and a shared-routine import take two
requests (a routine removal takes its token as `?confirm=`). The first (no
`confirmToken`) returns the preview with `confirmToken` and `expiresAt`; the
second sends the token back and acts on exactly what was previewed. A token is
single use, lives 120 seconds in the server's memory only, and is bound to the
route and the run: `409 confirm-expired` for an unknown, used or expired one,
`409 confirm-mismatch` for one minted elsewhere. A kill never deletes the
remote branch or the run's logs. Turning autopilot on stays a terminal command,
because it picks repositories with the user.

A shared-routine import previews the full body, its `sha256` and the local
name it would get (`targetName`), with the description, descriptionTr and
argument hint exactly as they become frontmatter and the payload `digest`
over all of them; the confirmation sends `confirmToken`, that `sha256` and
that `digest` back, and nothing else. A different `sha256` or `digest` is
`409 confirm-mismatch`, a routine that changed on the sharing site since the
preview (any of those fields) is `409 state-moved`, and a name a routine or any existing command directory
already has is
`409 name-taken`, answered by previewing again with `as`. The frontmatter is
rebuilt on this machine and the routine is never run. An unattended server
refuses both steps with `409 unattended-refused`. The usage token stays with
`routine-share.mjs`; the server only reads what it prints.

To answer, read `pendingQuestion` from the run (present when `waitingFor` is
`question`) and send its `id` with one or more of its `options[].id`. Anything
else is refused, and a run that has moved to another question refuses an
answer to the old one.

## Talking to the server

- It listens on `127.0.0.1` only, on the port its ready line names, and refuses
  any other `--host`.
- The ready line (stdout, one JSON object) names `tokenFile`, a 0600 file under
  `~/.claude/logs/multi-agent/contract-server/` holding the token. A client
  that spawned the server can pass `--print-token` to get it on the ready line.
- Every request sends `Authorization: Bearer <token>` and a `Host` of
  `127.0.0.1:<port>` or `localhost:<port>`.
- A browser page is allowed only from the server's own origin (the optional
  panel at `GET /office`) or an origin passed with `--allow-origin`; CORS is
  off without one. A write (POST, DELETE) and the chat route accept no Origin
  but the server's own, even an allowed one. A request carrying an `Origin` is
  always served redacted.
- The token is read from the `Authorization` header only, never from a cookie
  or a query parameter.
- `GET /office` serves the panel page (`MA_OFFICE_PAGE`, else
  `prefs.global.office.page`, else the installed `office/index.html` beside the
  package) without a token, with a per-response CSP nonce, and is 404 when no
  page exists. The page never sees the token in a URL: `POST /office/code`
  (bearer, no Origin) mints a code valid for 10 seconds and one use, the page
  is opened with it in the fragment, and trades it at `POST /office/exchange`
  (own Origin only, no bearer); a used, expired or unknown code is 401. The
  exchange also returns `resume` and `resumeExpiresAt`: a key the page keeps
  in its tab's sessionStorage and posts back as `{resume}` to the same route
  after a reload. It buys the token once, the answer carries its replacement,
  and it lapses after 12 hours or when the server stops; a used, expired or
  unknown key is 401. The server keeps at most 16 live keys and evicts the
  oldest past that. Browsers persist sessionStorage to disk for tab restore,
  and duplicating a tab copies the key, so the second copy to reload is
  signed out.
  `GET /office/assets/<name>.png` serves the page's sprites, also without a
  token: a plain file name, a PNG of at most 256 KiB directly in the assets
  directory beside the page, and 404 for anything else. `GET /favicon.ico`
  answers an empty 204 without a token, since browsers request it on their own.
- Every write route appends one line (who, route, step, status; never a body
  or token) to `~/.claude/logs/multi-agent/office-actions.jsonl`.
- Bodies are JSON, at most 64 KiB, and must satisfy the route's schema.
- Errors follow `contract-error.schema.json`; switch on `error`, never on
  `message`.
- Service reads, the work list, the review verdict and autopilot control run
  in child processes and never block other routes. A second write, or a
  second service read, while the same one runs is 429 `busy`; a read whose
  answer is the same for every caller (`GET /v1/prs`, `GET /v1/autopilot`,
  `GET /v1/issues/{key}/maturity`) is answered from the run already in
  flight instead.
- The server exits after 15 idle minutes (`--idle-minutes`), after 8 hours in
  any case (`--max-hours`, an open event stream does not extend it) or on
  SIGTERM. It is never a service; start it when you need it.

A client that relays anything off this machine uses `redact=1` (or
`--redact`) for every read.

## Versioning and breaking changes

The kit carries one `contractVersion` (`manifest.json`, and the
`X-Contract-Version` header on every response); each surface also stamps its
own version in its output.

- **Adding** a field, a surface, a query parameter or an error code is a
  **minor** bump. Decoders ignore keys they do not know, so nothing breaks.
- **Removing** or renaming a field, changing a field's type, narrowing what a
  request accepts, or changing what an error code means is a **major** bump.
  `frozen/toolbox.json` makes the toolbox's fields fail a test before such a
  change can land by accident.
- **After a major bump the previous major stays served for one minor**,
  selected with `?v=<major>` on any route. The minor after that removes it.
  `?v=` with a major the server does not serve, or one not written as a plain
  decimal (`01`, `+1`, `1.0`, empty), is a 400 `unsupported-version` whose
  `supported` lists the ones it does. Without `?v=` the current major is
  served.
- Every version change gets a section in `CHANGELOG.md` saying what a client
  has to do.
