> For the complete documentation index, see [llms.txt](https://faction-os.gitbook.io/faction-os-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://faction-os.gitbook.io/faction-os-docs/docs/api/event-api-hook-contracts.md).

# Event, API, WebSocket, and Hook Contracts

Last updated: 2026-06-26.

## Purpose

This is the canonical source-backed contract reference for the current FactionOS local-first API, event, WebSocket, protocol, and hook behavior. It documents shipped behavior separately from typed-only protocol surface, historical evidence, stubs, planned features, and Phase 01 hardening gaps.

Use this document with the concise API summary in `docs/api/README_api.md`. Historical files under ignored `EXAMPLES/` are traceability evidence only.

## Source Anchors

| Surface                             | Current source anchors                                                                                                                                                                         |
| ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Protocol events and client messages | `packages/protocol/src/events.ts`, `packages/protocol/tests/events.test.ts`                                                                                                                    |
| Local server routes                 | `apps/server/src/server.ts`, `apps/server/src/routes/*`, `apps/server/tests/*`                                                                                                                 |
| Local WebSocket                     | `apps/server/src/ws/*`, `apps/web/src/store/useWsClient.ts`, `apps/web/src/store/useGameStore.ts`                                                                                              |
| Hook handlers                       | `apps/hooks/hooks.json`, `apps/hooks/src/*`, `apps/hooks/README_hooks.md`                                                                                                                      |
| Historical evidence                 | `EXAMPLES/findings/api-routes.txt`, `EXAMPLES/findings/websocket-events.txt`, `EXAMPLES/findings/claude-hook-contract.md`, `EXAMPLES/findings/BUILD_LINKS.md`, `EXAMPLES/1st-pass-artifacts/*` |

## Status Vocabulary

| Status             | Meaning                                                                                   |
| ------------------ | ----------------------------------------------------------------------------------------- |
| `shipped`          | Current source wires and exposes the behavior in the local-first runtime.                 |
| `tested-shipped`   | Current source wires behavior and focused tests cover the contract.                       |
| `stubbed`          | Current source intentionally returns a not-implemented response or placeholder.           |
| `typed-only`       | Shared protocol types exist, but no current producer or handler was found.                |
| `planned`          | PRD or docs accept the behavior for a future phase, but current runtime does not ship it. |
| `unsupported`      | Historical source claims behavior that current source does not support.                   |
| `obsolete`         | Historical behavior is superseded or no longer useful after current-source review.        |
| `needs-hardening`  | Current behavior exists but has validation, auth, redaction, test, or reliability gaps.   |
| `separate-surface` | Behavior belongs to a different runtime surface, such as the Cloudflare Worker.           |

## Source Policy

* Prefer current source and focused tests over historical extraction files.
* Do not copy raw public tokens, OAuth IDs, probe output, prompt bodies, sensitive local paths, full command output, or long historical cookbook text.
* Treat `packages/protocol/src/events.ts` as the typed event baseline, but do not treat every typed event as a current runtime producer.
* Treat `/event` as a tolerant hook ingest route. It currently routes by `eventName` or `hook`, with `hook_event_name` normalized for Codex-shaped payloads, not by `type` alone except for the selected compatibility subset.
* Treat `apps/warroom` as a separate Cloudflare Worker surface until the web client and local server explicitly wire it.
* Record gaps as Phase 01 hardening notes instead of describing them as current support.

## Local Server Surface

Default HTTP base URL: `http://127.0.0.1:2468`

Default WebSocket URL: `ws://127.0.0.1:2468/`

Current hardening status: the local server is useful for local-first development, but it is not release-hardened. Rate limiting and request body size caps exist. It binds to loopback by default, rejects non-loopback bind hosts unless `FACTIONOS_ALLOW_NON_LOOPBACK_BIND=true`, restricts default CORS and WebSocket origins to local Vite dev origins, and enforces HTTP/WebSocket bearer auth when `FACTIONOS_AUTH_TOKEN` is set. Runtime schemas now cover the current high-risk local POST routes for notice creation, scroll collection, permission responses, plan approval, task queue mutations, template suggestions, guarded-action mutations, and malformed `/event` bodies. Export options and WebSocket client messages are also schema-validated. Session exports and local archives now apply deterministic redaction at their boundaries. LLM routes require explicit provider-transfer opt-in before local data can leave the machine. Archive and memory retention still need unified erasure controls before release.

### Shipped REST Routes

| Method       | Path                                                                                                                                                                                                                        | Status           | Contract                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET`        | `/health`                                                                                                                                                                                                                   | `tested-shipped` | Returns `{ ok, version, uptimeMs, mock, time }`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `POST`       | `/event`                                                                                                                                                                                                                    | `tested-shipped` | Tolerant hook ingest. Malformed non-object bodies use the shared validation envelope. See "Event Ingest Contract".                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `GET`        | `/heroes`                                                                                                                                                                                                                   | `tested-shipped` | Returns `{ heroes }`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `GET`        | `/heroes/:id`                                                                                                                                                                                                               | `tested-shipped` | Returns a `Hero` or `404 { error: "not_found" }`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `GET`        | `/missions`                                                                                                                                                                                                                 | `tested-shipped` | Returns `{ missions }`; `limit` defaults to 50 and must be an integer from 1 through 1000.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `GET`        | `/missions/:id`                                                                                                                                                                                                             | `tested-shipped` | Returns a `Mission` or `404 { error: "not_found" }`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `GET`        | `/notices`                                                                                                                                                                                                                  | `tested-shipped` | Returns `{ notices }`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `POST`       | `/notice`                                                                                                                                                                                                                   | `tested-shipped` | Requires bounded non-empty string `body`, accepts validated `severity` and bounded string `targets`, emits `notice_board_message`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `GET`        | `/scrolls`                                                                                                                                                                                                                  | `tested-shipped` | Returns `{ scrolls }`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `POST`       | `/scrolls/:id/collect`                                                                                                                                                                                                      | `tested-shipped` | Accepts validated optional `heroId`, returns `Scroll` or `404`, emits `scroll_collected`, may emit `achievement_unlocked`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `GET`        | `/achievements`                                                                                                                                                                                                             | `tested-shipped` | Returns `{ achievements }`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `GET`        | `/quests`                                                                                                                                                                                                                   | `tested-shipped` | Returns an idle-hero quest snapshot.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `GET`        | `/warroom`                                                                                                                                                                                                                  | `stubbed`        | Returns local compatibility state plus `capability.status: "stubbed"` and Worker `separate-surface` metadata.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `POST`       | `/permission-response`                                                                                                                                                                                                      | `tested-shipped` | Requires bounded non-empty `requestId`, validates optional boolean `approved`, defaults approval to true unless explicitly false, emits `permission_response`, and returns `{ ok, resolved }`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `POST`       | `/plan/approve`                                                                                                                                                                                                             | `tested-shipped` | Requires bounded non-empty `planId`, validates optional boolean `approved`, defaults approval to true unless explicitly false, emits `plan_approval_response`, and returns `{ ok, resolved }`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `GET`/`POST` | `/export/session`                                                                                                                                                                                                           | `tested-shipped` | Returns redacted JSON or CSV export of in-memory heroes and missions. GET reads \`?format=csv                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `GET`        | `/task-queue`                                                                                                                                                                                                               | `tested-shipped` | Returns a local in-memory queue snapshot with bounded limit and optional state filter. Terminal and Git executable rows expose only safe execution summaries and links.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `POST`       | `/task-queue`                                                                                                                                                                                                               | `tested-shipped` | Validates queue metadata and optional terminal or Git executable payloads, protects idempotent creates, emits `task_queue_update`, and returns the entry plus transition. Terminal command text and Git workbench requests are stored privately and never appear in broad queue rows.                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `PATCH`      | `/task-queue/:id`                                                                                                                                                                                                           | `tested-shipped` | Validates metadata, optional private terminal or Git executable payload, and optional `expectedRevision`, updates local queue state, emits `task_queue_update`, and returns the entry plus transition.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `POST`       | `/task-queue/:id/reject`                                                                                                                                                                                                    | `tested-shipped` | Validates rejection reason and code, rejects the local queue entry, emits `task_queue_update`, and returns the entry plus transition.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `POST`       | `/task-queue/:id/start-tracking`                                                                                                                                                                                            | `tested-shipped` | Preserves metadata-only queue tracking without claiming executor dispatch; emits `task_queue_update`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `POST`       | `/task-queue/:id/dispatch`                                                                                                                                                                                                  | `tested-shipped` | Dispatches terminal executable queue rows through the local terminal runtime and Git executable queue rows through the bounded Git workbench for status, stage, and unstage only. It creates or reuses a queue-targeted command-center execution run, emits both `task_queue_update` and `command_center_execution_update`, and returns safe execution links or compact Git result/recovery summaries. Missing executable payloads, stale revisions, duplicate triggers, PTY unavailable, timeouts, killed sessions, failed sessions, policy-blocked push, and unsupported Git operations return explicit queue/execution states without raw command text, Git output, diffs, patch bodies, commit messages, or broad paths. |
| `GET`        | `/agent-templates`                                                                                                                                                                                                          | `tested-shipped` | Returns compact source-owned local templates with bounded limit and optional role or tag filter; emits `agent_template_update`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `GET`        | `/agent-templates/:id`                                                                                                                                                                                                      | `tested-shipped` | Returns a template or `404`; emits `agent_template_update` when found.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `POST`       | `/agent-templates/suggestions`                                                                                                                                                                                              | `tested-shipped` | Validates bounded suggestion inputs, returns local deterministic template suggestions, and emits `agent_template_update`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `GET`        | `/guarded-actions`                                                                                                                                                                                                          | `tested-shipped` | Returns local in-memory guarded-action proposals with bounded limit and optional state or family filters.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `POST`       | `/guarded-actions`                                                                                                                                                                                                          | `tested-shipped` | Validates family, kind, rationale, preview, references, expiration, and idempotency metadata; creates a bounded non-executing guarded-action proposal; emits `guarded_action_update`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `GET`        | `/guarded-actions/:id`                                                                                                                                                                                                      | `tested-shipped` | Returns a proposal or `404`; pending proposals expire before response when deadlines pass.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `POST`       | `/guarded-actions/:id/approve`                                                                                                                                                                                              | `tested-shipped` | Validates optional reason, revision, and idempotency metadata; records approval; evaluates the executor registry; creates a bounded command-center execution run; completes with executed, failed, unavailable, or not-executed result state; emits guarded-action and command-center executor/execution updates. File approvals remain approved-not-executing until file mutation ships.                                                                                                                                                                                                                                                                                                                                    |
| `POST`       | `/guarded-actions/:id/reject`                                                                                                                                                                                               | `tested-shipped` | Validates optional reason, revision, and idempotency metadata; rejects a pending proposal; emits `guarded_action_update`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `POST`       | `/guarded-actions/:id/decision`                                                                                                                                                                                             | `tested-shipped` | Generic validated approve or reject endpoint for local clients.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `GET`        | `/command-center/capabilities`                                                                                                                                                                                              | `shipped`        | Returns command-center and executor capability envelopes with docs paths, repair requirements, and explicit registry-gated status.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `POST`       | `/command-center/capabilities/refresh`                                                                                                                                                                                      | `shipped`        | Refreshes capability timestamps and emits `command_center_executor_update` without invoking any executor.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `GET`        | `/command-center/{plans,tasks,attention,executors,heroes,executions,permissions,file-intents,workpads,evidence,verification,review-gates,handoffs,diagnostics,channels,usage,notification-readiness,collaboration-posture}` | `shipped`        | Returns bounded in-memory command-center scaffold snapshots with typed scope metadata and compact capability state.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `GET`        | `/command-center/collaboration-posture`                                                                                                                                                                                     | `shipped`        | Returns compact collaboration posture rows with visibility labels, Notice linkbacks, visibility counts, remote-access summary labels, and room-code labels only.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `POST`       | `/command-center/executors/probe`                                                                                                                                                                                           | `tested-shipped` | Re-probes all registered executor capabilities, stores compact capability posture, rejects blocked raw payload fields, and emits `command_center_executor_update`; no executor action runs.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `POST`       | `/command-center/executors/:id/probe`                                                                                                                                                                                       | `tested-shipped` | Re-probes one executor capability id, stores compact posture, rejects invalid ids and blocked raw payload fields, and emits `command_center_executor_update`; no executor action runs.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `POST`       | `/command-center/{plans,tasks,attention,permissions,file-intents,verification,review-gates,handoffs,channels,notification-readiness}`                                                                                       | `shipped`        | Validates protocol-shaped DTOs plus optional expected revision and idempotency key, stores bounded scaffold state, and emits the matching `command_center_*_update` event.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `POST`       | `/command-center/context-notices`                                                                                                                                                                                           | `shipped`        | Creates a canonical Notice for review requests, blockers, or completion handoffs with command-center linkbacks and optional War Room relay result. Raw prompt, command, transcript, output, token, and log fields are rejected.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `POST`       | `/command-center/handoffs/scaffold`                                                                                                                                                                                         | `shipped`        | Creates a handoff scaffold with target metadata, visibility, Notice links, lineage links, remote-access summary labels, and initial readiness checks.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `POST`       | `/command-center/handoffs/validate`                                                                                                                                                                                         | `shipped`        | Updates handoff readiness checks with stale-revision and duplicate-trigger guards, then emits `command_center_handoff_update`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `POST`       | `/command-center/handoffs/resume-source`                                                                                                                                                                                    | `shipped`        | Records a bounded resume-source label for a ready handoff without reading transcripts, files, replay buffers, or Worker payloads.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `POST`       | `/command-center/handoffs/reentry`                                                                                                                                                                                          | `shipped`        | Records re-entry, marks resume-source readiness stale, and preserves safe lineage metadata.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `POST`       | `/command-center/collaboration-posture`                                                                                                                                                                                     | `shipped`        | Records compact collaboration posture and emits `command_center_collaboration_posture_update` with labels, counts, links, and no raw relay payloads.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `POST`       | `/command-center/file-intents/conflicts`                                                                                                                                                                                    | `tested-shipped` | Checks active file-intent conflicts for one repo-relative path and operation, returning bounded intent ids, labels, owner context, state, and timestamps only. It does not read file contents.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `POST`       | `/command-center/file-intents/:id/resolve`                                                                                                                                                                                  | `tested-shipped` | Records file-intent clear, override, or reassignment audit metadata with expected revision and idempotency protection, then emits `command_center_file_intent_update`. It does not edit or delete workspace files.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `POST`       | `/command-center/git/preview`                                                                                                                                                                                               | `tested-shipped` | Builds an allowlisted Git workbench plan with bounded risk, cleanup, rollback, and unavailable metadata. It redacts raw command arguments from broad responses and does not run Git.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `POST`       | `/command-center/git/execute`                                                                                                                                                                                               | `tested-shipped` | Runs only allowlisted local Git workbench operations through timeout-capped execution, stores compact `git_` command-center execution runs, and emits `command_center_execution_update`; push remains policy-blocked unless external Git execution is explicitly enabled.                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `POST`       | `/command-center/permissions/:id/decision`                                                                                                                                                                                  | `shipped`        | Records a scaffold permission approve or reject decision with expected-revision and idempotency protection; emits `command_center_permission_update`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `POST`       | `/command-center/executions/unavailable`                                                                                                                                                                                    | `shipped`        | Records unavailable execution results only; file, git, terminal, container, remote, Worker, hosted, and channel executors are not invoked.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `GET`        | `/command-center/executions/:id`                                                                                                                                                                                            | `tested-shipped` | Returns one bounded execution run detail or `404`; ids must start with `execution_` or persisted Git workbench `git_` ids, and responses never include raw command output.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `GET`        | `/diagnostics/orchestration`                                                                                                                                                                                                | `tested-shipped` | Returns compact local orchestration availability and counts for queue, templates, mission graph, guarded actions, command-center registry posture, recent execution runs, and terminal queue execution posture. It exposes no raw manager payloads or recovery side effects.                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `GET`        | `/diagnostics/provider-readiness`                                                                                                                                                                                           | `tested-shipped` | Returns compact local provider, setup, runtime, command-center diagnostics, and safe recovery posture. It exposes provider labels, status labels, env names, counts, and docs paths only.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `POST`       | `/diagnostics/orchestration/recover`                                                                                                                                                                                        | `tested-shipped` | Accepts only `cleanup_stale_listener_pids` or `cleanup_malformed_spool_entries` plus an idempotency key, performs that narrow local cleanup, and returns compact action counts.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `GET`        | `/diagnostics/isolation`                                                                                                                                                                                                    | `tested-shipped` | Returns compact local isolation posture for unavailable executor families, guarded-action counts, unsupported-route families, redaction categories, and narrow recovery limits. It exposes no raw local payloads and has no mutation side effects.                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |

### LLM and Memory Routes

All LLM engines keep deterministic fallback behavior when provider configuration is absent, blocked, or unavailable. `ANTHROPIC_API_KEY` only marks Anthropic as configured; provider transfer also requires `FACTIONOS_ALLOW_LLM_PROVIDER_TRANSFER=true`. LLM and memory responses expose `X-FactionOS-LLM-Provider`, `X-FactionOS-LLM-Provider-Transfer`, and `X-FactionOS-LLM-Privacy` headers so clients can distinguish fallback, blocked, and enabled transfer modes.

| Method | Path                   | Status           | Contract                                                                                                                                                              |
| ------ | ---------------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `POST` | `/llm/plan`            | `tested-shipped` | Requires bounded `prompt`; accepts optional bounded `missionId` and `conventions`; emits `plan_generated` on success.                                                 |
| `POST` | `/llm/analyze`         | `tested-shipped` | Requires valid non-empty `files`; rejects malformed entries; caps to 12 files and 12000 chars per file; emits analysis completion metadata.                           |
| `POST` | `/llm/scan-codebase`   | `tested-shipped` | Requires validated `root`; walks only roots under the server working directory or `FACTIONOS_SCAN_ROOTS`; emits redacted scan start and analysis completion metadata. |
| `POST` | `/llm/idle-suggestion` | `tested-shipped` | Requires bounded `heroId`; bounds task/activity context; returns `{ suggestions }`; emits `idle_suggestion` when suggestions exist.                                   |
| `GET`  | `/memory`              | `tested-shipped` | Returns `{ findings }` with finding text, tags, and source task IDs redacted.                                                                                         |
| `GET`  | `/memory/:type`        | `tested-shipped` | Accepts `workspace_fact`, `convention`, or `anti_pattern`; rejects other types with shared `invalid_request` envelope.                                                |

Provider-bound text is redacted for prompts, paths, commands, tokens, URLs, and transcript-like values before SDK calls. Scan responses redact absolute roots and return relative scanned file paths, timestamps, sizes, truncation flags, and issues. The scan walker still ignores `EXAMPLES`, `findings`, generated artifacts, lockfiles, sourcemaps, minified bundles, oversized files, and symlinks by default.

### Export Route Behavior

`GET|POST /export/session` exports the current in-memory roster and mission catalog. GET reads `?format=csv|json`; POST accepts the same query parameter or body `{ format }`. JSON responses include schema version, counts, heroes, and missions. CSV responses include labeled sections and the response headers `Content-Disposition`, `X-FactionOS-Export-Schema`, and `X-FactionOS-Export-Privacy: redacted-local`. Responses also set `Cache-Control: no-store`.

Export redaction preserves schema version, JSON top-level fields, JSON counts, and CSV headers. Prompt, path, command, URL, token-like, terminal, and transcript-sensitive values are replaced with deterministic placeholders where they cross the export boundary. Keep exports local; redacted local exports are not a guarantee that arbitrary historical data is safe for public sharing.

### War Room Separation

`GET /warroom` on the local server is a stub. The real room create/join/approve and participant socket backend lives in `apps/warroom` as a Cloudflare Worker and Durable Object surface. The local stub response carries a route capability object for `/warroom` and separate-surface metadata for Worker room APIs. Local requests such as `/warroom/create` return 501 with `family: "warroom-worker"` and `status: "separate-surface"` instead of pretending to be local route parity.

Phase 05 Session 01 records the Worker requirements and trust baseline in `.spec_system/archive/phases/phase_05/war_room_requirements_trust_baseline.md`, the payload rules in `.spec_system/archive/phases/phase_05/war_room_payload_redaction_baseline.md`, and owner routing in `.spec_system/archive/phases/phase_05/war_room_requirement_routing_matrix.md`.

Phase 06 Session 01 adds the broader collaboration and isolation baseline in `.spec_system/archive/phases/phase_06/collaboration_isolation_safety_baseline.md`, with owner routing in `.spec_system/archive/phases/phase_06/phase06_requirement_routing_matrix.md`. Later authority and collaboration event work must start in `packages/protocol`, keep the local `/warroom` route as a stub, and keep file, git, terminal, Docker, remote, and hosted execution unavailable until a separate threat model ships.

Current Worker route vocabulary:

| Method | Worker path                           | Current status                                                                                   |
| ------ | ------------------------------------- | ------------------------------------------------------------------------------------------------ |
| `GET`  | `/health`                             | Shipped Worker liveness probe.                                                                   |
| `POST` | `/rooms`                              | Shipped room create primitive; Session 02 owns shared schema and deterministic errors.           |
| `GET`  | `/rooms/:code`                        | Shipped room snapshot primitive; Session 02 owns bounded response contract.                      |
| `POST` | `/rooms/:code/join`                   | Shipped pending-join primitive; Session 02 owns validation and duplicate/stale behavior.         |
| `POST` | `/rooms/:code/approve`                | Shipped leader approval primitive; Session 02 owns stronger authority and stale approval errors. |
| `WS`   | `/rooms/:code/socket?participant=:id` | Shipped socket primitive; Sessions 02 and 05 own event allowlists and catch-up filtering.        |

The Worker currently treats some socket payloads as opaque events. Web cockpit integration must not rely on that looseness. Future Worker and web clients must send only shared protocol-defined War Room events and must block prompts, file contents, command bodies, terminal output, transcripts, secrets, broad paths, exports, replay buffers, media drafts, and scan payloads from Worker transfer.

Phase 06 expands the blocked collaboration vocabulary to include diagnostics, logs, backups, archives, PID files, spool entries, settings snapshots, memory findings, quarantined historical content, and future hosted payloads. API, Worker, web, CLI, and hook diagnostics should expose compact status and family labels only, not raw local data.

### Isolation Diagnostics

`GET /diagnostics/isolation` reports the current local isolation posture. It is served by the local Express server and inherits the same loopback defaults, optional bearer auth, CORS, rate-limit, and body-size middleware as the rest of the local API. The route is read-only and must not inspect or mutate workspace files, valid spool state, archives, browser state, Worker state, backups, or local state files.

The response is compact protocol-shaped metadata:

* `status`, `generatedAt`, `localOnly`, and `posture`.
* Executor family labels for file, git, terminal, container, remote, and hosted families, all currently `unavailable`.
* Guarded-action counts and status labels only.
* Unsupported-route family labels and the docs path for deterministic 501 envelopes.
* Redaction category names and counts.
* Narrow recovery limits for stale listener PID files and malformed spool JSON.

The route must not echo request bodies, prompts, provider prompts, command bodies, terminal output, stdout, stderr, file contents, diffs, patches, broad paths, cwd, transcript paths, tokens, authorization values, raw queue entries, proposal rationale, raw spool payloads, state files, logs, backups, archives, browser state, Worker payloads, or hosted account data.

Guarded-action approval is registry-gated. Approval records the decision and then evaluates the executor registry. Git workbench adapters are in the bounded executor-ready subset when their local gates pass. File adapters currently report approved-not-executing with dependency-unavailable repair guidance: approval records a not-executed run and does not mutate workspace files until a file mutation manager ships. Git adapters run only allowlisted local workbench operations with timeout, cleanup, rollback, and redaction boundaries. Terminal, container, remote, Worker, hosted, channel, webhook, push, and settings families remain unavailable, approved-not-executing, observe-only, or proposal-only unless a future scoped session proves consent, authorization, audit, cleanup, rollback, redaction, tests, docs, and visible failure states.

### Provider Diagnostics

`GET /diagnostics/provider-readiness` reports local provider, setup, and runtime readiness for Claude Code, Codex, OpenCode, Cursor, Bedrock, and Vertex. The route is served by the local Express server, is also mounted under `/api`, and inherits the same loopback defaults, optional bearer auth, CORS, rate-limit, and body-size middleware as the rest of the local API.

The response is protocol-shaped compact metadata from `packages/protocol/src/providerDiagnostics.ts`:

* Provider ids, labels, readiness statuses, disabled reasons, hook-installed booleans, model-list status/counts, capability flags, repair descriptors, docs paths, and checked-at timestamps.
* Setup readiness status, docs paths, package manager label, setup command statuses, env variable names with status only, scan-root labels, local service labels, and whether setup work should be tracked as a task.
* Runtime health checks for server, listener PIDs, spool, queue, templates, graph, guarded actions, provider readiness, setup readiness, and isolation posture with counts and recovery-available booleans.
* Recovery action descriptors and summary counts.

The route must not echo raw env values, provider payloads, provider responses, prompts, command bodies, stdout, stderr, terminal output, file contents, diffs, patches, broad paths, cwd, transcript paths, tokens, authorization values, raw queue entries, proposal rationale, raw spool payloads, state files, logs, backups, archives, browser state, Worker payloads, or hosted account data. Cloud provider checks are env-label posture only; they do not call Bedrock, Vertex, OpenAI, Anthropic, or other external provider APIs.

`POST /diagnostics/orchestration/recover` accepts only `cleanup_stale_listener_pids` or `cleanup_malformed_spool_entries` plus a safe idempotency key and optional `dryRun`. It rejects unsupported actions with compact `validation_failed` errors and returns `409` when the same recovery action/idempotency key is already in flight. Successful recovery deletes only listener PID files whose process is no longer alive or unreadable local spool JSON entries. It does not delete settings, lifecycle files, valid spool entries, sessions, archives, memory, browser state, Worker state, backups, or workspace files, and it is not a trusted erasure endpoint.

### Historical Route Family Classification

The current source keeps a deterministic 501 catch-all for historical route strings that are not implemented by the local server. Responses include `method`, normalized `path`, `family`, `status`, `docs`, and `message`. They do not echo request bodies, prompts, command previews, token values, query strings, or private path fragments.

| Historical family                                    | Examples                                                                  | Status             |
| ---------------------------------------------------- | ------------------------------------------------------------------------- | ------------------ |
| File operations                                      | `/file-diff`, `/file-operations`, `/open-file`                            | `planned`          |
| Git operations                                       | `/codex/commit`, `/codex/push`, `/worktrees`                              | `planned`          |
| Terminal/internal hero commands                      | `/internal-heroes/...`, `/prompt`, `/response/...`                        | `planned`          |
| Remote access                                        | `/remote-access/...`, `/detect-ides`                                      | `planned`          |
| Container operations                                 | `/container/refresh`, `/docker/...`                                       | `planned`          |
| Hosted services and execution                        | `/hosted/...`, `/analytics/...`, `/replay/share`, `/api/auth/...`         | `planned`          |
| Worker execution bridges                             | `/worker/execute`, `/workers/command`                                     | `separate-surface` |
| Hosted auth, settings, model config                  | `/api/auth/...`, `/settings`, `/config/...`                               | `planned`          |
| Unapproved task queue, sessions, suggestions, memory | `/task-queue/...` outside the shipped subset, `/sessions`, `/suggestions` | `planned`          |
| Collaboration and channels                           | `/collaboration/...`, `/channels/...`, `/pair`                            | `planned`          |
| Push and inbound webhooks                            | `/push/...`, `/webhooks/...`                                              | `planned`          |
| War Room room API on local server                    | `/warroom/create`, `/rooms/...`                                           | `separate-surface` |
| Unknown local paths                                  | any unclassified path                                                     | `unsupported`      |

### Error Model

| Condition                                                   | Current response                                                                                    |
| ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| Missing or invalid request fields                           | `400 { error: "invalid_request", message, details? }` for hardened routes.                          |
| Missing heroes, missions, scrolls, or Worker room resources | `404` where the route explicitly checks the resource.                                               |
| Stale, duplicate, or non-pending guarded-action decisions   | `409 { error: "conflict", message, details? }`.                                                     |
| Rate limit exceeded                                         | `429` from the local fixed-window rate limiter.                                                     |
| Unsupported local server route                              | `501 { error: "not_implemented", method, path, family, status, docs, message }` from the catch-all. |
| LLM plan generation unavailable                             | `503 { error: "plan_generation_failed", hint }`.                                                    |

The 501 catch-all exists to prevent historical route inventories from looking like shipped route parity. Paths from `EXAMPLES/findings/api-routes.txt` are unsupported unless they are listed in this document as shipped or stubbed.

## Event Ingest Contract

Endpoint: `POST /event`

Response envelope: `{ accepted: true, heroId?, missionId? }`

Dispatch key: current source reads `body.eventName ?? body.hook`. When neither is present, the route also recognizes the selected compatibility `type` values listed below. Unknown type-only payloads are accepted as no-ops, not promoted to shipped behavior.

Malformed non-object JSON bodies return `400 { accepted: false, error: "invalid_request", message, details }`.

### Accepted Common Hook Fields

| Field                                                                                                                                                                                                                                                         | Current use                                                                                                                                                                                                                    |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `eventName` or `hook`                                                                                                                                                                                                                                         | Primary dispatch key for provider-neutral hook handling.                                                                                                                                                                       |
| `hook_event_name`                                                                                                                                                                                                                                             | Codex snake\_case alias normalized to `eventName` at the route boundary.                                                                                                                                                       |
| `type`                                                                                                                                                                                                                                                        | Secondary dispatch key for selected compatibility payloads and hook-specific mapping.                                                                                                                                          |
| `heroId`                                                                                                                                                                                                                                                      | Associates prompt, stop, tool, and result events with an existing hero. A saved `sessionId` alias is also accepted here.                                                                                                       |
| `sessionId`, `session_id`                                                                                                                                                                                                                                     | Stored on spawned heroes and used as an alias for later hook and compatibility payloads.                                                                                                                                       |
| `tty`                                                                                                                                                                                                                                                         | Stored on spawned heroes when present.                                                                                                                                                                                         |
| `cwd`                                                                                                                                                                                                                                                         | Stored on spawned heroes and used by hook payloads. Defaults to `/` in the route.                                                                                                                                              |
| `cli`                                                                                                                                                                                                                                                         | Stored on spawned heroes; `claude-code`, `codex-cli`, `cursor`, `opencode`, `openclaw`, and `web` are the protocol-owned values. Unknown values fall back to `claude-code`.                                                    |
| `faction`                                                                                                                                                                                                                                                     | Used by `SessionStart`; otherwise server picks a selectable faction.                                                                                                                                                           |
| `modelId`                                                                                                                                                                                                                                                     | Used by `SessionStart` when provided.                                                                                                                                                                                          |
| `turnId`, `turn_id`                                                                                                                                                                                                                                           | Compact provider turn metadata for opaque or diagnostic mission events only. It does not create a transcript link or durable payload path.                                                                                     |
| `agentId`, `agent_id`, `agentType`, `agent_type`                                                                                                                                                                                                              | Compact Codex agent metadata. Lineage events may use `agent_id` as the subagent identifier when `subagentId` is absent.                                                                                                        |
| `prompt`                                                                                                                                                                                                                                                      | Used by `UserPromptSubmit` and `mission_start`; bounded to the hook contract limit.                                                                                                                                            |
| `summary`                                                                                                                                                                                                                                                     | Used by `Stop` and `hero_idle`; optional mission completion summary.                                                                                                                                                           |
| `tool`, `toolName`, `tool_name`, `toolSummary`, `path`, `filePath`, `inputPreview`, `command`                                                                                                                                                                 | Used by tool payloads to create generic `ToolUse` entries and selected first-class events. `tool` wins over aliases. apply\_patch and MCP-shaped events use explicit safe previews or summaries instead of raw command bodies. |
| `toolUseId`, `tool_use_id`, `ok`, `preview`                                                                                                                                                                                                                   | Used by `PostToolUse` to finish and emit a tool result when `toolUseId` is present.                                                                                                                                            |
| `requestId`, `request_id`, `toolName`, `tool_name`, `rationale`, `detail`, `expiresAt`                                                                                                                                                                        | Used by first-class `permission_request` events.                                                                                                                                                                               |
| `options`, `response`                                                                                                                                                                                                                                         | Used by first-class input wait and input received events.                                                                                                                                                                      |
| `missionId`, `mission_id`                                                                                                                                                                                                                                     | Used by opaque fallback `mission_event`; otherwise falls back to active mission id, resolved hero id, session id, or `unknown`.                                                                                                |
| `subagentId`, `subagent_id`, `parentSubagentId`, `parent_subagent_id`, `parentAgentId`, `parent_agent_id`, `parentMissionId`, `parent_mission_id`, `childMissionId`, `child_mission_id`, `subagentType`, `subagent_type`, `degradedReason`, `degraded_reason` | Used by typed subagent lineage handling. IDs are sanitized and bounded; missing, malformed, or oversized values degrade with reason codes.                                                                                     |

### Ingest Mapping

| Dispatch                                                                                 | Status                          | Current server behavior                                                                                                                                                                                                                                                                  |
| ---------------------------------------------------------------------------------------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `SessionStart`                                                                           | `tested-shipped`                | Spawns or reuses a hero, stores `sessionId` as an alias, emits `internal_hero_spawn` only for new heroes, and returns the generated `heroId`.                                                                                                                                            |
| `hero_active`                                                                            | `tested-shipped`                | Selected type-only compatibility path. Spawns or reuses a hero for `sessionId` and returns the generated `heroId`.                                                                                                                                                                       |
| `UserPromptSubmit` / `mission_start`                                                     | `tested-shipped`                | Resolves `heroId` or `sessionId`, starts a mission if none is active, marks hero active, emits `hero_state` and `mission_start`, and returns `missionId`.                                                                                                                                |
| `Stop` / `hero_idle`                                                                     | `tested-shipped`                | Resolves `heroId` or `sessionId`, completes the active mission when present, clears `activeMissionId`, idles the hero, and emits completion/state events.                                                                                                                                |
| `PreToolUse` with `file_access`                                                          | `tested-shipped`                | With a resolved hero and active mission, records generic `tool_use` and emits first-class `file_access`. Safe `repoRelativePath` metadata is also promoted into command-center file intents; unsafe absolute fallback paths are skipped.                                                 |
| `PreToolUse` with `bash_command`                                                         | `tested-shipped`                | With a resolved hero and active mission, records generic `tool_use` and emits first-class `bash_command`.                                                                                                                                                                                |
| `PreToolUse` with `awaiting_input`                                                       | `tested-shipped`                | Resolves the hero, records generic tool use when a mission is active, marks hero awaiting input, and emits `awaiting_input`. Missing heroes emit bounded `mission_event` kind `missing_hero`.                                                                                            |
| `PostToolUse` with `input_received`                                                      | `tested-shipped`                | Resolves the hero, finishes `tool_result` when `toolUseId` and active mission are present, clears awaiting state, and emits `input_received`. Missing heroes emit bounded `missing_hero`.                                                                                                |
| `PreToolUse` or `PermissionRequest` with `permission_request`                            | `tested-shipped`                | Resolves the hero, records generic tool use when active, emits first-class `permission_request`, and promotes the request into paired command-center permission and attention records when safe identifiers are available.                                                               |
| `PreToolUse` or `SubagentStart` with `subagent_spawn`                                    | `tested-shipped`                | Resolves the parent mission when possible, creates or reuses a bounded child mission graph node, emits `subagent_lineage_update` and `mission_graph_update`, and degrades missing or malformed IDs with compact reason codes.                                                            |
| `SubagentStop` with `subagent_complete`                                                  | `tested-shipped`                | Resolves linked child mission state when possible, completes typed lineage state, emits compact graph updates, and degrades missing child state without crashing.                                                                                                                        |
| `git_dirty`, unsupported subagent variants, `UserPromptCancel`, and unknown named events | `shipped` as opaque             | Git guard payloads with safe attribution metadata are promoted into compact command-center Git diagnostics and also emit bounded compatibility `mission_event` frames. Other unsupported variants emit bounded opaque `mission_event` frames. Payload data is allowlisted and truncated. |
| Missing dispatch key                                                                     | `unsupported` for state changes | Returns `{ accepted: true }` and does not emit a specific event.                                                                                                                                                                                                                         |
| Unknown type-only payload                                                                | `unsupported`                   | Returns `{ accepted: true }` and does not promote the event to a shipped behavior.                                                                                                                                                                                                       |

### Tolerance Behavior

* Missing `heroId` no longer prevents hook flows when `sessionId` resolves to a spawned hero alias.
* Missing heroes for input and permission payloads produce bounded `mission_event` frames with kind `missing_hero`.
* Missing or malformed subagent lineage metadata produces typed degraded lineage updates and compact `lineage_degraded` mission events where a hero or mission relationship cannot be resolved.
* Unknown named events are forwarded as opaque `mission_event` frames so the UI can record them without tight coupling to every CLI hook variant.
* Codex unknown named events keep only allowlisted compact metadata such as event, session, turn, tool, request, and lineage IDs. Opaque fallback data does not include prompt, command, cwd, path, file path, transcript, patch-body, command-output, MCP argument, hosted telemetry, token, or broad local path fields.
* Malformed JSON is handled by Express middleware before the route. Wrong content types usually reach route-level validation as empty bodies on routes that validate required fields.
* Current `/event` validates that the body is an object and bounds fallback detail fields. Codex snake\_case aliases must be strings when present. Pending permission routing remains observational and does not enforce Codex approvals.

### Codex Lifecycle Support

Codex local hook payloads are tested as first-class local ingest data when they use the provider-neutral hook names and compact aliases documented above. The current tested lifecycle is:

`SessionStart -> UserPromptSubmit -> PreToolUse Bash -> PreToolUse apply_patch -> PermissionRequest -> SubagentStart -> SubagentStop -> Stop`

The server materializes this as a `codex-cli` hero, an active and completed parent mission, bounded Bash and apply\_patch tool-use records, a first-class permission request frame, typed subagent lineage with a child mission, and a completed parent mission on Stop. Compact `turn_id`, `hook_event_name`, `agent_id`, `agent_type`, `tool_name`, `tool_use_id`, and `request_id` aliases are normalized at the ingest boundary.

This is local-first support only. It does not add hosted ingestion, external telemetry, provider transfer, Codex approval enforcement, raw transcript capture, raw prompt persistence guarantees, raw patch storage, command output storage, MCP argument storage, or a Codex-specific event store. Existing local auth, CORS, rate-limit, body-size, and validation boundaries remain the same.

### OpenClaw Compatibility Note

Historical OpenClaw instructions posted selected `type`-only payloads. Current source supports this subset:

| `type`          | Status           | Behavior                                                                                |
| --------------- | ---------------- | --------------------------------------------------------------------------------------- |
| `hero_active`   | `tested-shipped` | Materializes or reuses a hero for `sessionId`.                                          |
| `mission_start` | `tested-shipped` | Starts or reuses an active mission for the resolved session hero.                       |
| `file_access`   | `tested-shipped` | Emits generic `tool_use` plus first-class `file_access` when an active mission exists.  |
| `bash_command`  | `tested-shipped` | Emits generic `tool_use` plus first-class `bash_command` when an active mission exists. |
| `hero_idle`     | `tested-shipped` | Completes the active mission and returns the resolved hero to idle.                     |

Other historical type-only events, such as `set_race` and `team_member_detected`, are not shipped compatibility behavior.

## WebSocket Contract

Endpoint: `ws://127.0.0.1:2468/`

The local WebSocket is a best-effort fanout of server events plus a small set of client messages. The server archives emitted events through the broadcaster before notifying server-side listeners and connected sockets.

### Connection Hydration

On connect, the server sends these frames in order:

| Order | Frame                                         | Status    | Payload summary                                                                                                                                                                                            |
| ----- | --------------------------------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1     | `connected`                                   | `shipped` | Server version, protocol version, server time.                                                                                                                                                             |
| 2     | `roster_update`                               | `shipped` | Live heroes plus heroes referenced by the compact initial mission snapshot.                                                                                                                                |
| 3     | `mission_state`                               | `shipped` | Recent mission snapshot. Defaults to 80 missions through `FACTIONOS_WS_HYDRATION_MISSION_LIMIT`; non-active mission tool-use arrays default to 20 entries through `FACTIONOS_WS_HYDRATION_TOOL_USE_LIMIT`. |
| 4     | `notice_board_hydrate`                        | `shipped` | Current notice list.                                                                                                                                                                                       |
| 5     | `scroll_state`                                | `shipped` | Current scroll list.                                                                                                                                                                                       |
| 6     | `achievement_state`                           | `shipped` | Current achievement list.                                                                                                                                                                                  |
| 7     | `task_queue_update`                           | `shipped` | Compact task queue state.                                                                                                                                                                                  |
| 8     | `agent_template_update`                       | `shipped` | Compact agent template availability.                                                                                                                                                                       |
| 9     | `mission_graph_update`                        | `shipped` | Compact mission graph snapshot.                                                                                                                                                                            |
| 10    | `guarded_action_update`                       | `shipped` | Compact guarded-action state.                                                                                                                                                                              |
| 11    | `command_center_plan_update`                  | `shipped` | Compact command-center campaign state.                                                                                                                                                                     |
| 12    | `command_center_task_update`                  | `shipped` | Compact command-center task state.                                                                                                                                                                         |
| 13    | `command_center_attention_update`             | `shipped` | Compact attention queue state.                                                                                                                                                                             |
| 14    | `command_center_executor_update`              | `shipped` | Compact executor capability state; default non-ready families stay unavailable, approved-not-executing, observe-only, or proposal-only unless a registered entry reports ready.                            |
| 15    | `command_center_hero_lifecycle_update`        | `shipped` | Compact hero lifecycle command state.                                                                                                                                                                      |
| 16    | `command_center_execution_update`             | `shipped` | Compact execution-run state for queued, executing, executed, failed, unavailable, and not-executed registry outcomes.                                                                                      |
| 17    | `command_center_permission_update`            | `shipped` | Compact command-center permission state.                                                                                                                                                                   |
| 18    | `command_center_file_intent_update`           | `shipped` | Compact safe-relative file intent state with bounded owner, conflict, related task, guarded-action, and resolution metadata.                                                                               |
| 19    | `command_center_workpad_update`               | `shipped` | Compact workpad state.                                                                                                                                                                                     |
| 20    | `command_center_evidence_update`              | `shipped` | Compact evidence artifact state.                                                                                                                                                                           |
| 21    | `command_center_verification_update`          | `shipped` | Compact verification attempt and review-gate state.                                                                                                                                                        |
| 22    | `command_center_handoff_update`               | `shipped` | Compact handoff state.                                                                                                                                                                                     |
| 23    | `command_center_collaboration_posture_update` | `shipped` | Compact collaboration posture with visibility, Notice links, visibility counts, room labels, and remote-access summary labels only.                                                                        |
| 24    | `command_center_diagnostic_update`            | `shipped` | Compact command-center diagnostic state.                                                                                                                                                                   |
| 25    | `command_center_channel_command_update`       | `shipped` | Compact channel command state; channels do not send externally.                                                                                                                                            |
| 26    | `command_center_usage_update`                 | `shipped` | Compact usage and notification-readiness state.                                                                                                                                                            |

Full imported session history remains available over authenticated HTTP snapshots. WebSocket connection hydration stays intentionally smaller so local session imports do not force the browser to apply hundreds of historical hero and mission records, or thousands of historical tool-use summaries, before the first interactive frame.

### Client Messages

| Client message            | Status           | Server behavior                                                                                                                                                                                                                                                                               |
| ------------------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `hello`                   | `shipped`        | No-op after the hydration frames.                                                                                                                                                                                                                                                             |
| `ping`                    | `shipped`        | Sends `pong`.                                                                                                                                                                                                                                                                                 |
| `permission_response`     | `tested-shipped` | Validates request id and boolean approval, ignores duplicate responses from the same socket lifecycle, resolves and deletes pending permission entry if present, emits `permission_response`.                                                                                                 |
| `plan_approval`           | `tested-shipped` | Validates plan id and boolean approval, ignores duplicate responses from the same socket lifecycle, resolves and deletes pending plan entry if present, emits `plan_approval_response`.                                                                                                       |
| `guarded_action_decision` | `tested-shipped` | Validates guarded-action id, approval boolean, optional reason, expected revision, and idempotency key; ignores duplicate responses from the same socket lifecycle; accepted approvals evaluate the executor registry and emit guarded-action plus command-center executor/execution updates. |
| `post_notice`             | `tested-shipped` | Validates bounded body, severity, target count, and target IDs, then posts a commander notice and emits `notice_board_message`.                                                                                                                                                               |
| `collect_scroll`          | `shipped`        | Collects a scroll, emits `scroll_collected`, and may emit `achievement_unlocked`.                                                                                                                                                                                                             |
| `hero_state_override`     | `tested-shipped` | Validates hero id and hero state enum, then updates hero state and emits `hero_state`.                                                                                                                                                                                                        |

Malformed JSON, non-object payloads, unknown message types, oversized frames, and invalid fields produce compact `server_toast` warning frames. They do not close healthy sockets, mutate manager state, or echo raw payloads.

### Runtime-Produced Event Families

| Family                         | Produced now                                                                                                                                        | Notes                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Connection and state hydration | `connected`, `roster_update`, `mission_state`, `notice_board_hydrate`, `scroll_state`, `achievement_state`, `pong`                                  | Produced by WebSocket handlers.                                                                                                                                                                                                                                                                                                                                                                                                                                |
| Hero and mission lifecycle     | `internal_hero_spawn`, `hero_state`, `mission_start`, `mission_complete`, `mission_event`                                                           | Produced by `/event`, LLM routes, and mock generator.                                                                                                                                                                                                                                                                                                                                                                                                          |
| Demo-only hero details         | `hero_text_chunk`, `hero_metrics_update`, `hero_evidence_update`                                                                                    | Produced by mock generator, not hook ingest.                                                                                                                                                                                                                                                                                                                                                                                                                   |
| Tool flow                      | `tool_use`, `tool_result`                                                                                                                           | Produced by `/event` and mock generator.                                                                                                                                                                                                                                                                                                                                                                                                                       |
| Notice, scroll, achievements   | `notice_board_message`, `scroll_spawned`, `scroll_collected`, `achievement_unlocked`                                                                | Produced by routes, client messages, and mock generator.                                                                                                                                                                                                                                                                                                                                                                                                       |
| Plans and permissions          | `plan_generated`, `plan_approval_response`, `permission_request`, `permission_response`                                                             | Plans and permissions are produced by LLM/mock/routes. Hook `permission_request` does not yet create a pending permission.                                                                                                                                                                                                                                                                                                                                     |
| LLM and idle                   | `idle_suggestion`, opaque analysis `mission_event`                                                                                                  | Produced by LLM routes and mock generator.                                                                                                                                                                                                                                                                                                                                                                                                                     |
| Local orchestration contracts  | `task_queue_update`, `agent_template_update`, `subagent_lineage_update`, `mission_graph_update`, `guarded_action_update`, `command_center_*_update` | Produced by queue/template routes, typed subagent lifecycle ingest, guarded-action routes or WebSocket decisions, terminal/Git queue dispatch, and command-center scaffold routes. Queue, lineage, guarded-action, and command-center frames expose counts, IDs, states, bounded metadata, revision or change metadata, safe relative paths, docs paths, safe terminal/Git execution summaries, and degraded, unavailable, or proposal-only reason codes only. |

Command-center route and event families are local scaffolds unless an explicit registry or coordinator path owns execution. The shipped local executor-ready subset is bounded Git workbench operations, direct terminal/container runtime routes, and terminal or Git executable task-queue dispatch. Other command-center families must not perform file writes, git operations, terminal commands, container runs, remote access, Worker relay, hosted sync, or channel delivery. All broad responses and frames must not expose raw prompts, command bodies, diffs, terminal output, stdout, stderr, file contents, transcript text, provider payloads, tokens, secrets, broad absolute paths, hosted account data, raw logs, replay buffers, or export payloads.

### Command-Center Collaboration And Handoff

`command_center_handoff_update` now carries safe handoff metadata for the web Federation/Handoff panel: visibility labels, command-center Notice linkbacks, readiness status and checks, resume-source state, lineage links, and compact remote-access summary labels. These fields are intended for coordination and review handoff only. They must not include raw prompts, command bodies, terminal output, transcripts, diffs, file contents, raw Worker frames, tunnel tokens, authority values, logs, replay buffers, or export payloads.

`command_center_collaboration_posture_update` is the companion compact posture frame. It reports collaboration visibility, target labels, room code labels, Notice links, visibility counts, and `remoteAccess` summary state such as `disabled`, `unavailable`, `summary_only`, or `no_claim`. The current local scaffold does not open remote access, create a tunnel, call the Worker, or transfer command-center state externally.

Command-center context Notice creation stores canonical Notice Board messages with `commandCenterLinks` pointing back to safe command-center records. The server rejects raw command-center payload fields before persistence, relay, catch-up, WebSocket broadcast, diagnostics, or docs examples. War Room relay, when configured, remains optional external transfer for bounded Notice messages and resolution metadata only.

### Typed-Only and Planned Event Families

The protocol union also contains typed event families that current source does not produce or fully handle as first-class runtime events:

* `hero_dismissed`, `internal_hero_idle`, `internal_hero_active`, `hero_activity_update`, `internal_hero_model_change`, and `internal_hero_permission_mode_change`.
* First-class `file_access`, `file_read`, file-intent, `bash_command`, `awaiting_input`, and `input_received` WebSocket frames from hook payloads.
* Most plan state, plan budget, plan verification, task progress, and task verification events.
* `channel_status`, `cli_availability`, `settings_update`, `ts_errors`, `lint_error`, `test_failure`, `test_pass`, `build_error`, `build_fix`, and `loop_update`.
* `warroom_*`, `remote_access_*`, `remote_transcript_update`, `remote_viewers_update`, and `tunnel_url_changed` in the local server.

These are `typed-only`, `planned`, `unsupported`, or `separate-surface` depending on the owning feature. Do not describe them as emitted by the local server until a source producer and tests exist.

### Phase 03 Orchestration Routing

Phase 03 planning is tracked in `.spec_system/archive/phases/phase_03/orchestration_gap_matrix.md`.

Current orchestration-relevant classifications:

* Task queue and agent template behavior ships the local contract subset. Queue entries are local, in-memory, and bounded. Metadata-only rows remain tracking state; rows with a private terminal executable payload may dispatch through the local terminal runtime and expose only safe execution summaries. Template defaults are compact and source-owned. Broad historical task queue, session, suggestions, usage, skills, issue, and raw template paths remain planned 501 responses.
* Subagent spawn and completion hook payloads now produce typed local lineage and mission graph updates when safe IDs are available. Missing, malformed, or unresolved lineage degrades locally. Git guard payloads remain bounded opaque `mission_event` frames.
* Guarded-action proposal and decision routes now ship a local, in-memory, bounded Session 04 runtime with Session 06 registry-gated approval completion. Approval records a decision, creates a bounded command-center execution run, and returns unavailable or approved-not-executing state by default unless an explicit executor-ready entry runs and returns a redacted bounded result.
* File access and bash command hook payloads remain current observability events, not approved local action execution. File guarded-action approval currently records approved-not-executing/not-executed state and does not edit workspace files. File, git, terminal, remote-access, and container route families outside the guarded-action endpoints remain deterministic 501 responses unless a later PRD approves an executor and tests.
* Web cockpit orchestration controls are planned for Session 05 after protocol/server contracts exist.
* CLI orchestration diagnostics and bounded recovery controls are planned for Session 06 after local state contracts exist.
* War Room federation, hosted collaboration, inbound chat commands, public sharing, analytics, Docker isolation, and broad remote execution remain deferred or excluded from the Phase 03 MVP.

### Replay-Relevant Boundaries

`apps/web/src/store/useWsClient.ts` parses incoming frames as unknown JSON, queues valid server-event objects, and flushes them through `useGameStore.applyEvent()` on the next browser frame. The queue coalesces replacement-safe frames such as hero metrics and full state snapshots to the latest value in a burst, while preserving additive frames such as text chunks, tool use, tool results, notices, toasts, and approvals in arrival order. The web store buffers applied server events for local replay. Generated replay-share links filter malformed entries, cap entries, cap single-event size, and redact prompt, path, command, URL, token-like, terminal, and transcript-sensitive fields before encoding. Replay links remain bounded local convenience payloads, not a hosted-safe sharing contract.

## Provider Hook Contracts

### Claude Code Hook Contract

The installed Claude compatibility map lives in `apps/hooks/hooks.json`. `apps/hooks/hooks.claude.json` mirrors that installed map byte-for-byte for the current release. Handlers live under `apps/hooks/src/` and post to `/event` with a 1500 ms timeout. Handlers are designed to exit quickly, avoid stdout/stderr during normal operation, and log metadata to `~/.factionos/hooks.log`.

### Session 02 Retained Runtime Assumptions

Session 02 keeps the Session 01 ingest vocabulary stable while hardening hook runtime behavior:

* `SessionStart`, `UserPromptSubmit`, `Stop`, selected `PreToolUse`, selected `PostToolUse`, `SubagentStop`, and `PermissionRequest` remain the only installed Claude Code hook triggers in the compatibility map.
* Hook handlers continue to send `eventName` plus the existing hook-specific `type` value; the server remains responsible for resolving session aliases and for accepting bounded opaque `mission_event` fallbacks where first-class protocol events do not exist yet.
* The local server, WebSocket listener, bearer token, hosted services, and adapters remain optional for hook execution. Normal hook handlers must exit 0 and stay silent when those services are unavailable.
* Diagnostics may record handler names, event kinds, timestamps, sizes, status codes, and local state filenames, but must not record raw payloads, full prompts, command bodies, terminal output, secret values, or file contents.
* Spool fallback files are local recovery artifacts, not a remote-delivery guarantee. They must stay bounded, redacted where practical, and safe to discard when malformed.

### Trigger to Handler Mapping

| Trigger             | Matcher                 | Handler                           | Payload sent to `/event`                                                                                                                                                              | Current server result                                                                                                                                        |
| ------------------- | ----------------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `SessionStart`      | none                    | `factionos-hero-spawn.js`         | `eventName: "SessionStart"`, `type: "internal_hero_spawn"`, session, tty, cli, cwd, model, optional faction.                                                                          | Spawns hero and starts listener.                                                                                                                             |
| `UserPromptSubmit`  | none                    | `factionos-hero-active.js`        | `eventName: "UserPromptSubmit"`, `type: "hero_active"`, session alias, truncated prompt and title.                                                                                    | Starts or reuses active mission through session alias.                                                                                                       |
| `Stop`              | none                    | `factionos-hero-idle.js`          | `eventName: "Stop"`, `type: "hero_idle"`, session alias, optional summary.                                                                                                            | Completes active mission and idles hero through session alias.                                                                                               |
| `PreToolUse`        | `Task`, `Agent`         | `factionos-subagent-spawn.js`     | `eventName: "PreToolUse"`, `type: "subagent_spawn"`, tool use id, sanitized subagent IDs, bounded type and description, degraded reason. Raw prompt and transcript path are not sent. | Typed lineage and mission graph updates, with degraded fallback.                                                                                             |
| `SubagentStop`      | none                    | `factionos-subagent-complete.js`  | `eventName: "SubagentStop"`, `type: "subagent_complete"`, sanitized subagent id, bounded summary, degraded reason. Transcript path is not sent.                                       | Typed lineage and mission graph updates, with degraded fallback.                                                                                             |
| `PreToolUse`        | `AskUserQuestion`       | `factionos-awaiting-input.js`     | `eventName: "PreToolUse"`, `type: "awaiting_input"`, truncated prompt and option labels.                                                                                              | Generic `tool_use` when active plus first-class `awaiting_input`.                                                                                            |
| `PostToolUse`       | `AskUserQuestion`       | `factionos-input-received.js`     | `eventName: "PostToolUse"`, `type: "input_received"`, truncated response.                                                                                                             | First-class `input_received`; also `tool_result` when `toolUseId` is present.                                                                                |
| `PreToolUse`        | `ExitPlanMode`          | `factionos-permission-request.js` | `eventName: "PreToolUse"`, `type: "permission_request"`, request id, tool name, rationale, detail, expiry.                                                                            | First-class `permission_request` plus paired command-center permission and attention records when safe identifiers are available.                            |
| `PermissionRequest` | none                    | `factionos-permission-request.js` | Same handler and payload family.                                                                                                                                                      | First-class `permission_request` plus paired command-center permission and attention records when `type` and safe identifiers are present; otherwise opaque. |
| `PreToolUse`        | `Bash`                  | `factionos-git-guard.js`          | When command is dangerous, `eventName: "PreToolUse"`, `type: "git_dirty"`, command preview plus compact `gitOperation`, `gitRisk`, and attribution status when available.             | Compact command-center Git diagnostic plus bounded compatibility `mission_event`; may block only when restricted mode is enabled.                            |
| `PreToolUse`        | `Bash`                  | `factionos-bash-command.js`       | `eventName: "PreToolUse"`, `type: "bash_command"`, command preview and tool summary.                                                                                                  | Generic `tool_use` plus first-class `bash_command` when active mission exists.                                                                               |
| `PreToolUse`        | `Read`, `Write`, `Edit` | `factionos-file-access.js`        | `eventName: "PreToolUse"`, `type: "file_access"`, path, operation, line counts, preview, and compact `repoRelativePath` metadata when safe.                                           | Generic `tool_use` plus first-class `file_access` when active mission exists; safe attribution is promoted into command-center file intents.                 |

### Codex CLI Hook Contract

The Codex source map lives in `apps/hooks/hooks.codex.json`. `factionos init --cli codex` and `factionos init --cli all` install that template into user-level Codex `hooks.json`, respecting `CODEX_HOME` when set. The CLI interpolates the installed hooks package root, injects managed environment values such as `FACTIONOS_CLI=codex-cli`, removes older FactionOS-managed Codex command hooks, preserves user-owned hooks, and backs up a pre-existing raw `hooks.json` before the first managed write.

Supported Codex hook event names are `SessionStart`, `UserPromptSubmit`, `Stop`, `PreToolUse`, `PostToolUse`, `PermissionRequest`, `SubagentStart`, and `SubagentStop`. The map sends these through the same bounded local handlers as Claude where the semantics match, plus Codex-specific source mapping for `apply_patch`, MCP-shaped tools, and Codex subagent metadata. The server normalizes compact Codex aliases such as `hook_event_name`, `tool_name`, `tool_use_id`, `turn_id`, `request_id`, `agent_id`, and `agent_type` at the `/event` boundary.

Codex-specific mapping summary:

| Codex trigger                       | Matcher or source                                            | Handler                                                    | Payload boundary                                                                                             | Current server result                                                                                   |
| ----------------------------------- | ------------------------------------------------------------ | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------- |
| `SessionStart`                      | start source                                                 | `factionos-hero-spawn.js`                                  | `eventName: "SessionStart"`, `cli: "codex-cli"`, compact session, tty, cwd, model, and optional faction.     | Spawns or reuses a Codex-labeled hero and starts the listener.                                          |
| `UserPromptSubmit`                  | ignored matcher                                              | `factionos-hero-active.js`                                 | Bounded prompt summary and title through `type: "hero_active"`.                                              | Starts or reuses an active mission through the session alias.                                           |
| `PreToolUse`                        | `Bash`                                                       | `factionos-git-guard.js`, then `factionos-bash-command.js` | Command preview and tool summary only; no terminal output.                                                   | Bounded `git_dirty` where applicable plus first-class `bash_command` when active.                       |
| `PreToolUse`                        | `apply_patch`, `Edit`, `Write`, selected file-like MCP tools | `factionos-file-access.js`                                 | File path or safe preview metadata only; raw patch bodies, diff bodies, and MCP argument bodies are blocked. | Generic `tool_use` plus first-class `file_access` when active.                                          |
| `PermissionRequest` or `PreToolUse` | permission or selected tools                                 | `factionos-permission-request.js`                          | Request id, tool name, bounded rationale/detail, and expiry.                                                 | First-class `permission_request`; FactionOS remains observational and does not enforce Codex approvals. |
| `PostToolUse`                       | `Bash`, `apply_patch`, MCP                                   | `factionos-tool-result.js`                                 | Tool-use id, status, response type, and compact counts only.                                                 | Finishes a local `tool_result` when a matching tool use exists.                                         |
| `SubagentStart`                     | agent type                                                   | `factionos-subagent-start.js`                              | Compact agent id/type and lineage metadata.                                                                  | Typed subagent lineage and mission graph updates, with degraded fallback.                               |
| `SubagentStop`                      | agent type                                                   | `factionos-subagent-complete.js`                           | Compact agent id/type and bounded summary.                                                                   | Completes typed lineage and mission graph state where resolvable.                                       |
| `Stop`                              | ignored matcher                                              | `factionos-hero-idle.js`                                   | Optional bounded summary.                                                                                    | Completes active mission and idles the Codex hero.                                                      |

Codex handlers use the same 1500 ms bounded POST behavior and quiet failure contract as the Claude handlers. They are local-first observability hooks: no hosted telemetry, external provider transfer, Codex plugin packaging, project-local trusted `.codex/` state, hook-trust bypass, raw transcript capture, raw prompt storage, raw patch storage, command-output storage, MCP argument storage, or Codex approval enforcement is claimed by this contract. Users review loaded Codex hooks with `/hooks` after install.

Phase 12 Session 01 explicitly defers Codex plugin packaging. The supported install surface for this release remains user-level Codex hooks written by `factionos init --cli codex` or `factionos init --cli all`. No plugin manifest, repo marketplace entry, plugin cache validation, plugin trust validation, or plugin uninstall behavior is claimed by this contract.

### Listener and Spool Behavior

`factionos-hero-spawn.js` starts `ws-listener.js` once per terminal when a session starts. The listener:

* Connects to the local WebSocket URL derived from `FACTIONOS_SERVER_URL`.
* Sends `hello` on open and `ping` every 20 seconds.
* Reconnects with capped exponential delay.
* Logs selected server messages and connection state to `~/.factionos/listener-<tty>.log`.
* Polls `~/.factionos/spool` every 10 seconds and tries to send up to 20 JSON files over the WebSocket.

Current limitation: hook POST failures are not currently written to the spool by `postEvent()`, so the spool path is listener-ready but not a complete offline delivery guarantee.

### Hook Privacy and Reliability Notes

* Prompt text is truncated to 8000 characters by `factionos-hero-active.js`.
* Command previews, file write/edit previews, questions, answers, and permission details are truncated before posting.
* Hook logs avoid full payloads and record handler metadata.
* Handlers use fire-and-forget network calls so Claude Code should not stall when FactionOS is down.
* Phase 01 added focused tests for stdout/stderr silence, timeout behavior, event mapping, failed POST handling, listener lifecycle, and prompt/path redaction.

## Phase 06 Collaboration And Isolation Contracts

Phase 06 closeout keeps collaboration and isolation ownership split by runtime surface:

* `packages/protocol` owns shared room authority, participant, safe collaboration event, catch-up, redaction, isolation diagnostics, unsupported-route, and guarded-action unavailable-result contracts.
* `apps/warroom` owns optional Worker room transfer, authority checks, sender exclusion, bounded recent events, compact errors, and safe socket frame persistence.
* `apps/web` owns visible local-only, remote-context, authority failure, reconnect, leave/reset, mobile, reduced-motion, and browser evidence states.
* `apps/server` owns loopback local APIs, the `/warroom` compatibility stub, explicit separate-surface or planned 501 envelopes, and read-only isolation diagnostics.
* `apps/cli` and `apps/hooks` own compact local diagnostics and narrow listener/spool recovery metadata. They do not execute queued tasks or mutate workspace files through recovery paths.

The shipped Phase 06 subset is non-executing. File, git, terminal, Docker, remote, Worker, and hosted executor families remain unavailable until a later approved threat model adds consent, authorization, audit, rollback, redaction, tests, docs, and visible failure states. Diagnostics and errors must expose status, counts, family labels, timestamps, and compact reason codes only; they must not echo raw prompts, command bodies, terminal output, file contents, diffs, tokens, authority values, request URLs with authority query strings, exports, replay buffers, scans, logs, backups, archives, spool payloads, settings, memory findings, or broad local paths.

## Historical Source Classification

This section records what to preserve from historical route, event, hook, listener, and OpenClaw evidence without treating unsupported behavior as current product support.

Phase 08 Session 07 confirms the retained conclusion from these historical findings before any cleanup decision: current source and stable docs are the contract; ignored `EXAMPLES/findings/` files remain local traceability evidence only. The Session 07 action record retains ignored API, WebSocket, hook, architecture, build-link, and prompt findings instead of deleting or reducing them. No copied route inventory, raw prompt body, probe output, command output, copied bundle code, OAuth value, token value, sensitive local path, or quarantined media excerpt is required in this stable contract doc.

| Historical group                                 | Status                                                                              | Current disposition                                                                                                                                                       |
| ------------------------------------------------ | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `EXAMPLES/findings/api-routes.txt`               | Current subset `tested-shipped`; broad list `stubbed` or `unsupported`              | Preserve as source evidence until release decommission gates close. Current local server routes are listed above. All other local paths hit 501 unless later implemented. |
| `EXAMPLES/findings/websocket-events.txt`         | Mixed `shipped`, `typed-only`, `planned`, and `unsupported`                         | Preserve event names as protocol evidence only. Runtime producers are listed in the WebSocket section.                                                                    |
| `EXAMPLES/findings/claude-hook-contract.md`      | Main hook map `tested-shipped`; broader payload cookbook `planned` or `unsupported` | The trigger/matcher map matches current installed hooks. Historical payload details not represented above require future orchestration scope before reuse.                |
| `EXAMPLES/findings/BUILD_LINKS.md`               | Mixed `captured`, `planned`, and `obsolete`                                         | Useful as a pointer map, but it contains stale claims about hook packaging and older spec references.                                                                     |
| `EXAMPLES/1st-pass-artifacts/hooks-config.json`  | `captured`                                                                          | Current `apps/hooks/hooks.json` preserves the main hook map with updated package paths.                                                                                   |
| `EXAMPLES/1st-pass-artifacts/hooks-bundle/`      | Mixed `shipped`, `obsolete`, and `planned`                                          | Maintained handlers now live in `apps/hooks/src/`. Extra historical handlers are not installed by the current map.                                                        |
| `EXAMPLES/1st-pass-artifacts/ws-listener.js`     | Historical remote-control behavior `unsupported`; current local listener `shipped`  | Current listener does not spawn Claude from remote prompts and does not use `/response/:sessionId`.                                                                       |
| `EXAMPLES/1st-pass-artifacts/spawn-listeners.sh` | `obsolete` for current install flow                                                 | Current hero-spawn handler starts the per-terminal listener directly.                                                                                                     |
| `EXAMPLES/1st-pass-artifacts/openclaw-SKILL.md`  | Selected subset `tested-shipped`; broader cookbook `unsupported`                    | Current `/event` supports selected `type`-only payloads listed in the OpenClaw compatibility table. Other historical cookbook events remain unsupported.                  |

## Phase 01 Runtime Hardening Summary

Phase 01 completed the local runtime hardening package for the current shipped surface:

* HTTP and WebSocket auth/token checks, default loopback binding, stricter CORS, WebSocket origin validation, and rate limits are in place for the local server.
* Current high-risk REST routes, WebSocket client messages, export options, and LLM route bodies use compact validation envelopes.
* `/event` ingest accepts the current hook and selected compatibility payloads without crashing and keeps broader historical payloads unsupported unless explicitly mapped above.
* Hook handlers and listener paths have tests for quiet failure behavior, bounded POSTs, payload shaping, lifecycle state, spool handling, and install/uninstall safety.
* WebSocket hydration, client messages, malformed messages, duplicate responses, disconnect cleanup, export privacy, archive redaction, replay-share redaction, and LLM provider-transfer boundaries have focused tests.

Remaining runtime contract gaps are future-phase work:

* Decide whether git guard, file operation, terminal, and remaining orchestration payloads should gain dedicated protocol frames. Subagent lineage frames are now local graph state only and do not provide control actions.
* Do not treat exported sessions, archives, replay links, LLM scans, adapter payloads, War Room federation, or future analytics as share-safe until hosted sharing requirements, access controls, and privacy review exist.
* Add unified local erasure/retention controls for archives, memory, settings, and browser state before trusted release use.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://faction-os.gitbook.io/faction-os-docs/docs/api/event-api-hook-contracts.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
