# The data-plane /v1 contract, the twin of openapi.yaml's control-plane document. Pinned by
# packages/server/test/openapi-contract.test.ts, which asserts this document and
# packages/server/src/routes.ts describe the same route table, and that the handler
# actually routes everything the table declares — without that pair, "API as a product"
# degrades into documentation that lies (the control-plane spec §9.3 test 3 argument, verbatim).
#
# Scope, mirroring the control-plane document's own boundary note: only the client-facing
# surface. The handler also serves the workload lifecycle (/workloads — off unless the operator
# enables it, see docs/harness/how-to/workloads.md) and the deprecated pre-rename paths (/run-leaf,
# /run-leaf/status) — listed in src/routes.ts as surface: 'internal' and not described here.
# The unprefixed /turn and /runs ARE described: supported, frozen aliases of /v1/turn and /v1/runs
# (docs/reference/change-policy.md, decision 3; #507), whose request body and responses are $refs
# to the /v1 route's, so the two cannot drift apart here. /runs/status has no /v1 form; it is the
# canonical path.
openapi: 3.1.0
info:
  title: MOCA harness (data plane)
  version: 1.7.0
  description: |
    The agent execution tier: HTTP server and P6 workers that run turns and jobs against sandboxed
    workspaces. It is a separate deployable from the control plane, and a client that knows only
    the control-plane URL finds this one through `GET /v1/discovery` there (SH_PUBLIC_HARNESS_URL).

    Authentication is the control plane's session token (see the sessionToken scheme below). A
    deployment opts into requiring it with SH_REQUIRE_AUTH; a token that is PRESENT is verified
    and refused if bad in either mode. Two rules hold on every authenticated route:

      * THE TOKEN NAMES THE SESSION. token.sid must equal the request's sessionId — a token for
        another session is a 400 session_mismatch, never silently resolved (MU1 §4.3).
      * AN AUTHENTICATED CALLER MAY NOT NAME A TENANT. The session token alone scopes the work
        (MI1 R7); tenant remains available only to unauthenticated deployments, where it
        namespaces the session id. Enforced on the two routes that accept a tenant — /v1/runs
        (body) and /runs/status (query); /v1/turn reads only prompt, sessionId and detachable,
        so a tenant field there is inert, not refused.

    Detachable turns (#471, docs/specs/2026-10-09-turn-reattach-design.md) are a deployment
    opt-in, SH_TURN_DETACH=1: a turn whose life belongs to the harness rather than the
    connection, which a client re-attaches to (GET /v1/turn) and cancels (POST
    /v1/turn/cancel). With it off, both of those routes answer 404 turn_not_found and POST
    /v1/turn ignores `detachable`.

    UNPREFIXED ALIASES. POST /turn and POST /runs are aliases of POST /v1/turn and POST /v1/runs:
    the same handler, so the same auth, request body and responses. They are supported and frozen,
    with no removal date, and the change policy's notice rules apply to them as to any route. New
    features appear under /v1 only (the detachable-turn routes, GET /v1/turn and POST
    /v1/turn/cancel, have no unprefixed form), so a new client should use /v1.

    What changed in each version: docs/api/CHANGELOG.md (each data-plane version is noted in the
    control-plane section that shipped it).

security:
  - sessionToken: []
paths:
  /health:
    get:
      operationId: health
      summary: Liveness — answers `ok` with no dependencies
      description: |
        Deliberately touches nothing (no Redis, no keyset): a probe that depended on either
        would report a healthy harness as unready. This is the one route a client may call
        before it has any token.
      security: []
      responses:
        '200':
          description: ok
          headers:
            X-Moca-Version:
              description: |
                The deployment's version (MOCA_VERSION, baked in at image build), so a client can
                show it. Absent on a harness that predates advertising one; the body is unchanged
                either way.
              schema:
                type: string
          content:
            text/plain:
              schema:
                type: string
                enum: [ok]
  /v1/turn:
    post:
      operationId: createTurn
      summary: Run one agent turn — sync JSON, or an SSE frame stream
      description: |
        One conversational turn against a session's sandboxed workspace. Send `Accept:
        text/event-stream` for the streamed form; omit it for the sync form. The two run the
        same execution core and report the same facts (§3.4): a failure before the first frame
        is a real HTTP error byte-identical to the sync path's; a failure after streaming has
        begun degrades to a terminal `error` frame, since the status code is spent. Streaming
        begins at the first frame, or at SH_TURN_STREAM_FIRST_FRAME_FLUSH_MS (default 15000, 0
        disables) if none has come by then, so a proxy idle timeout cannot cut a slow first
        frame: a failure slower than that is an `error` frame, including a 503 that would have
        carried `Retry-After`.

        Authenticated turns run on the caller's exchanged credential, with the session's
        config bundle, sandbox tier and sandbox template taken from the control plane — never
        from the request (ADR-0038) — and create the session if absent. A session with a
        template runs only on workers serving it (and, pinned to a manifest-hash build, only on
        workers labelled moca.dev/build with that build), and a template's seed runs once in the
        session's workspace before the turn's first tool call; a session with none runs only
        on untemplated workers. Unauthenticated turns (SH_REQUIRE_AUTH
        off, no token) run on the operator's ambient credential: a named session must already
        exist (404 session_not_found otherwise), and an omitted sessionId starts a fresh one.

        `X-SH-Subject` is accepted only as a trusted-orchestrator convenience and REJECTED when
        it conflicts with the token's subject (spec §3.5) — a silent winner there is a
        cross-tenant bug waiting.

        DETACHABLE TURNS. `detachable: true` is honoured only when all three hold: the
        deployment runs with SH_TURN_DETACH=1, the request carries a session token the
        harness accepts, and it asks for SSE (`Accept: text/event-stream`). Otherwise the field
        is ignored and the turn behaves exactly as above. A detachable turn's stream differs in
        three ways: its first event is a `turn` frame (FrameTurn — its presence is the
        capability signal; there is no separate probe); every LOGGED frame carries an SSE
        `id: <turnId>:<entryId>`, the cursor GET /v1/turn resumes from; and closing the
        connection does NOT abort the turn. A frame is written to the turn's log before it is
        sent, so an id a client holds always names a logged entry. If that log write fails,
        the frame is still sent, but without an `id:` line, and a later attach may not replay
        it. The same holds once the turn has lost its lease or its log already holds a
        terminal: nothing is logged after the terminal. If an attach ended the turn with
        `owner_lost` while its owner was cut off, that `owner_lost` frame (with its id) is
        also the terminal the starting connection receives. A detached turn nobody watches is aborted
        after SH_TURN_DETACHED_MAX_S (default 1800), and its log is retained for
        SH_TURN_LOG_TTL_S (default 86400). A turn the harness ended itself carries the reason
        on its terminal `error` frame (`abortReason`). The lazy flush is unchanged except for
        its deadline: the session's one-live-turn lease is taken before the first frame, so a
        409 or 503 from it is still a real status code, and a failure before the first frame
        is the sync path's status and JSON. At SH_TURN_STREAM_FIRST_FRAME_FLUSH_MS the `turn`
        frame is written on its own, and a failure after that is an `error` frame.

        ONE LIVE TURN PER SESSION. With SH_TURN_DETACH=1, every /v1/turn — detachable or not —
        checks for a running detachable turn on its session before its first frame, and is
        refused 409 turn_in_progress while one runs. The check of a non-detachable turn is
        bounded and fails open: a Redis that cannot answer in time does not block it (the
        server logs each time it does).
        Non-detachable turns take no lease, so concurrent non-detachable turns behave as
        without the flag.
      security:
        - sessionToken: []
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/TurnRequest' }
      responses:
        '200':
          description: |
            The completed turn. Sync callers get the final result as JSON; stream callers get
            the same facts incrementally as frames.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TurnResult' }
            text/event-stream:
              schema:
                type: string
              description: |
                SSE. Each frame is `event: <frame.type>` + `data: <frame JSON>`; idle gaps are
                filled with `: keepalive` comments (invisible to EventSource). The frame
                vocabulary is TurnStreamFrame below — incremental text/thinking/tool frames,
                then exactly one terminal `done` or `error` frame. Client disconnect aborts the
                in-flight turn — except on a detachable turn, which opens with a `turn` frame,
                puts `id: <turnId>:<entryId>` before the `event:` line of every frame it logged
                (a frame whose log write failed is sent without one), and runs on when the
                client leaves.
        '400':
          description: |
            prompt_required (no prompt in the body) · invalid_json · read_error (the body never
            arrived whole) · session_mismatch (the token names another session) ·
            subject_conflict (X-SH-Subject contradicts the token) · credential_required ·
            credential_ambiguous · endpoint_unresolved (the control-plane exchange refused the
            caller's credential or its endpoint)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401':
          description: token_required (this deployment requires a token) · token_invalid · token_expired
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: |
            session_not_found — an unauthenticated turn named a session the backend does not
            have, or an authenticated turn's token names a session the control plane does not
            know: the exchange refuses it before the harness's own create-or-resume ever runs.
            credential_not_found — the token's subject has no resolvable credential there.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: |
            turn_in_progress — SH_TURN_DETACH=1 and the session already runs a detachable turn
            (one live turn per session). The body's `turnId` names the running turn, for
            GET /v1/turn or POST /v1/turn/cancel; it is omitted for an unauthenticated caller,
            which holds no token for the session.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TurnConflict' }
        '410':
          description: config_bundle_not_found — the session's promoted bundle digest is gone
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '422':
          description: |
            config_bundle_unsupported — the session's promoted bundle is stored and intact, but its
            format (format.json) is newer than this harness reads, or its marker is not a format
            version. The message says which, and what to upgrade. Not retryable as-is: the turn
            succeeds once the harness is upgraded to a release that reads that format.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '429':
          description: |
            subject_quota_exceeded — the authenticated subject already holds
            SH_TURNS_PER_SUBJECT in-flight turns on this worker (default half the per-worker
            turn cap), counting the subject's running QUEUED turns as well as its interactive
            ones: one owner's async fan-out and its /turn traffic share one per-subject budget
            (#391), so a caller can be refused here while its own queued leaves are running.
            Distinct from the supervisor's pre-hand-off `overloaded` 429, which has
            no error body: this one names the caller's own share, so a client can tell "you are
            over your share" from "the host is full". Carries Retry-After. No quota is
            configured (neither SH_TURNS_PER_SUBJECT nor SH_TURNS_PER_WORKER set) or the caller
            is unauthenticated ⇒ this response does not occur.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '503':
          description: |
            Retryable, from one of three causes: no sandbox capacity right now (every candidate
            is at its cap, none is present yet — none of the session's tier or template, say —
            or the session's own sandbox is briefly absent — sandbox_unavailable, whose message
            names the cause: a pool, tier, template or sandbox id, never a secret), the
            control-plane credential exchange failed
            (credential_unavailable — the control plane is unreachable or its answer was
            unusable), or a detachable turn could not take its lease because Redis did not
            answer, or did not answer within SH_TURN_REGISTRY_TIMEOUT_MS (default 5000) —
            redis_unavailable. The turn can succeed unmodified on a retry.
          headers:
            Retry-After:
              schema: { type: integer }
              description: seconds to wait before retrying
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '500':
          description: |
            internal_error — not retryable as-is; among its causes, a sandbox template's seed
            that failed (its output is in the workspace's .moca-seed.log)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
    get:
      operationId: attachTurn
      summary: Re-attach to a session's detachable turn — SSE replay from a cursor, then live
      description: |
        Resolves the session's current turn — the running detachable turn, or else the last one
        whose log is still retained — and streams it as SSE, in the same framing as a detachable
        POST /v1/turn: `id: <turnId>:<entryId>`, `event: <frame.type>`, `data: <frame JSON>`,
        with `: keepalive` comments in idle gaps.

        The stream opens with a `turn` frame (FrameTurn). If `Last-Event-ID` names this turn,
        the replay is the entries after that cursor, and the `turn` frame's id is the cursor
        itself, so a reconnect straight after it resumes in place. A cursor naming another
        turn, or none, replays the turn from its first entry. A cursor older than the first
        retained entry (the log was trimmed) sets `truncated: true`, and replay starts at the
        first retained entry. After the replay the stream follows the live turn until its
        terminal `done` or `error` frame, and then ends.

        A finished turn replays to its terminal frame and ends at once. A cursor at or past a
        finished turn's terminal gets only the `turn` frame, with `ended: true`, and the stream
        ends: the client is already caught up and must not read the end as a drop. A turn whose
        owning harness process stopped is ended by the attach itself, with an `error` frame
        carrying `abortReason: owner_lost`. If following fails mid-stream, the response ends
        without a terminal frame; reconnect with the last id received.

        While connected, the attach counts as watching the turn, so a watched turn is never
        aborted as unwatched. A token is REQUIRED here in every mode — 401 token_required
        without one — and it must name the session; no credential is exchanged (the
        GET /runs/status rule). With SH_TURN_DETACH off, every authorized attach answers 404
        turn_not_found.
      security:
        - sessionToken: []
      parameters:
        - name: sessionId
          in: query
          required: true
          schema: { type: string }
          description: The session whose turn to attach to; must be the token's `sid`.
        - name: Last-Event-ID
          in: header
          required: false
          schema: { type: string }
          description: |
            Optional cursor, `<turnId>:<entryId>` — the last SSE `id` the client received.
            Absent, or naming another turn, means replay from the turn's start.
      responses:
        '200':
          description: The turn's frames — the replay, then the live tail to its terminal.
          content:
            text/event-stream:
              schema:
                type: string
              description: |
                SSE of TurnStreamFrame, every frame with `id: <turnId>:<entryId>`. First a
                `turn` frame; then the replay and live frames; then exactly one terminal `done`
                or `error` frame — unless the `turn` frame says `ended: true`, in which case it
                is the only frame.
        '400':
          description: sessionId_required · session_mismatch (the token names another session)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401':
          description: token_required (required on this route in every mode) · token_invalid · token_expired
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: |
            turn_not_found — the session has no running or retained turn, or this deployment
            does not run detachable turns (SH_TURN_DETACH off).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '503':
          description: |
            Retryable: redis_unavailable — the turn registry could not be read before the stream
            began, or did not answer within SH_TURN_REGISTRY_TIMEOUT_MS (default 5000). Or
            credential_unavailable — the token keyset became unusable under an already-serving
            pod.
          headers:
            Retry-After:
              schema: { type: integer }
              description: seconds to wait before retrying
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '500':
          description: internal_error — not retryable as-is
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/turn/cancel:
    post:
      operationId: cancelTurn
      summary: Cancel a session's running detachable turn
      description: |
        Asks the harness running the session's detachable turn to abort it. The turn ends
        through its normal path: a terminal `error` frame with `abortReason: cancelled` reaches
        the log and every attached watcher, so the cancelling client learns of the end by
        watching the turn, not from this response. When no turn is running, the cancel is a
        no-op that still answers 202, naming the session's LAST retained turn.

        Pass `turnId` to make the cancel conditional, so a stale cancel cannot kill a newer
        turn: if the running turn is another one, the answer is 409 turn_mismatch and nothing
        is cancelled. The `turnId` is compared only against a RUNNING turn. When none is
        running, the 202 names the last turn, which may not be the one the caller sent. A
        client sending a conditional cancel should compare the two ids: a different id means
        its own turn had already ended, and nothing was cancelled. The 202's `outcome` says
        the same for any cancel: `requested` for a running turn, `ended` for a no-op.

        A cancel without `turnId` is fenced by the time the harness received it: a turn that
        began more than 2 s after that counts as not running, so the cancel is a no-op even when
        it reaches Redis late (after its caller timed out and began another turn).

        A token is REQUIRED here in every mode — 401 token_required without one — and it must
        name the session. With SH_TURN_DETACH off, every authorized cancel answers 404
        turn_not_found.
      security:
        - sessionToken: []
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CancelTurnRequest' }
      responses:
        '202':
          description: |
            The cancel was requested of the running turn, and `turnId` names it. Or no turn is
            running, and `turnId` names the session's last retained turn (a no-op). In the second
            case the id need not equal the request's `turnId`. `outcome` tells the two apart:
            `requested` for a running turn asked to stop, `ended` for a retained turn that had
            already ended (nothing was cancelled). Older harnesses omit `outcome`.
          content:
            application/json:
              schema:
                type: object
                required: [turnId]
                properties:
                  turnId: { type: string }
                  outcome:
                    type: string
                    enum: [requested, ended]
        '400':
          description: |
            invalid_json (the body is not a JSON object) · sessionId_required · session_mismatch
            (the token names another session)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401':
          description: token_required (required on this route in every mode) · token_invalid · token_expired
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: |
            turn_not_found — the session has no running or retained turn, or this deployment
            does not run detachable turns (SH_TURN_DETACH off).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: |
            turn_mismatch — `turnId` was given and names a turn other than the running one;
            the body's `turnId` names the running turn. Nothing was cancelled.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TurnConflict' }
        '503':
          description: |
            Retryable: redis_unavailable — the turn registry failed, or did not answer within
            SH_TURN_REGISTRY_TIMEOUT_MS (default 5000). Or
            credential_unavailable — the token keyset became unusable under an already-serving
            pod.
          headers:
            Retry-After:
              schema: { type: integer }
              description: seconds to wait before retrying
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '500':
          description: internal_error — not retryable as-is
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /turn:
    post:
      operationId: createTurnUnversioned
      summary: Supported unversioned alias of POST /v1/turn
      description: |
        The pre-/v1 path of POST /v1/turn, kept indefinitely as a supported, frozen alias
        (docs/reference/change-policy.md, decision 3). It runs the same handler, so everything
        POST /v1/turn documents holds here: the same session-token rules, the same body (including
        `detachable`), the same sync and SSE answers and the same errors. Frozen means new features
        are added under /v1 only; the detachable-turn routes (GET /v1/turn, POST /v1/turn/cancel)
        have no unprefixed form. Not deprecated: removing it would need the same notice as any
        route. A new client should call POST /v1/turn.
      security:
        - sessionToken: []
      requestBody: { $ref: '#/paths/~1v1~1turn/post/requestBody' }
      responses:
        '200': { $ref: '#/paths/~1v1~1turn/post/responses/200' }
        '400': { $ref: '#/paths/~1v1~1turn/post/responses/400' }
        '401': { $ref: '#/paths/~1v1~1turn/post/responses/401' }
        '404': { $ref: '#/paths/~1v1~1turn/post/responses/404' }
        '409': { $ref: '#/paths/~1v1~1turn/post/responses/409' }
        '410': { $ref: '#/paths/~1v1~1turn/post/responses/410' }
        '422': { $ref: '#/paths/~1v1~1turn/post/responses/422' }
        '429': { $ref: '#/paths/~1v1~1turn/post/responses/429' }
        '503': { $ref: '#/paths/~1v1~1turn/post/responses/503' }
        '500': { $ref: '#/paths/~1v1~1turn/post/responses/500' }
  /v1/runs:
    post:
      operationId: createRun
      summary: 'Run a leaf/solve/prompt job synchronously'
      description: |
        The job mode of the data plane: a self-contained unit of agent work (review one finding,
        solve one problem, answer one prompt) rather than a conversational turn. The `kind`
        discriminator picks the shape; absent or `converge` means the leaf (finding-review)
        shape.

        On pool saturation the sync path bounded-waits with backoff before answering 503, and a
        503 is never persisted — `/runs/status` must not report a retryable refusal as a
        terminal failure.

        `async: true` is removed and stays removed: it went with the Knative/KEDA deployment path
        (ADR-0041), whose KEDA drainer consumed the queue, and is answered 400 async_removed. This
        route is not restored (#687) — it is unauthenticated when `SH_REQUIRE_AUTH` is off. Its
        replacement is the authenticated `POST /v1/sessions/{id}/turns` with `async: true`
        (ADR-0047, #686), which has shipped.

        A client disconnect does not cancel the run: it finishes and persists its result record,
        which `GET /runs/status` serves afterwards, so submit-then-poll is supported here. This is
        permanent, not interim (ADR-0028). `POST /v1/turn` is the opposite and aborts on
        disconnect, unless the turn is detachable (see DETACHABLE TURNS below, which is the one
        `/turn` that outlives its client). A run that must survive a worker restart belongs on
        async turns, which have redelivery.

        `sandboxPoolSelector` is internal routing state and is deleted at the request boundary —
        never settable by an external caller. A synchronous prompt run naming a `workloadId` runs
        with that workload's frozen context, which Moca copies read-only into the sandbox; the
        session token's user must own the workload (docs/harness/how-to/workloads.md). With workloads off
        it is refused with 501 workload_runs_unavailable rather than run on the default pool; a
        synchronous one without a token is 401 token_required.
        `contextWritable: true` gives that run its own writable copy of the context instead,
        discarded when the run ends. A workload created with `sandboxes` runs only on its own
        sandboxes, never on the shared pool. One created with `workspace.mount` as well has its
        context mounted there instead of copied: the run starts in it, and `contextWritable: true`
        gives a `read-only` mount's run its own copy and changes nothing on a `writable` one.
      security:
        - sessionToken: []
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/RunEnvelope' }
      responses:
        '200':
          description: The completed job (sync execution).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/LeafResult' }
        '400':
          description: |
            envelope_invalid (the body matches no run shape) · configRef_invalid (an empty
            configRef is a well-formed envelope making an unsatisfiable request, so the error
            names the field) · async_removed (async: true — removed with the Knative/KEDA path,
            ADR-0041) · tenant_not_allowed (an authenticated caller named a tenant) ·
            session_mismatch · subject_conflict · credential_required · credential_ambiguous ·
            endpoint_unresolved (the control-plane exchange refused the caller's credential or
            its endpoint) · workload_run_requires_prompt (a run naming a workloadId must be a
            prompt run) · context_writable_invalid (contextWritable is not a boolean) ·
            context_writable_requires_workload (contextWritable true without a workloadId)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401':
          description: token_required · token_invalid · token_expired
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: |
            session_not_found / credential_not_found — the control-plane exchange refused the
            token's session or subject. workload_not_found — the named workload does not exist
            or belongs to another user.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: workload_not_ready — the named workload is not ready (not yet activated, or its own sandboxes are still provisioning).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '501':
          description: |
            workload_runs_unavailable — the envelope named a workloadId, but workloads are off.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '503':
          description: |
            Retryable, from one of three causes — note the two body shapes. Saturation: still
            no pool capacity after the bounded wait; the body is the LeafResult failed/saturated
            branch, NOT an Error, and is never persisted. Or credential_unavailable — the
            control-plane exchange failed (an Error body). Or workload_sandbox_unavailable — the
            run names a workload with sandboxes of its own and none of them is attached (an
            Error body, never persisted); it never falls back to the shared pool.
          headers:
            Retry-After:
              schema: { type: integer }
              description: seconds to wait before retrying
          content:
            application/json:
              schema:
                oneOf:
                  - type: object
                    description: The saturated LeafResult branch — a 503 is "retry", not a terminal failure.
                    required: [status, reason]
                    properties:
                      status: { type: string, enum: [failed] }
                      reason: { type: string, enum: [saturated] }
                  - $ref: '#/components/schemas/Error'
        '500':
          description: |
            internal_error — not retryable as-is. workloads_misconfigured — the run named a
            workloadId, but the operator's Context Service settings are missing or unsafe
            (docs/harness/how-to/workloads.md).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /runs:
    post:
      operationId: createRunUnversioned
      summary: Supported unversioned alias of POST /v1/runs
      description: |
        The pre-/v1 path of POST /v1/runs, kept indefinitely as a supported, frozen alias
        (docs/reference/change-policy.md, decision 3). It runs the same handler, so everything
        POST /v1/runs documents holds here: the same session-token and tenant rules, the same job
        shapes and the same answers and errors. Frozen means new features are added under /v1
        only. Not deprecated: removing it would need the same notice as any route (the
        deprecated /run-leaf is a different path). A new client should call POST /v1/runs.
      security:
        - sessionToken: []
      requestBody: { $ref: '#/paths/~1v1~1runs/post/requestBody' }
      responses:
        '200': { $ref: '#/paths/~1v1~1runs/post/responses/200' }
        '400': { $ref: '#/paths/~1v1~1runs/post/responses/400' }
        '401': { $ref: '#/paths/~1v1~1runs/post/responses/401' }
        '404': { $ref: '#/paths/~1v1~1runs/post/responses/404' }
        '409': { $ref: '#/paths/~1v1~1runs/post/responses/409' }
        '501': { $ref: '#/paths/~1v1~1runs/post/responses/501' }
        '503': { $ref: '#/paths/~1v1~1runs/post/responses/503' }
        '500': { $ref: '#/paths/~1v1~1runs/post/responses/500' }
  /runs/status:
    get:
      operationId: getRunStatus
      summary: Poll a run by session id
      description: |
        Reads the result record a run wrote. A missing record is `queued`, not an error:
        polling is the contract, and "not finished yet" is a normal answer. No credential is
        exchanged — a status read spends nothing upstream — but the same token rules as a turn
        apply (MI1 §5 R7): required under SH_REQUIRE_AUTH, verified when present, and the token
        must name the polled session.
      security:
        - sessionToken: []
      parameters:
        - name: sessionId
          in: query
          required: true
          schema: { type: string }
          description: The run's session id — the same one the accepted run echoed back.
        - name: tenant
          in: query
          required: false
          schema: { type: string }
          description: |
            Unauthenticated deployments only, where it namespaces the session id. An
            authenticated caller passing tenant gets 400 tenant_not_allowed (MI1 R7).
      responses:
        '200':
          description: The run's current status — see RunStatus for the shapes.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/RunStatus' }
        '400':
          description: sessionId_required · tenant_not_allowed · session_mismatch (the token names another session)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401':
          description: token_required · token_invalid · token_expired
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '503':
          description: |
            credential_unavailable — the token keyset became unusable under an already-serving
            pod. No credential exchange runs on a status read, so this is the only 503 here; an
            operator fix, not a retry, resolves it.
          headers:
            Retry-After:
              schema: { type: integer }
              description: seconds to wait before retrying
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '500':
          description: internal_error — not retryable as-is
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
components:
  securitySchemes:
    sessionToken:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: |
        Ed25519 (`alg: EdDSA`) JWT minted by the control plane at `POST /v1/sessions/{id}/token`
        — scope `turn:write`, claim `sid` naming the session, 5-minute TTL. No credential
        travels in the token; the data plane exchanges it with the control plane per turn, and
        that exchange can refuse the caller with the control plane's own codes (token_expired,
        credential_*, endpoint_unresolved, session_not_found) or, for any other exchange fault
        — control plane unreachable, an unusable answer — 503 credential_unavailable. The
        per-route response lists name every code.
        Required on every route here when the deployment sets SH_REQUIRE_AUTH; verified, and
        refused if bad, whenever presented in either mode.
  schemas:
    Error:
      type: object
      required: [error]
      properties:
        error:
          type: string
          description: |
            A stable machine-readable code; the codes this document names in each response
            description are the contract. The routes never put exception text here — a failure
            no route could classify answers internal_error, with its text in the server log only.
        message:
          type: string
          description: |
            Operator-facing detail; never parse it. Absent on internal_error — an unclassified
            failure's text can carry connection strings or credentials, and this body reaches an
            arbitrary caller (the control-plane document's rule).
        sessionId:
          type: string
          description: Echoed when the request named a session.
    TurnRequest:
      type: object
      required: [prompt]
      properties:
        prompt:
          type: string
          description: The user turn to run.
        sessionId:
          type: string
          description: |
            The session to run the turn in. When a token is presented this must be the token's
            `sid` (400 session_mismatch otherwise) and may be omitted — the token alone names
            the session. An unauthenticated caller may also omit it: a fresh session is then
            created and its id minted. A supplied id must already exist — 404
            session_not_found otherwise.
        detachable:
          type: boolean
          description: |
            Ask for a detachable turn. Honoured only with SH_TURN_DETACH=1, a session token,
            and `Accept: text/event-stream`; otherwise ignored, and the turn runs exactly as
            without it. See POST /v1/turn.
    CancelTurnRequest:
      type: object
      required: [sessionId]
      properties:
        sessionId:
          type: string
          description: The session whose running turn to cancel; must be the token's `sid`.
        turnId:
          type: string
          description: |
            Cancel only if this is the running turn — 409 turn_mismatch otherwise. Absent
            cancels whichever turn is running.
    TurnConflict:
      type: object
      required: [error]
      description: A 409 on a detachable-turn route.
      properties:
        error:
          type: string
          enum: [turn_in_progress, turn_mismatch]
        turnId:
          type: string
          description: |
            The session's running turn. Always present on turn_mismatch; on turn_in_progress,
            absent for an unauthenticated caller.
    TurnResult:
      type: object
      required: [sessionId, response, stopReason]
      properties:
        sessionId: { type: string }
        response: { type: string }
        stopReason: { type: string }
        errorMessage: { type: string }
        budgetExceeded:
          type: boolean
          description: |
            `true` when the turn's token cap was reached and tool calls were refused from then on
            (#391). Reported because the loop itself stops with `stopReason: "end_turn"` in that
            case, so the cap firing is otherwise invisible to the caller. Absent when it did not.
        usage: { $ref: '#/components/schemas/LeafUsage' }
        sandbox: { $ref: '#/components/schemas/TurnPlacement' }
        workspace: { $ref: '#/components/schemas/TurnWorkspace' }
    TurnPlacement:
      type: object
      description: Where the turn ran; `workspaceReset` explains why earlier files are gone.
      properties:
        id: { type: string }
        tier: { type: string }
        seed:
          type: object
          description: |
            A seeded template's seed origin (session-templates spec §5): `build`, the pinned
            build's own `spec.seed` in the control plane's template store (`buildId` names it), or
            `declared`, the deployment's SH_SANDBOX_TEMPLATES. Absent when no seed applies.
          required: [source]
          properties:
            source: { type: string, enum: [build, declared] }
            buildId: { type: string, pattern: '^sha256:[0-9a-f]{64}$' }
        workspaceReset:
          type: object
          description: |
            Why the session's earlier files are gone — the tier is `sandbox.tier` above (and on
            the SSE frame). `detached`: the session's sandbox `from` is gone and the session moved.
            `retiered`: the sandbox now serves another tier or sandbox template. `reclaimed`: the
            session is still on `from`, but its workspace there no longer holds the harness's
            marker file, most often because the worker reclaimed the idle workspace
            (SH_WORKSPACE_IDLE). Clients ignore a reason they do not know.
          properties:
            from: { type: string }
            reason: { type: string, enum: [detached, retiered, reclaimed] }
    TurnWorkspace:
      type: object
      description: |
        A templated session's workspace after the turn (session-templates spec §5.1), taken in
        the turn's sandbox before its lease is returned: `git diff --cached --binary` from the
        seed's baseline commit to everything in the workspace now, staged in a throwaway index
        (Moca's own files left out: `.moca-*`, `.sh-config*` and `leaves/*/.sh-config`), with
        `a/` and `b/` prefixes, no color and no renames whatever the workspace's git config says,
        so it applies with `git apply`. Present on every templated turn that leased its
        sandbox; a failed capture is `error` alone and never fails the turn.
      properties:
        baseline:
          type: string
          description: The commit the seed left the workspace at (`.moca-baseline`), else HEAD.
        patch:
          type: string
          description: The whole diff, when it is valid UTF-8. Never truncated.
        patchBase64:
          type: string
          description: The whole diff as base64, in place of `patch`, when it is not valid UTF-8.
        patchSha256:
          type: string
          description: '`sha256:<hex>` of the diff bytes.'
        patchBytes: { type: integer, description: The diff's length in bytes. }
        diffstat:
          type: object
          description: |
            What the diff changes, so a caller can judge it without fetching it. Counted from the
            diff's hunks, so a binary-only change reports its file count with no changed lines.
            Present whenever the capture succeeded, `patchRefused` included — there it is the only
            description of the patch a caller gets.
          required: [files, insertions, deletions]
          properties:
            files: { type: integer }
            insertions: { type: integer }
            deletions: { type: integer }
        patchRefused:
          type: string
          enum: [too_large]
          description: |
            The diff is over SH_TURN_PATCH_MAX_BYTES (default 4 MiB, at most the transport's
            8 MiB output cap): `patch` is left out, never cut.
        error:
          type: string
          description: |
            Why no patch was taken (no baseline commit, a baseline that is not a full commit id,
            a failed exec).
    LeafUsage:
      type: object
      description: Cumulative token usage, for run cost pricing.
      required: [input, output, cacheRead, cacheWrite, total]
      properties:
        input: { type: integer }
        output: { type: integer }
        cacheRead: { type: integer }
        cacheWrite: { type: integer }
        total: { type: integer }
    # The SSE frame vocabulary of POST /v1/turn (harness/src/turn-stream.ts). A discriminated
    # union on `type`; old clients ignore unknown types, so this list only grows.
    TurnStreamFrame:
      oneOf:
        - $ref: '#/components/schemas/FrameTurn'
        - $ref: '#/components/schemas/FrameText'
        - $ref: '#/components/schemas/FrameThinking'
        - $ref: '#/components/schemas/FrameToolUse'
        - $ref: '#/components/schemas/FrameToolResult'
        - $ref: '#/components/schemas/FrameWorkspaceReset'
        - $ref: '#/components/schemas/FrameDone'
        - $ref: '#/components/schemas/FrameError'
    FrameTurn:
      type: object
      required: [type, turnId, sessionId]
      description: |
        Detachable turns only: the first event of a detachable POST /v1/turn stream and of every
        GET /v1/turn attach, naming the turn its frame ids belong to. Not terminal. A client
        that never asks for a detachable turn never sees it.
      properties:
        type: { type: string, enum: [turn] }
        turnId:
          type: string
          description: The turn's id (a UUID), the first half of every frame's SSE id.
        sessionId: { type: string }
        truncated:
          type: boolean
          description: |
            Attach only: the client's cursor is older than the first retained log entry (the
            log was trimmed); replay starts at the first retained entry, so frames were lost.
        ended:
          type: boolean
          description: |
            Attach only: the cursor is at or past this finished turn's terminal frame. Nothing
            follows; the stream ends after this frame.
    FrameText:
      type: object
      required: [type, delta]
      properties:
        type: { type: string, enum: [text] }
        delta: { type: string, description: Assistant-text token. }
    FrameThinking:
      type: object
      required: [type, delta]
      properties:
        type: { type: string, enum: [thinking] }
        delta: { type: string, description: Reasoning token; may never fire. }
    FrameToolUse:
      type: object
      required: [type, id, name, args]
      properties:
        type: { type: string, enum: [tool_use] }
        id: { type: string }
        name: { type: string }
        args:
          description: The tool call's arguments, verbatim (fidelity B).
    FrameToolResult:
      type: object
      required: [type, id, isError, preview]
      properties:
        type: { type: string, enum: [tool_result] }
        id: { type: string }
        isError: { type: boolean }
        preview:
          type: string
          description: The clipped result — no transport ever sees the untruncated form.
    FrameWorkspaceReset:
      type: object
      required: [type, sessionId, from, tier, reason]
      description: |
        First frame of a turn whose workspace is not the one the session's previous turn left,
        so the user learns at the turn itself why earlier files are gone: its sandbox is not the
        one the previous turn used (`detached`, `retiered`; P6.3), or it is, but the workspace
        there lost the session's marker (`reclaimed`, #338). `from` is the sandbox the files
        were on; for `reclaimed` that is the turn's own sandbox (empty when the turn has none to
        name). The model is told as well, in a message of its own beside the turn's prompt,
        which is left as sent.
      properties:
        type: { type: string, enum: [workspace_reset] }
        sessionId: { type: string }
        from: { type: string }
        tier: { type: string }
        reason: { type: string, enum: [detached, retiered, reclaimed] }
    FrameDone:
      type: object
      required: [type, sessionId, stopReason]
      description: The terminal success frame, derived from the same TurnResult a sync caller reads.
      properties:
        type: { type: string, enum: [done] }
        sessionId: { type: string }
        stopReason: { type: string }
        usage: { $ref: '#/components/schemas/LeafUsage' }
        sandbox: { $ref: '#/components/schemas/TurnPlacement' }
        workspace: { $ref: '#/components/schemas/TurnWorkspace' }
    FrameError:
      type: object
      required: [type, sessionId, stopReason]
      description: The terminal failure frame — also how post-first-frame errors are reported.
      properties:
        type: { type: string, enum: [error] }
        sessionId: { type: string }
        stopReason: { type: string }
        errorMessage: { type: string }
        budgetExceeded:
          type: boolean
          description: |
            `true` when the turn's token cap was reached and tool calls were refused from then on
            (#391). Reported because the loop itself stops with `stopReason: "end_turn"` in that
            case, so the cap firing is otherwise invisible to the caller. Absent when it did not.
        usage: { $ref: '#/components/schemas/LeafUsage' }
        sandbox: { $ref: '#/components/schemas/TurnPlacement' }
        workspace: { $ref: '#/components/schemas/TurnWorkspace' }
        abortReason:
          type: string
          enum: [cancelled, unwatched, restarting, lease_lost, owner_lost]
          description: |
            Detachable turns only: present when the harness, not the turn, ended it —
            cancelled (POST /v1/turn/cancel) · unwatched (no client attached for
            SH_TURN_DETACHED_MAX_S) · restarting (the worker is draining) · lease_lost (the
            owner could not renew the turn's lease) · owner_lost (the process running the turn
            stopped; written by an attach). `errorMessage` then carries a human-readable form.
    # The POST /v1/runs body: one of three job shapes sharing a set of optional controls.
    # Discriminated by `kind` — absent (or 'converge') means the leaf shape.
    RunEnvelope:
      oneOf:
        - $ref: '#/components/schemas/LeafJob'
        - $ref: '#/components/schemas/SolveJob'
        - $ref: '#/components/schemas/PromptJob'
    RunOptions:
      type: object
      description: Controls shared by every run shape.
      properties:
        model: { type: string }
        provider: { type: string }
        maxTurns: { type: integer }
        async:
          type: boolean
          description: |
            Removed with the Knative/KEDA path (ADR-0041); answered 400 async_removed. Permanently
            removed, not pending restoration — the replacement is the authenticated
            POST /v1/sessions/{id}/turns (ADR-0047, #686).
        tenant:
          type: string
          description: Unauthenticated deployments only; namespaces the session id.
        configRef:
          type: string
          description: Digest of a promoted Claude Code config bundle (sha256:…). Absent ⇒ none.
        repoUrl: { type: string, description: Git remote to converge the sandbox repo copy from. }
        ref: { type: string, description: Commit/branch/tag the leaf's worktree is pinned to. }
        workspaceRef:
          { type: string, description: Derived from the worktree when repoUrl+ref are given. }
    LeafJob:
      allOf:
        - $ref: '#/components/schemas/RunOptions'
        - type: object
          required: [sessionId, item]
          properties:
            kind:
              type: string
              enum: [converge]
              description: Absent means this shape.
            sessionId: { type: string }
            item: { $ref: '#/components/schemas/LeafItem' }
            decision:
              type: object
              description: Resume/approve only — answers a paused run's gate.
    SolveJob:
      allOf:
        - $ref: '#/components/schemas/RunOptions'
        - type: object
          required: [sessionId, kind, problemStatement, repoUrl, ref]
          properties:
            kind: { type: string, enum: [solve] }
            sessionId: { type: string }
            problemStatement: { type: string, description: The task the agent must implement. }
            repoUrl: { type: string }
            ref: { type: string }
            env_key:
              type: string
              description: swebench solve only — triggers the contained swebench-setup path.
    PromptJob:
      allOf:
        - $ref: '#/components/schemas/RunOptions'
        - type: object
          required: [sessionId, kind, prompt]
          properties:
            kind: { type: string, enum: [prompt] }
            sessionId: { type: string }
            prompt: { type: string, description: The free-form prompt to run. }
            workloadId:
              type: string
              description: Run on this workload's frozen context. Synchronous runs only.
            contextWritable:
              type: boolean
              description: |
                Give the run its own writable copy of the workload's context, discarded when the
                run ends, instead of a read-only view. true needs workloadId; false is ignored.
    LeafItem:
      type: object
      required: [item_id, file, pattern]
      properties:
        item_id: { type: string }
        file:
          type: string
          description: Absolute path in the sandbox workspace — the agent reads exactly this.
        pattern:
          { type: string, description: The pattern of interest to review the finding against. }
        require_approval: { type: boolean }
    Verdict:
      type: object
      required: [item_id, verdict, reason]
      properties:
        item_id: { type: string }
        verdict: { type: string, enum: [FLAGGED, CLEAR] }
        reason: { type: string }
    LeafResult:
      oneOf:
        - type: object
          required: [status, verdict]
          properties:
            status: { type: string, enum: [done] }
            verdict: { $ref: '#/components/schemas/Verdict' }
        - type: object
          required: [status, gateId, gate]
          properties:
            status: { type: string, enum: [paused] }
            gateId: { type: integer }
            gate:
              type: object
              required: [summary, proposed_action]
              properties:
                summary: { type: string }
                proposed_action: { type: string }
        - type: object
          required: [status]
          properties:
            status: { type: string, enum: [aborted] }
        - type: object
          required: [status, patch]
          properties:
            status: { type: string, enum: [solved] }
            patch: { type: string }
            usage: { $ref: '#/components/schemas/LeafUsage' }
            workspace:
              description: |
                A descriptor of the patch in `patch` — `baseline`, `patchSha256`, `patchBytes`,
                `diffstat` — so a caller can apply it against the commit it was taken from.
                Absent when the capture printed no baseline. The bytes stay in `patch`; this
                never repeats them.
              $ref: '#/components/schemas/TurnWorkspace'
        - type: object
          required: [status, text]
          properties:
            status: { type: string, enum: [responded] }
            text: { type: string }
            usage: { $ref: '#/components/schemas/LeafUsage' }
            seed:
              description: |
                A templated session's prompt run only: the seed's origin (session-templates spec
                §5.2), as `TurnPlacement.seed`.
              type: object
              required: [source]
              properties:
                source: { type: string, enum: [build, declared] }
                buildId: { type: string, pattern: '^sha256:[0-9a-f]{64}$' }
            workspace: { $ref: '#/components/schemas/TurnWorkspace' }
        - type: object
          required: [status, reason]
          properties:
            status: { type: string, enum: [failed] }
            reason:
              type: string
              enum: [no_verdict, invalid_verdict, bad_inputs, error, saturated, budget]
              description: |
                `budget` (#391): the turn spent a cap its caller set -- its token cap, or the wall
                clock the control plane anchored at dequeue -- and the leaf was stopped. Terminal
                like the other deterministic reasons; only `error` and `saturated` are retried.
            message: { type: string }
    RunStatus:
      oneOf:
        - type: object
          required: [status]
          description: No result record yet — keep polling.
          properties:
            status: { type: string, enum: [queued] }
        - type: object
          required: [status, verdict]
          properties:
            status: { type: string, enum: [done] }
            verdict: { $ref: '#/components/schemas/Verdict' }
        - type: object
          required: [status, patch]
          properties:
            status: { type: string, enum: [solved] }
            patch: { type: string }
        - type: object
          required: [status]
          properties:
            status: { type: string, enum: [paused] }
            gateId: { type: integer }
            gate:
              type: object
              properties:
                summary: { type: string }
                proposed_action: { type: string }
        - type: object
          required: [status]
          properties:
            status: { type: string, enum: [failed] }
            reason: { type: string }
        - type: object
          required: [status, text]
          properties:
            status: { type: string, enum: [responded] }
            text: { type: string }
        - type: object
          required: [status]
          description: A run whose execution was aborted — persisted, so it polls back like any other outcome.
          properties:
            status: { type: string, enum: [aborted] }
      description: |
        A status not in this list passes through verbatim as `{ status }` — the record's own
        status wins over an enum here, so a new server status reads as unknown, not as an error.
