openapi: "3.1.0" info: title: MCP Task Orchestrator REST API version: "1.0" description: | HTTP REST API for the MCP Task Orchestrator. Operates alongside the MCP transport when API_ENABLED=true. Base URL: /api/v1 NOTE: This file is hand-maintained and may lag edge-case behavior. The source code and api-rest.md are authoritative. See api-rest.md for full semantics including ETag formats, idempotency, audit model, and the SSE replay known limitation. Every operation also accepts the optional X-Client-Host request header (components/parameters/clientHost), which names the calling client in the call log. servers: - url: /api/v1 description: REST API base security: - BearerAuth: [] components: securitySchemes: BearerAuth: type: http scheme: bearer description: | Static bearer token (API_AUTH_MODE=bearer) or JWT (API_AUTH_MODE=jwks). For SSE, use Authorization header or opt-in ?token= query param. Optional opt-in unauthenticated mode (API_AUTH_MODE=none + API_ALLOW_UNAUTHENTICATED=true) accepts requests with no Authorization header at all — loopback-only, see api-rest.md §1. parameters: clientHost: name: X-Client-Host in: header required: false description: >- Optional name of the calling client application, recorded as the host on the request's call_log and events rows. Precedence: this header, else the first User-Agent product token (the text before the first slash), else rest. Normalized: control characters dropped, trimmed, lowercased, capped at 64 code points; an empty result counts as absent. Accepted on every operation. See api-rest.md section 6a. schema: type: string itemId: name: id in: path required: true schema: type: string format: uuid noteKey: name: key in: path required: true schema: type: string schemas: ActorClaimDto: type: object nullable: true required: [id, kind] properties: id: type: string description: "Server-synthesized: api: (the credential principal's id)" kind: type: string enum: [orchestrator, subagent, user, external] description: Always "external" for REST API writes parent: type: string nullable: true NoteSchemaEntryDto: type: object required: [key, role, required, description] properties: key: type: string role: type: string enum: [queue, work, review] required: type: boolean description: type: string guidance: type: string nullable: true skill: type: string nullable: true maxLength: type: integer description: Maximum note-body length configured for this entry. Present only when configured. DispatchProfileDto: type: object description: >- Dispatch routing profile for a phase — who/what should pick up the work. Declared per trait per phase under traits..dispatch. in .taskorchestrator/config.yaml. All fields are optional; at least one is present on any profile the server returns. properties: agent: type: string description: Opaque agent identifier (e.g. "task-orchestrator:implementer"), never validated against any registry. model: type: string description: Opaque model identifier/alias. effort: type: string enum: [low, medium, high, xhigh, max] description: Matched case-sensitively at config-parse time. ResourceRequirementDto: type: object required: [key, mode] description: A trait's declared shared-resource requirement. properties: key: type: string mode: type: string enum: [exclusive, advisory] ttlSeconds: type: integer description: Present only when configured. TraitDto: type: object required: [name, notes] description: >- dispatch and resources are omitted (not present) when the trait declares neither — never an empty map/array. Reflects GLOBAL config only; a per-root override of the same trait's dispatch/resources is not visible here. properties: name: type: string notes: type: array items: $ref: "#/components/schemas/NoteSchemaEntryDto" dispatch: type: object description: Map of lowercase phase name ("queue"|"work"|"review") to DispatchProfileDto. Omitted when the trait declares no dispatch profiles. additionalProperties: $ref: "#/components/schemas/DispatchProfileDto" resources: type: array description: Declared shared-resource requirements. Omitted when the trait declares none. items: $ref: "#/components/schemas/ResourceRequirementDto" EffectiveSchemaDto: type: object required: [type, matchedType, configSource, lifecycleMode, hasReviewPhase, notes, defaultTraits] description: >- A single type's RESOLVED base schema (no trait merging), one entry of EffectiveConfigDto.schemas / EffectiveConfigDto.defaultSchema. properties: type: type: string description: The queried type key. matchedType: type: string description: >- The schema that actually answered the lookup — "default" when a default schema answered a miss on the queried type. configSource: type: string enum: [per-root, global] description: Which layer supplied the schema - same literal the items_read schema select reports. configFingerprint: type: string nullable: true description: The supplying layer's fingerprint, omitted when that layer has none. lifecycleMode: type: string hasReviewPhase: type: boolean notes: type: array items: $ref: "#/components/schemas/NoteSchemaEntryDto" defaultTraits: type: array items: type: string EffectiveConfigDto: type: object required: [schemas, traits, types, statusGraph] description: >- The resolved (layered) config view returned by the `config` tool's `effective` op (POST /ops/config; the element result less its `ok` flag) — every registered type resolved against rootId's per-root config over the server config, in one result. Without a rootId it is the server config alone. properties: rootId: type: string format: uuid description: Omitted for the server-only view. schemas: type: array items: $ref: "#/components/schemas/EffectiveSchemaDto" traits: type: array items: $ref: "#/components/schemas/TraitDto" types: type: array items: type: string description: The union of the per-root and global schema keys, in ascending natural String order; always equal to the `type` values of `schemas`. Each key resolves by one precedence rule (per-root exact type, global exact type, per-root default, global default). statusGraph: $ref: "#/components/schemas/StatusGraphDto" defaultSchema: $ref: "#/components/schemas/EffectiveSchemaDto" globalFingerprint: type: string nullable: true description: Omitted when no global config is loaded. perRootFingerprint: type: string nullable: true description: Omitted when no per-root config is pushed for this root. StatusGraphTypeDto: type: object required: [type, lifecycleMode, hasReviewPhase, transitions] properties: type: type: string lifecycleMode: type: string enum: [auto, manual, permanent, none] description: A `none` type is lifecycle-free and has empty `transitions`. hasReviewPhase: type: boolean transitions: type: object additionalProperties: type: object additionalProperties: type: string description: | role -> trigger -> targetRole. Value "" is a sentinel string for blocked.resume — resolve from the live item's previousRole field. StatusGraphDto: type: object required: [roles, triggers, types] properties: roles: type: array items: type: string triggers: type: array items: type: string types: type: array items: $ref: "#/components/schemas/StatusGraphTypeDto" ServiceInfoDto: type: object required: [serverName, version, apiVersion, capabilities, claimModeAvailable, verifier, features, configWarnings] properties: serverName: type: string version: type: string apiVersion: type: string capabilities: type: array items: type: string claimModeAvailable: type: boolean verifier: type: string enum: [none, bearer, jwks] description: >- The API credential verifier in force: none (unauthenticated mode), bearer (token file) or jwks (JWTs against a key set). Always present. maxStale: type: integer format: int64 description: >- With the jwks verifier, max_stale_seconds: the oldest a cached key set may be, in seconds, and still be served after a failed refresh; past it a JWT is answered 503 unavailable. Omitted for the other verifiers. features: type: array items: type: string description: >- A1/A2: server-wide optional-response feature advertisement (currently ["seats", "dispatchBySeat", "independent_of", "rules"]), advertised unconditionally regardless of whether the resolved config for any given root declares seats or independent_of. Same list as WellKnownDto.features. configWarnings: type: array items: type: string description: >- Warnings stored with the SERVER config head: the reasons recorded when the global config file was imported at boot (one per legacy top-level key such as orchestration, retrospective, actor_attribution or schema_resolution), in the form push warnings use. Empty when there is no server config. WellKnownDto: type: object required: [name, version, apiVersion, apiUrl, features] description: Service discovery document served at GET /.well-known/mcp-task-orchestrator.json (mounted at the root, not under /api/v1). properties: name: type: string version: type: string apiVersion: type: string apiUrl: type: string features: type: array items: type: string description: A1/A2 — same server-wide feature advertisement as ServiceInfoDto.features. SeatDto: type: object required: [name, phase] description: >- One declared orchestration seat (A1) — parsed, merged, and served, but not itself enforced by the server. See config-format.md "Seats (Trait & Schema Dimension)". properties: name: type: string phase: type: string enum: [queue, work, review] enters: type: boolean description: Present only when true. after: type: array items: type: string description: Seat names this seat's work logically follows. Present only when non-empty. readsExclude: type: array items: type: string description: Note keys this seat should not read. Present only when non-empty. ItemSchemaNoteEntryDto: type: object required: [key, role, required, description] description: >- Full note-schema entry of the item schema view (items_read select schema) — same base shape as NoteSchemaEntryDto, plus the A1 seat fields. A distinct schema from NoteSchemaEntryDto because /config* and /config/effective (which use NoteSchemaEntryDto) do not serve seats in A1. properties: key: type: string role: type: string enum: [queue, work, review] required: type: boolean description: type: string guidance: type: string nullable: true skill: type: string nullable: true maxLength: type: integer description: Maximum note-body length configured for this entry. Present only when configured. seat: type: string nullable: true description: >- A1: this entry's declared owning seat. Present (possibly null) only when the schema is seat-aware; omitted entirely for a seat-less schema. null means the note has no owning seat and is served under "unowned" in missingBySeat. independentOf: type: array items: type: string description: >- A1: seat names this note's authoring must stay independent of. Present only when non-empty, regardless of seat-awareness. Parsed and served since A1; enforced as of A2 (the independence attestation gate) — see config-format.md "Independence (A2)". ItemSchemaViewDto: type: object required: [type, configSource, notes, features] description: >- The item schema view (A1c), now served as the data of items_read select schema (the GET /items/{id}/schema route is removed), built by the ItemSchemaView server-side builder, never a second, separately maintained builder. properties: type: type: string configFingerprint: type: string nullable: true configSource: type: string enum: [per-root, global] notes: type: array items: $ref: "#/components/schemas/ItemSchemaNoteEntryDto" dispatch: type: object description: Map of lowercase phase name ("queue"|"work"|"review") to DispatchProfileDto. Omitted when no resolved trait declares a profile for any phase. additionalProperties: $ref: "#/components/schemas/DispatchProfileDto" resources: type: array description: Trait-declared shared-resource requirements. Omitted when none resolve. items: $ref: "#/components/schemas/ResourceRequirementDto" seats: type: array items: $ref: "#/components/schemas/SeatDto" description: A1 — merged-seat order. Present only for a seat-aware schema. dispatchBySeat: type: object description: >- A1: map of lowercase phase name to a map of seat name to DispatchProfileDto. Present only for a seat-aware schema; a phase is included only when at least one of its seats has a resolved profile. additionalProperties: type: object additionalProperties: $ref: "#/components/schemas/DispatchProfileDto" features: type: array items: type: string description: A1 — always present, same server-wide feature advertisement as ServiceInfoDto.features. HealthDto: type: object required: [status, dbReachable] properties: status: type: string enum: [ok, degraded] dbReachable: type: boolean OpsEnvelope: type: object description: >- The 4.0 response envelope: ok, then data (success) or error {code, kind, message, fix?, detail?} (failure), and meta {reqId}. Per-tool data shapes are served by the tool's describe call. required: [ok, meta] properties: ok: type: boolean data: type: object additionalProperties: true error: type: object additionalProperties: true meta: type: object required: [reqId] properties: reqId: type: string responses: Unauthorized: description: >- Missing or invalid bearer token: the unauthenticated error envelope (Q32). The RFC 6750 WWW-Authenticate challenge names the reason: error="invalid_request" (missing, non-Bearer or empty credential) or error="invalid_token" (unknown, expired or invalid token). A JWT whose key set is unavailable is not "invalid": see KeySetUnavailable. headers: WWW-Authenticate: description: Bearer challenge, e.g. Bearer error="invalid_token" schema: type: string content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" KeySetUnavailable: description: >- The unavailable error envelope (retryable): a JWT was presented while the JWKS key set cannot be had (never fetched, or older than max_stale_seconds), so the credential could be neither accepted nor rejected. Verification fails closed: no identity is guessed. error.detail.retryAfterMs is 15000. There is NO WWW-Authenticate header. Any route behind the jwks verifier can answer it, as can /mcp and GET /events with ?token=. content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" Forbidden: description: >- The forbidden error envelope; error.detail.scope is capability (the token lacks the route's capability), root or tag (the item is outside the token's scope) or host (the Host header is not allowed; required is a fixed literal, never the allowlist). A token-file credential with profile director gets scope capability and required director on every path except POST /api/v1/ops/director/{tool}. content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" paths: /items/{id}: get: summary: Get a single work item (items_read select get) operationId: getItem tags: [items] description: | Equivalent to `POST /api/v1/ops/items_read` with `{"select":"get","itemId":""}`: the same dispatcher, the same access (the bearer principal, its root/tag scope and capabilities) and the same envelope body, apart from `meta.reqId`. `id` is a UUID or an 8 to 32 hex-character prefix. The route takes no query parameter: any is `unknown_parameter` (`/`); timestamps, ancestors and `ifVersion` are served by the select over `/ops`. A successful answer carries `ETag: "v"`; a request whose `If-None-Match` names it (a tag list, a weak validator or `*`, as for the note GET) is answered `304 Not Modified` with no body. An error is never a 304 and carries no ETag: an item outside the caller's scope is `403 forbidden` (a missing id under a restricted scope too), whatever `If-None-Match` says. parameters: - name: id in: path required: true description: Item id, a UUID or an 8 to 32 hex-character prefix. schema: type: string - name: If-None-Match in: header required: false description: ETags from previous reads (a list, weak validators or `*`); naming the current one answers 304. schema: type: string responses: "200": description: >- Envelope with `data` = the full item view (lean: empty members omitted, tags as an array); a pinned item adds `schemaVersion` `{server?, root?, key?, layer?}` and, only when a pinned config version is no longer the head, `stale: true` headers: ETag: description: '"v" of the item read.' schema: type: string X-Req-Id: description: The call's correlation id, equal to meta.reqId. schema: type: string content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "304": description: Not Modified - If-None-Match names the current ETag (no body) "400": description: invalid_request (malformed id) or unknown_parameter (any query parameter) envelope content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "401": $ref: "#/components/responses/Unauthorized" "503": $ref: "#/components/responses/KeySetUnavailable" "403": description: forbidden envelope (capability, root or tag scope, or a director-profile credential (detail.required director)) content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "404": description: not_found envelope (unrestricted caller only) content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "409": description: ambiguous_id envelope (the prefix matches several items the caller may see) content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "500": description: internal envelope content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" /items/{id}/children: get: summary: List an item's direct children (items_read select list) operationId: getItemChildren tags: [items] description: | Equivalent to `POST /api/v1/ops/items_read` with `{"select":"list","parentId":"","limit"?,"cursor"?}`: the same dispatcher, access and envelope body, apart from `meta.reqId`. The page is the compact item view (`id`/`parentId` as 8-hex short ids) with `data.page {total, truncated, capped?, next?}`; the caller's root/tag scope is applied before paging, so `total` counts only visible children. A parent the caller may not see, or one that matches nothing, is an empty page. Only `limit` and `cursor` are accepted (anything else is `unknown_parameter`); a non-integer `limit` is `invalid_request`. No ETag. parameters: - name: id in: path required: true description: Parent item id, a UUID or an 8 to 32 hex-character prefix. schema: type: string - name: limit in: query required: false description: Page size, 1 to 200 (default 50). schema: type: integer - name: cursor in: query required: false description: The page.next of the previous page. schema: type: string responses: "200": description: Envelope with `data` = {items, page} content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "400": description: invalid_request, invalid_cursor or unknown_parameter envelope content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "401": $ref: "#/components/responses/Unauthorized" "503": $ref: "#/components/responses/KeySetUnavailable" "403": description: forbidden envelope (capability; or a prefix that matches no item the caller may see, or a director-profile credential (detail.required director)) content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "409": description: ambiguous_id envelope content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" /items/{id}/notes: get: summary: List notes for an item (notes_read list) operationId: listNotes tags: [notes] description: | A thin translation to `notes_read select=list`: the answer is the response envelope, byte-equal to `POST /ops/notes_read` for the same arguments apart from `meta.reqId`. `data.items[]` are note summaries `{id (8 hex characters), key, role, version, bodyLength, modifiedAt, actor?, verification?, owner?}` ordered by key and never carry a body (read one with the single-note route). `actor`, `verification` and `owner` (`{id}`, the owning principal; omitted for an unowned note) are present only when the caller may see attribution (an admin, or `API_REDACT_NOTE_ATTRIBUTION=false`); `verification` is `{proofStatus (verified | verified_stale | issued | none | rejected), verifier?, reason?}`; proof evidence is never shown. `data.page` is `{total, truncated, next?}` with an opaque cursor (envelope amendment U22): `total` is the full count on every page, `truncated` is true exactly when notes exist after this page, and `next` is present exactly when `truncated`. A query parameter other than the four below is `invalid_request` (400). parameters: - $ref: "#/components/parameters/itemId" - name: role in: query schema: type: string enum: [queue, work, review] - name: keys in: query description: Comma-separated note keys to keep. schema: type: string - name: limit in: query description: Page size, 1 to 200 (default 50). schema: type: integer - name: cursor in: query description: Opaque cursor from the previous page's `data.page.next`. schema: type: string responses: "200": description: Envelope with ok=true headers: X-Req-Id: schema: type: string content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "400": description: invalid_request, unknown_parameter or invalid_cursor envelope content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "401": $ref: "#/components/responses/Unauthorized" "503": $ref: "#/components/responses/KeySetUnavailable" "403": description: forbidden envelope (capability, root or tag scope, or a director-profile credential (detail.required director)) content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "404": description: not_found or ambiguous_id envelope for the item id content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" /items/{id}/notes/{key}: get: summary: Get a single note by key (notes_read get) operationId: getNote tags: [notes] description: | A thin translation to `notes_read select=get`: the answer is the response envelope whose `data` is `{id, key, role, version, body, modifiedAt, actor?, verification?, owner?}`. The `ETag` response header is `"v{version}"`; an `If-None-Match` naming it (or `*`) answers 304 with no body. Writes have no resource route: use `POST /ops/notes_write` (`upsert`, `delete`, each with an optional `expectedVersion`; an `upsert` may carry the admin-only `takeover` flag, and a write to another principal's non-shared note is `note_owned_by_other`). The route takes no query parameter. parameters: - $ref: "#/components/parameters/itemId" - $ref: "#/components/parameters/noteKey" - name: If-None-Match in: header schema: type: string responses: "200": description: Envelope with ok=true headers: ETag: description: '"v{version}" of the note.' schema: type: string X-Req-Id: schema: type: string content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "304": description: The note is still at the version named by If-None-Match (empty body) headers: ETag: schema: type: string "400": description: invalid_request or unknown_parameter envelope content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "401": $ref: "#/components/responses/Unauthorized" "503": $ref: "#/components/responses/KeySetUnavailable" "403": description: forbidden envelope (capability, root or tag scope, or a director-profile credential (detail.required director)) content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "404": description: not_found envelope (item, or note with id "/") or ambiguous_id content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" /config/schema: get: summary: The JSON Schema every config document is validated against operationId: getConfigSchema tags: [config] description: >- The JSON Schema (draft 2020-12) for a config document, served byte for byte as application/schema+json (not wrapped in an envelope). The ETag changes exactly when the schema does. parameters: - name: If-None-Match in: header schema: type: string responses: "200": description: The schema document headers: ETag: schema: type: string content: application/schema+json: schema: type: object "304": description: Not modified "401": $ref: "#/components/responses/Unauthorized" "503": $ref: "#/components/responses/KeySetUnavailable" "403": $ref: "#/components/responses/Forbidden" /ops/{tool}: post: summary: Call a 4.0 tool (RPC) operationId: callOp tags: [ops] description: | The canonical RPC route over the 4.0 tool registry. The body is the tool's MCP arguments (`select` for a read tool, `ops[]` for a write tool, `describe: true` for its schema); the answer is the response envelope, byte-equal to what MCP returns for the same arguments and access, apart from `meta.reqId` (also the `X-Req-Id` header). The HTTP status comes from the envelope error code (200 for ok, 207 for a partial batch); no route picks one by hand. Identity is the bearer credential (`api:`); a body `actor` is ignored, so idempotency keys (`ops[].idempotencyKey`) are namespaced per token. Capability is checked per select/op (ADMIN grants all): a read select lacking it fails the whole call with `forbidden` (`scope: capability`), an op element lacking it fails alone and is never executed. The token's root/tag scope reaches every handler; an out-of-scope item is `forbidden` (`scope: root|tag`), list reads filter instead. Faults answer an envelope with status 400 `invalid_request`: a tool that is not registered (field `tool`), a `Content-Type` other than `application/json` (field `Content-Type`; absent is accepted), an `Idempotency-Key` header (field `Idempotency-Key`; use `ops[].idempotencyKey`), or a body that is not a JSON object (field `$`). A body over 1 MiB is 413 `payload_too_large`. A missing or invalid credential answers the 401 unauthenticated envelope (see Unauthorized). Serves every registered select and op whatever its MCP profile set, REST-only members included. The `advance` tool (`/ops/advance`) replaces the 3.x `advance_item` and `claim_item` tools and the removed `POST /items/{id}/advance` route. Its `ops[]` elements are `transition` (apply a trigger), `claim` (by `itemId` or `select`), `release` and `heartbeat`, all needing the `advance` capability. Claim ownership and resource leases are enforced on this route exactly as on MCP. Inside a run that is not closed, whose pinned schema declares `seats`, a `transition` is also checked against the caller's seat: a caller that may not send the trigger to that item is `403 seat_forbidden` (`detail`: `itemId`, `seat` (omitted without a token), `action`, `allowedSeats`), nothing is applied, and a human credential is exempt. A cascade into such a member the caller could not advance directly is not applied and is reported with `blocked: seat`. A terminal cascade never moves a parent in `review`: it is reported with `blocked: gate` and `reason: review-pending` (no `missing`). A `claim` that takes an item over another holder pair's lapsed claim adds `displaced: {assignmentId?, expiredAt, principal?}` to its result (`principal` only for a caller that may see principals) and records the table-only `claim.expired` row with `reason: "displaced"` and `displacedBy` (the new holder's assignment id, or null); a claim.expired row found by a sweep or advance carries `reason: "expired"`. `items_write` ops are `create`, `update`, `delete`, and `create_tree`, `complete_tree` and `repin` (orchestration profile only). `repin` (`{op: "repin", id, expectedVersion?}`, `write-items` capability) moves the item's config pin to the current config heads and answers `{ok, id, version, repinned, schemaVersion?}`; `repinned: false` means the pin was current and nothing was written. A `notes_write` `upsert` of a key that a pinned item's pinned schema lacks but the current head schema requires fails `schema_pinned_conflict` (409; `detail.itemId`, `pinnedVersion`, `currentVersion` as `server:/root:`): repin the item first. The `docs_read` and `docs_write` tools replace the 3.x `manage_plan_documents` tool and the removed `/roots/{rootId}/plans[/{slug}]` routes. `docs_read` selects are `get`, `list`, `history` and `links` (`READ`); `docs_write` ops are `upsert`, `archive`, `unarchive`, `delete`, `attach` and `detach`, all needing `write-docs` (`write-config` grants none of them). A document is addressed by `(rootId, kind, slug)`. `bodyFromFile` is refused on this route (`invalid_request`, no file read). The `config` tool (`/ops/config`) replaces the 3.x `manage_project_config` and `query_rules` tools and the per-root config, rule and config-discovery routes (`/roots/{rootId}/config*`, `/roots/{rootId}/rules*`, `/config`, `/config/schemas*`, `/config/traits`, `/config/types`, `/config/status-graph`, all removed). Its `ops[]` elements are `get`, `history`, `validate`, `effective` and `rules` (capability `read`) and `push`, `rollback` and `reset` (capability `write-config`). Only `GET /config/schema` stays a route. The `report` tool (`/ops/report`, capability `read`; on MCP the director profile only) serves aggregate reports. Its selects are `usage` (windows at most 400 days), `gates`, `notes`, `contention` and an anchor `rollup` (at most 31 days), `waste` (at most 7 days) and a run `rollup` (the whole run). `usage` reports call-log calls, errors, response bytes, token estimate, average and maximum latency, retries and replays per `groupBy` group over a half-open `[since, until)` window (default the last 7 days, at most 400; at most 31 inside the raw horizon reads `call_log`, `basis: raw`, otherwise the per-day summaries plus the raw tail, `basis: daily`), with `data.window` next to `items` and `page`. `gates` counts rejected transitions (`transition.rejected` events; `blocks` and `items`) per `noteKey` (default), `type`, `trait` or `errorCode`. `notes` counts note writes (`note.upserted` events: `writes`, `notes`, `rewrites`, `bytes`, `maxBytes`, `avgBytes`) per `role` (default), `noteKey`, `seat`, `type`, `principalKind` or `day`, optionally within the subtree of `anchorId`. `contention` counts claim and lease events per `resource` (`acquired`, `rejected`, `expired`, `released`, `forceReleased`, with `contentionRate`, `expiryRate` and `forceReleaseRate` rounded to 4 decimals and omitted when the denominator is 0). `gates`, `notes` and `contention` windows are at most 31 days. Each item's `key` is `{: value}`, or `{}` when the group value is missing (never a JSON `null`). `waste` answers one object of call-pattern waste signals (`redundantReads`, `overFetch`, `readsWithoutLaterWrite`, `emptyNext`, `relatedFollowThrough`, `lifecycleFreeRejections`, each `{value?, numerator, denominator, basis?}`), with no grouping and no page. `rollup` takes exactly one of `anchorId` and `runId` (neither is `invalid_request` on `/anchorId`, both on `/runId`). With `anchorId` it answers one object for the anchor's subtree (inclusive): `{scope: {anchorId, rootId}, window: {since, until, clamped?}, itemCounts: {total, byRole}, blocked: {total}, transitions: {total, cascades, rejected}, notes: {written}, cost: {calls, errors, retries, responseBytes, responseTokensEst, basis: targets}}`, short ids only; with neither `since` nor `until` the window runs from the subtree's first event to its last plus 1 ms, clamped to 31 days (`window.clamped`). Its cost is a lower bound (calls that named a subtree item or wrote one of its events). With `runId` (resolved like `runs_read` `get`; `since` or `until` with it is `invalid_request` on that field) it answers the whole run: `scope: {runId, rootId}`, `window` from `openedAt` to `closedAt` or now, `run: {status, terminalReason?, openedAt, closedAt?}`, item and blocked counts over the current members (`blocked.byReason`, plus `resumable` and `dwellMs` when non-zero), transitions and notes from the events stamped with the run, `cost` (`basis: run`) from the calls stamped with it, `decisions: {open, byClass, bySeverity}`, `seats: {active, stalled, count}`, `attempts: {total, max}` (no `budget`: removed in 4.0.1). A closed run answers the snapshot stored in its `run.ended` event; a root-scoped token sees only runs of its roots. Scope differs per select. `usage`, `waste` and `rollup` read `call_log` rows, which carry no tags: a tag-scoped token is `forbidden` (`scope: tag`) and a root-scoped token sees only calls recorded against its roots; `groupBy: principal` needs `admin` (else `forbidden`, `scope: capability`) and is raw-only (`invalid_request` on the daily basis). `gates`, `notes` and `contention` read events: a tag-scoped token is not refused and sees only the events whose item currently carries an allowed tag, and a root-scoped token sees only the events of its roots. The `runs_read` tool (`get`, `list`, `seats`, `frontier`; capability `read`) and the `runs_write` tool (`open`, `update`, `close`, `pause`, `resume`, `mark`, `assign`, `end_seat`, `raise`, `withdraw`; capability `runs`, and `ack` and `answer` with capability `decide`) serve runs and decisions. A run is as visible as its root: a run whose root is outside the token's scope is `forbidden` (`root` or `tag`) before any permission rule, and `list` leaves it out. `open` returns `coordinatorToken`, the run's coordinator credential (shown once). A token is shown once: a keyed replay of `open` or `assign` returns the stored result without `coordinatorToken` or `seatToken` and with `tokenRedacted: true` (the idempotency store never holds a token); re-assign the seat for a fresh token, or close the run and open a new one for a new coordinator token. The coordinator is the caller presenting that token as the top-level `seatToken`. `close` is for the coordinator, the director profile or a human token; `pause` and `resume` for the director profile or a human token (never under a seat token); `update` and `assign` for the coordinator; `end_seat` for the seat's own token; a refusal is `forbidden` with `detail.scope: principal_kind` and `detail.required` the allowed kinds. `assign{runId, itemId, seat, hints?}` returns `{assignmentId, seatToken, attempt}` (an unknown seat is `not_found`, `detail.kind: seat`); `end_seat{outcome, summary?, links?}` returns `{assignmentId, itemId, seat, attempt, outcome, endedAt, released}`; `seats{runId, itemId?, ended?}` returns `{runId, seats}` without any token. `frontier{runId}` returns `{runId, status, stalled, counts, ready, inFlight, waiting}` (item ids are 8-hex short ids; members and blockers outside the token's scope are left out). Every run view carries `activeSeats` and `stalledSeats`; under a restricted scope, `members`, `activeSeats` and `stalledSeats` count only what the caller's scope can see. `mark` is REST only: it sets a named instant on a run in any status, first write wins, and `marked: false` reports a replay. Decisions: `runs_write` `raise` (capability `runs`), `ack` and `answer` (capability `decide`) and `withdraw` (capability `runs`); `runs_read` `decisions{runId?, itemId?, rootId?, overdue?, limit?, cursor?}` (newest first) and `decision{decisionId}` (capability `read`). `decisions` has no status filter: every summary carries `status`, so a caller filters by status client-side. A decision is as visible as its root, like a run. Any body may carry a top-level `seatToken` (every tool): it is accepted only while its assignment is active and only from the principal it was issued to; otherwise the call is `401 unauthenticated` with the fixed message `The seat token is not accepted.` and no detail, before anything else in the body is read. A call under a token loses ADMIN, holds claims as its seat (principal plus assignment), owns the notes it creates or adopts as its seat (owner pair), records its seat as each written note's attribution seat, and is its own idempotency principal. `advance` `heartbeat` takes no `usage` (removed in 4.0.1). The run errors are 409 `run_closed` (`runId`, `terminalReason`), `run_paused` (`runId`, `pauseReason`, `pauseDecisionId?`), `invalid_run_state` (`runId`, `status`, `allowed`), `run_at_capacity` (transient; `runId`, `active`, `max`) and `decision_closed` (`decisionId`, `status`); a refused seat is 403 `seat_forbidden`. The check order is scope, then permission, then the state of the run. The coordinator token of a closed run is dead (`401 unauthenticated`); a director or human `close` still works. parameters: - name: tool in: path required: true description: Registry tool name. schema: type: string requestBody: required: true content: application/json: schema: type: object description: The tool's arguments, exactly as in an MCP tools/call. additionalProperties: true responses: "200": description: Envelope with ok=true; every batch element succeeded (any failed element makes the call 207) headers: X-Req-Id: description: The call's correlation id, equal to meta.reqId. schema: type: string content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "207": description: Partial batch - some ops[] elements failed (see results[].error) content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "400": description: invalid_request or unknown_parameter envelope content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "401": $ref: "#/components/responses/Unauthorized" "503": $ref: "#/components/responses/KeySetUnavailable" "403": description: forbidden envelope (capability, root or tag scope, or a director-profile credential (detail.required director)) or another 403 catalog code content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "409": description: >- Envelope whose top-level error is a 409 catalog code: version_conflict, schema_pinned_conflict (a notes_write upsert against a stale pin), resource_unavailable and the other conflict codes content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "413": description: payload_too_large envelope (body over 1 MiB) content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "500": description: internal envelope (fixed message; detail only in the server log) content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" /ops/director/{tool}: post: summary: Call a director-profile tool (RPC) operationId: callDirectorOp tags: [ops] description: | The director tool profile over REST, through the same dispatcher as `/ops/{tool}`: the same body, envelopes, statuses, capability and scope checks, serving only the director set (`items_read` `get`, `list`, `overview`, `blocked`; `deps_read` `list`, `graph`; `runs_read` `get`, `list`, `frontier`, `decisions`, `decision`; `runs_write` `open`, `close`, `pause`, `resume`, `ack`, `answer`, `withdraw`). For a member of that set the envelope is byte-equal to the `/ops/{tool}` answer, apart from `meta.reqId`. A registered tool with no member in the director set is 403 `forbidden` (`scope: capability`, `required: director`); an unregistered name is 400 `invalid_request` (field `tool`); a select hidden inside a visible tool is the dispatcher's 400 `invalid_request` (`/select`). This is the only path a token-file credential with `profile: director` may call; every other path answers that credential 403 `forbidden` (`required: director`). parameters: - name: tool in: path required: true description: Registry tool name (lowercase). schema: type: string requestBody: required: true content: application/json: schema: type: object description: The tool's arguments, exactly as in an MCP tools/call. additionalProperties: true responses: "200": description: Envelope with ok=true headers: X-Req-Id: description: The call's correlation id, equal to meta.reqId. schema: type: string content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "400": description: invalid_request or unknown_parameter envelope content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "401": $ref: "#/components/responses/Unauthorized" "503": $ref: "#/components/responses/KeySetUnavailable" "403": description: forbidden envelope (a tool outside the director set, capability, root or tag scope) content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "413": description: payload_too_large envelope (body over 1 MiB) content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "500": description: internal envelope (fixed message; detail only in the server log) content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" /resources/leases: get: summary: List active resource leases operationId: listResourceLeases tags: [resources] description: >- Cross-project, server-wide - not root-scoped, unlike the rest of this API. Backs the resource-lease gate of the `advance` tool's `transition` op and the resources: trait dimension. Answers the response envelope: a list page ordered by (resourceKey, holderItemId) whose `page.total` equals `items.length` (lease cardinality is bounded, so the list is never truncated). Item shape: `{resourceKey, holderItemId, acquiredByActorId?, acquiredAt, expiresAt, originalAcquiredAt}`; `acquiredByActorId` is present only for ADMIN callers. Requires `read`; a token without it gets `forbidden` (`scope: capability`). responses: "200": description: Envelope with ok=true and a list page of active leases content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "401": $ref: "#/components/responses/Unauthorized" "503": $ref: "#/components/responses/KeySetUnavailable" "403": description: forbidden envelope (the token lacks `read`, or a director-profile credential (detail.required director)) content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" /resources/leases/{key}: delete: summary: Force-release a resource lease (operator recovery) operationId: forceReleaseResourceLease tags: [resources] description: >- ADMIN only (`admin` capability; otherwise `forbidden` with `scope: capability`, `required: admin`). Recovers a lease stuck by a crashed holder without waiting out the TTL (up to 24h) or disabling enforcement server-wide; this is the only recovery path now that the advance `overrideResourceLeases` flag is gone. WARN-logged with the acting principal's token id. Answers the response envelope: `data = {resourceKey, releasedCount}`. parameters: - name: key in: path required: true schema: type: string pattern: '^[a-z0-9][a-z0-9\-_./]*$' maxLength: 128 responses: "200": description: Envelope with ok=true; data is {resourceKey, releasedCount} content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "400": description: invalid_request envelope (field `key` fails the pattern or length) content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "401": $ref: "#/components/responses/Unauthorized" "503": $ref: "#/components/responses/KeySetUnavailable" "403": description: forbidden envelope (the token lacks `admin`, or a director-profile credential (detail.required director)) content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "404": description: >- not_found envelope with detail kind `lease`: no active lease exists on this key (a repeat call after a successful release is a 404, not a second 200) content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" /resources/leases/history: get: summary: Lease-interval audit history (who held resource R at time T) operationId: listResourceLeaseHistory tags: [resources] description: >- Append-only lease-interval audit log - answers "who held resource R at time T" after a lease has already been released, stolen, or force-released, which the current-holders-only /resources/leases list cannot. Closed intervals are pruned by RETENTION_LEASE_HISTORY_DAYS (default 365); open intervals never. Answers the response envelope: a list page, newest-first `(acquiredAt DESC, id ASC)`, with `page.total` the count of all matching intervals, `page.truncated` true while more remain and `page.next` the cursor for the next page. Item shape: `{resourceKey, holderItemId, acquiredByActorId?, acquiredAt, expiresAt, releasedAt?, releaseReason?, releasedByActorId?}`; the two actor ids are present only for ADMIN callers. Requires `read`. parameters: - name: key in: query required: false schema: type: string pattern: '^[a-z0-9][a-z0-9\-_./]*$' maxLength: 128 - name: at in: query required: false description: >- ISO-8601 instant. When present, returns every interval held at that instant (acquiredAt <= at < coalesce(releasedAt, expiresAt)). When absent, returns the most recent intervals. An unparsable value is invalid_request on field `at`. schema: type: string format: date-time - name: limit in: query required: false description: Integer from 1 to 200, default 50. Any other value is invalid_request on field `limit`. schema: type: integer minimum: 1 maximum: 200 default: 50 - name: cursor in: query required: false description: >- The previous page's `page.next` (an offset only, not bound to key/at). Absent is the first page; a malformed or empty value is invalid_cursor. schema: type: string responses: "200": description: Envelope with ok=true and a list page of lease intervals content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "400": description: invalid_request envelope (fields key, at or limit) or invalid_cursor envelope content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "401": $ref: "#/components/responses/Unauthorized" "503": $ref: "#/components/responses/KeySetUnavailable" "403": description: forbidden envelope (the token lacks `read`, or a director-profile credential (detail.required director)) content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" /info: get: summary: Server metadata and caller capabilities operationId: getInfo tags: [service] responses: "200": description: Ok envelope whose data is the service info content: application/json: schema: allOf: - $ref: "#/components/schemas/OpsEnvelope" - type: object properties: data: $ref: "#/components/schemas/ServiceInfoDto" "401": $ref: "#/components/responses/Unauthorized" "403": $ref: "#/components/responses/Forbidden" "422": description: config_invalid envelope (the stored server config head cannot be loaded) content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "503": description: >- unavailable envelope: the server config head cannot be read, or (jwks verifier) the credential's key set is unavailable (no WWW-Authenticate); retry after error.retryAfterMs content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" /health: get: summary: Health check — no authentication required operationId: healthCheck tags: [service] security: [] responses: "200": description: Healthy content: application/json: schema: $ref: "#/components/schemas/HealthDto" "503": description: Degraded — database unreachable content: application/json: schema: $ref: "#/components/schemas/HealthDto" /.well-known/mcp-task-orchestrator.json: servers: - url: / description: Mounted at the server root, not under /api/v1 get: summary: Service discovery document — no authentication required operationId: getWellKnown tags: [service] security: [] responses: "200": description: Service descriptor content: application/json: schema: $ref: "#/components/schemas/WellKnownDto" /events: get: summary: Server-Sent Events stream operationId: getEvents tags: [events] description: | Real-time SSE stream. Auth runs in a pre-flight plugin phase (before the SSE handler commits the 200 response). Requires read or admin capability. This route is exempted from the global auth plugin via publicPaths (matched against the request path only, not the full URI, so ?token= and other query strings still match) and honors API_AUTH_MODE=none + API_ALLOW_UNAUTHENTICATED=true (see api-rest.md §1) the same way the bearer route does — no token required when both opt-in keys are set. Browser clients cannot use native EventSource because it does not support custom headers. Use a fetch-based SSE library (e.g. @microsoft/fetch-event-source) with Authorization: Bearer, or enable API_ALLOW_QUERY_TOKEN_FOR_SSE=true for ?token= access. The stream is a projection of the durable events table (4.0, V20): event ids are the table's seq (above 10^12, monotonic, durable across restarts), writes from other processes sharing the database stream within about one second, and nothing a rolled-back write did is ever streamed. Rejections, lease, config and plan-document rows are table-only. Scope filtering: root scope (?root= intersected with principal.scope.rootIds) is applied identically to the live stream and to Last-Event-ID replay -- every row carries its root_id, so replay is not unfiltered. A root-scoped principal (non-null scope.rootIds) whose ?root= values do not intersect that scope gets 403 forbidden (scope root) before the SSE stream opens; any ?root= value that is not a UUID gets 400 invalid_request (Q32: a mix of valid and invalid values is rejected too). Every pre-flight body is the error envelope. A principal with scope.tags_include set is additionally filtered per event (live and replay alike), using the same ScopeGuard predicate as the tools and REST reads; see api-rest.md §21/§3. KNOWN LIMITATION: item.deleted is dropped for a tag-scoped connection (its tags can no longer be resolved once the item is gone) -- see api-rest.md section 24. A tags_include-scoped token additionally requires the route's WorkItemRepository wiring; if that is unavailable the pre-flight plugin rejects the connection with 403 forbidden (scope tag) rather than serving an unfiltered stream. Event ID namespace is independent from /mcp SSE channel. Do NOT reuse Last-Event-ID values across the two channels. parameters: - name: root in: query schema: type: string format: uuid description: Root-subtree filter (repeatable); intersected with principal scope - name: types in: query schema: type: string description: >- Comma-separated event type filter. Exempt: sync.lost and auth.expired (control events) are always delivered regardless of this filter. - name: token in: query schema: type: string description: Bearer token (only accepted when API_ALLOW_QUERY_TOKEN_FOR_SSE=true) - name: Last-Event-ID in: header schema: type: string description: >- Resume from this event ID (a seq); replay is read from the events table and filtered by root and tags_include the same way the live stream is, deduplicated against live delivery by id. API_SSE_BUFFER_SIZE (default 1000) is the replay window. When the id is not replayable -- more than the window behind the newest event (buffer_evicted), above the newest event, below the 10^12 seq floor (any pre-4.0 ring-buffer id; the floor itself is a valid start-of-log cursor), or unparsable (unknown_event_id) -- the server emits a sync.lost event with that reason as the first frame, then immediately replays the whole window after it (replay resumes from the sentinel's own id, max(10^12, newest - window), not the client's cursor -- no second reconnect needed). A blank or absent header is not a resume attempt and never triggers sync.lost. API_SSE_BUFFER_SIZE=0 means no replay: every resume behind the newest event yields buffer_evicted with no events to replay. responses: "200": description: SSE stream (text/event-stream) content: text/event-stream: schema: type: string description: | Each event: id:\nevent:\ndata:\n\n Event types: item.created, item.updated, item.deleted, item.advanced, note.upserted, note.deleted, note.ownership_transferred, dependency.added, dependency.removed, scope.entered, scope.left, run.opened, run.updated, run.paused, run.resumed, run.ended, run.marked, seat.ended, decision.raised, decision.acknowledged, decision.answered, decision.withdrawn, sync.lost, auth.expired ApiEvent JSON fields: id, event, itemId (null for sync.lost/auth.expired), modifiedAt, newRole (item.advanced only), actor ({id, kind, parent?}, the writer; domain events only; omitted when unknown, or for a non-admin caller when API_REDACT_NOTE_ATTRIBUTION is true; never proof/verification), rootId (depth-0 ancestor of the item; present on every domain event since 4.0, live and on replay; never redacted), runId (run.*, seat.ended and decision.* events; run.* carry no itemId), decisionId, class and severity (decision.* events only; a decision event never carries an actor), and reason -- set only on sync.lost, one of queue_overflow (per-connection queue overflowed), buffer_evicted (resumed Last-Event-ID further behind than the replay window), or unknown_event_id (resumed Last-Event-ID above the newest event, below the seq floor, or unparsable); null/absent on every other event type. auth.expired: sent and the stream closed when the connection's token expires (checked every API_SSE_AUTH_CHECK_INTERVAL_SECONDS). Fires for every JWKS session (exp is a required claim in jwks mode — a token with no exp is rejected at auth time, 401 unauthenticated). Does not fire for API_AUTH_MODE=none unauthenticated sessions or for a bearer token with no expires_at — neither has an expiry to watch. "400": description: >- Pre-flight validation failure: a ?root= value is not a UUID (invalid_request envelope, field root). content: application/json: schema: $ref: "#/components/schemas/OpsEnvelope" "401": $ref: "#/components/responses/Unauthorized" "503": $ref: "#/components/responses/KeySetUnavailable" "403": $ref: "#/components/responses/Forbidden"