# The MU1 /v1 contract, delivered as a product surface rather than as prose
# (spec §4). Pinned by packages/control-plane/test/openapi-contract.test.ts, which
# asserts this document and src/routes.ts describe the same route table -- without
# it, "API as a product" degrades into documentation that lies (spec §9.3 test 3).
#
# Two conventions this document follows (spec §4.1):
#   * THE PRINCIPAL IS NEVER IN A PATH. /v1/sessions means MY sessions, derived
#     from the token. Admin listing is ?owner=<subject>, gated on a role claim.
#   * NO CREDENTIAL VALUE IS EVER RETURNED. PUT is write-only and there is no
#     read-back path at all.
openapi: 3.1.0
info:
  title: MOCA control plane
  version: 1.33.0
  description: |
    Multi-user control plane: authenticated API, owned sessions, per-user credentials (MU1).
    This document covers the CONTROL PLANE's routes only. The data plane also serves `/v1` paths
    -- `/v1/turn` and `/v1/runs` -- and they are described in
    harness-openapi.yaml, this document's twin; "the `/v1` API contract" in spec §1/§4 is
    therefore split across the two files.
    `/internal/credentials` is the data-plane-only credential exchange and is not part of the
    public surface; it is documented here because it is part of the contract between the tiers.
    What changed in each version: docs/api/CHANGELOG.md.
servers:
  - url: http://sh-control-plane.default.svc:8080
    description: in-cluster
components:
  securitySchemes:
    sessionToken:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: |
        Ed25519 (`alg: EdDSA`) JWT minted by the control plane. Two shapes: an API token
        (`scope: ["api"]`, 15 minutes, renewed at /v1/auth/token) for `/v1` routes, and a session token (`scope: ["turn:write"]`
        plus `sid`, 5 minutes) for the data plane's `/turn`. No credential travels in the token.
    exchangeToken:
      type: http
      scheme: bearer
      description: The shared `SH_EXCHANGE_TOKEN`, mounted into both tiers from one Secret.
    janitorToken:
      type: http
      scheme: bearer
      description: |
        The sandbox host janitor's `SH_JANITOR_TOKEN` (sandbox-service spec §8.3); admits GET /v1/janitor/sandboxes
        only. No user or admin API token is accepted there, and with none configured every call is
        refused.
    installerToken:
      type: http
      scheme: bearer
      description: |
        The operator's static `SH_INSTALLER_TOKEN` (sandbox members API): admits the /v1/subjects
        routes only, acting as the synthetic `installer` subject with the admin role. With none
        configured every call is refused. An admin's API token is accepted on the same routes
        instead.
    egress:
      type: http
      scheme: bearer
      description: |
        One KVM host's egress token (`SH_EGRESS_TOKEN_<ID>`, egress-credentials spec §4.2); admits
        POST /v1/egress/credential only. Compared against every configured host; no user,
        admin or janitor token is accepted there.
    hostToken:
      type: http
      scheme: bearer
      description: |
        One template host agent's token (`SH_HOST_TOKEN_<ID>`, `SH_TEMPLATE_HOSTS`; template
        lifecycle spec §6.1); admits the /v1/hosts/{host}/ routes for that host only. Distinct
        from every egress and janitor token; no user or admin token is accepted there.
  parameters:
    sessionId:
      name: id
      in: path
      required: true
      schema: { type: string }
    credentialName:
      name: name
      in: path
      required: true
      schema:
        type: string
        pattern: '^[a-z0-9]([a-z0-9-]{0,38}[a-z0-9])?$'
    sandboxId:
      name: id
      in: path
      required: true
      schema:
        type: string
        pattern: '^sbx-[0-9a-f]{26}$'
    turnId:
      name: turnId
      in: path
      required: true
      schema: { type: string }
  schemas:
    Error:
      type: object
      required: [error]
      properties:
        error:
          type: string
          # A real enum, NOT a prose list: this is the half a client generator and a schema validator
          # consume, and the half openapi-contract.test.ts compares against CP_ERROR_CODES. Keep it
          # sorted the same way as the source array for a readable diff when a code is added.
          enum:
            - invalid_json
            - invalid_request
            - token_required
            - token_invalid
            - token_expired
            - grant_invalid
            - invalid_grant
            - subject_conflict
            - unauthorized
            - forbidden
            - not_found
            - session_not_found
            - session_mismatch
            - not_enrolled
            - sandbox_not_found
            - sandbox_terminated
            - name_conflict
            - credential_unsafe
            - destination_conflict
            - destination_ambiguous
            - no_credential
            - quota_exceeded
            - unknown_template
            - template_not_found
            - template_exists
            - policy_refused
            - no_active_slot
            - template_unavailable
            - template_not_active
            - template_retired
            - build_in_use
            - quota_changed
            - policy_changed
            - mode_not_allowed
            - self_attested
            - bootstrap_subject
            - self_revoke
            - admin_granted
            - digest_mismatch
            - bundle_quota_exceeded
            - config_bundle_not_found
            - configRef_invalid
            - envelope_invalid
            - async_quota_exhausted
            - workload_runs_unavailable
            - turn_not_cancellable
            - turn_not_claimable
            - turn_not_found
            - credential_required
            - credential_ambiguous
            - credential_not_found
            - credential_unavailable
            - endpoint_unresolved
            - model_unavailable
            - model_catalog_unavailable
            - authorization_pending
            - device_code_expired
            - identity_provider_misconfigured
            - redis_unavailable
            - internal_error
          description: snake_case error code.
        message:
          type: string
          description: |
            Human-readable detail. ABSENT on `internal_error` by design -- an arbitrary error's text
            can carry a Redis connection string or a presented token, and this body reaches an
            arbitrary caller (errors.ts).
        sessionId: { type: string }
        reason:
          type: string
          description: |
            sandbox_terminated: deleted | expired. no_active_slot: `memory` when no holder under its
            active limit has the memory for the worker (1.12.0; absent at the active limit, as
            before). template_unavailable: `memfile_mismatch` when every holder reports the
            snapshot's memory file is not the guest's size. template_not_active with readiness
            `unavailable`: the build's readinessReason
        rule:
          type: string
          description: |
            policy_refused only: the gating rule the create failed (profile, M1, registry, M7.id,
            M7.guest, M7.vcpus, M7.workspace, M7.home, M7.egress, M7.seed, M7.probe, M7.tools,
            M7.description, M7.skip_git_identity_check, M7.guest_home_gitconfig, M7.spec_id,
            M7.spec_image, M8, M9, envelope, gate.json, X1, X1.trusted, X1.image, X10, X10.record,
            X11, X12, X14, X15; deploy/sbx/template-onboarding/governance/GATING-RULES.md)
        quota:
          type: string
          enum: [templates, buildsQueued, owned, active]
          description: |
            quota_exceeded on a template create (`templates`, `buildsQueued`, `owned`) or an
            activation (`active`): which quota
        readiness:
          type: string
          description: |
            template_unavailable, no_active_slot and template_not_active: the build's readiness
            (template lifecycle spec §3.3)
    TurnGrants:
      type: object
      description: |
        One turn's pair of session grants (MI1 §6.1). Returned by both `/internal/turn-grants` and
        `/internal/grants/refresh`, which is what makes refresh a drop-in for the caller.

        Each grant is a compact Ed25519 JWS with header `typ: moca-grant+jwt`, signed with the
        control plane's GRANT ring — a different key from the session-token signer, so a session
        token can never pass as a grant even where an `aud` check is forgotten. The inference half
        carries `aud: moca-inference` and claims `iss sub tenant sid cred iat exp jti turn_exp`; the
        sandbox half carries `aud: moca-sandbox` and `iss sub tenant sid cfg egress iat exp jti
        turn_exp`. `cred` is a credential NAME (`''` when the session named none) and `egress` a
        list of names — NO SECRET VALUE IS EVER IN A GRANT (§7.2). Each half gets its own `jti`:
        they are separate capabilities presented to separate enforcement points.

        `moca-sandbox` is also `sandbox-token.ts`'s audience, so `aud` alone does not distinguish a
        sandbox token from a sandbox grant; `typ` does, and every verifier pins its own.
      required: [inferenceGrant, sandboxGrant, turnExp, exp]
      properties:
        inferenceGrant: { type: string, description: 'compact JWS, aud moca-inference' }
        sandboxGrant:
          type: string
          description: |
            compact JWS, aud moca-sandbox. Its `egress` claim lists the session OWNER's
            `sandbox-egress` credential names as of this mint — by name, never by value — so one
            added mid-turn appears at the next refresh. The token endpoint narrows them to the
            destination's own hosts, which makes the claim an upper bound rather than a grant of
            access to every name in it.
        turnExp:
          type: integer
          description: |
            epoch SECONDS; the absolute cap on this turn (turn start + `MOCA_TURN_MAX_S`, default
            1800). Carried forward unchanged by every refresh, so refreshing cannot extend a turn.
            A refresh past it is refused with `401 grant_invalid`. A fresh call to
            `/internal/turn-grants` does start a new window — `turnExp` is anchored to the call, and
            no turn is yet identified to anchor to — so it caps a turn's refresh chain, not a
            session.
        exp:
          type: integer
          description: |
            epoch SECONDS; when both grants expire, `min(iat + MOCA_GRANT_TTL_S, turnExp)` with
            `MOCA_GRANT_TTL_S` defaulting to 300. Workers refresh at half-life. With no revocation
            list built (§6.2 builds none deliberately), this lifetime IS the revocation latency.
        cfg:
          type: string
          description: |
            the config-bundle digest bound to the session, echoing the sandbox grant's `cfg` claim;
            absent when the session binds no bundle
    Session:
      type: object
      required: [sessionId, owner, tenant, createdAt, state, turns]
      properties:
        sessionId: { type: string }
        owner: { type: string, description: 'github:<numeric id>' }
        tenant: { type: string }
        createdAt: { type: integer, description: epoch ms }
        state: { type: string, enum: [active, deleting] }
        configRef:
          { type: [string, 'null'], description: recorded at creation; not a liveness signal }
        lastTurnAt: { type: [integer, 'null'] }
        turns: { type: integer }
        sandboxTier:
          type: [string, 'null']
          description: |
            the sandbox tier the session runs in (P6.3): the tier recorded at creation; for a
            session that recorded none (created before P6.3, or while the deployment declared no
            tiers), today's deployment default, which the data plane applies; null whenever the
            deployment declares no tiers, even for a session that recorded one (the data plane
            then runs untiered)
        sandboxTemplate:
          type: [string, 'null']
          description: |
            the sandbox template the session runs on (session-templates spec §3.3): present on a
            deployment that declares templates (SH_SANDBOX_TEMPLATES) and on every `combined`
            deployment (whose template list is always set, empty when the variable is), null there
            for a session with none; present too for any session that named one, even once the
            deployment no longer declares it (its turns then find no worker and are refused).
            Absent otherwise, and so are sandboxBuildId and templateManifestHash
        sandboxBuildId:
          type: [string, 'null']
          description: |
            present exactly when sandboxTemplate is: the build the template resolved to at creation
            through the template store (combined control plane spec §3.4), kept for the session's
            life; a manifest-hash build's turns run only on workers labelled moca.dev/build with
            it. Null for a session with no template, or one created without a template store
        templateManifestHash:
          type: [string, 'null']
          description: |
            present exactly when sandboxTemplate is: the manifest hash of sandboxBuildId; null when
            sandboxBuildId is null or an imported build
        model:
          type: [string, 'null']
          description: |
            the model the session's turns run on, as chosen at creation or by PATCH; null when it
            runs on the deployment default
    TurnStatus:
      type: object
      required: [turnId, state, attempts]
      properties:
        turnId: { type: string }
        state:
          type: string
          description: |
            `queued` and `running` are the only non-terminal states; everything else is final. The
            five result-shaped terminals mirror the leaf result's own discriminants, so a result maps
            to a state with no translation. `lost` is written by the reaper for a turn whose worker
            died without a result -- it guarantees every record eventually reaches a terminal state,
            and therefore eventually expires.
          enum: [queued, running, paused, responded, done, solved, failed, cancelled, lost]
        attempts:
          type: integer
          description: |
            deliveries so far, DESCRIPTIVE only: the queue's delivery count is the sole authority for
            retry exhaustion. `0` while queued.
        cancelRequested:
          type: boolean
          description: |
            present and `true` only on a `running` turn a `DELETE` has asked to stop (#391): the
            request is in flight and the worker has not yet reported. The turn reaches `cancelled`
            on its own; absent otherwise.
        result:
          type: object
          description: |
            the leaf's result, absent until one is written. Its own `status` may read `aborted`, which
            has no corresponding turn `state` -- such a turn reads `state: "cancelled"`, since a leaf
            that aborted stopped because something asked it to.

            BOUNDED: this is a projection of the stored result, not the result itself. The turn's
            OUTPUT -- a solve leaf's patch, a prompt leaf's assistant text -- is never inlined here,
            because this route is polled; `summary` describes it and `artifacts` says what can be
            fetched from `GET …/turns/{turnId}/artifacts/{kind}`. The other MODEL-written strings --
            `verdict.reason`, `gate.summary`, `gate.proposed_action` -- are clipped to the same
            MOCA_TURN_SUMMARY_BYTES cap, with the same trailing `…[truncated]`, and are OMITTED when
            that cap is `0`. The cap bounds the CONTENT of each string: a clipped one is up to
            `MOCA_TURN_SUMMARY_BYTES` plus the 14-byte marker. Everything else the leaf recorded is
            passed through unchanged.
          required: [status]
          properties:
            status:
              type: string
              enum: [done, failed, aborted, paused, solved, responded]
            summary:
              type: string
              description: |
                one bounded line about the turn: the assistant's text, or a gate's summary, or the
                patch's diffstat (`"3 files, +120 -4"`), or the failure's reason -- whichever this
                result has, in that order. Clipped to MOCA_TURN_SUMMARY_BYTES (default 2048) with a
                trailing `…[truncated]` -- so a clipped line is that many bytes plus the 14-byte
                marker; absent when the result has none of the four, and absent altogether when that
                cap is `0`.
            artifacts:
              type: array
              description: |
                what `GET …/turns/{turnId}/artifacts/{kind}` can serve for this turn, absent when
                nothing can; `patch` first, then `text`. A capture refused for size
                (`workspace.patchRefused`) has no `patch` artifact by design: the bytes never left
                the sandbox. A `text` artifact carries no `sha256` -- nothing hashes the assistant's
                reply on the way in, and the fetch route hashes the bytes it serves for the `ETag`.
              items:
                type: object
                required: [kind, bytes]
                properties:
                  kind: { type: string, enum: [patch, text] }
                  bytes: { type: integer }
                  sha256:
                    type: string
                    description: the capture's own digest, when the leaf recorded one
            gate: { type: object }
            reason:
              type: string
              description: |
                on `failed` only, the leaf's own reason (harness-openapi.yaml). `budget` means the
                turn spent one of its `caps` -- its token cap, or the wall clock -- and was stopped
                (#391).
            seed:
              type: object
              description: |
                `responded` on a templated session only: where its workspace's seed came from
                (`source`: `build` or `declared`; `buildId` with `build`), session-templates spec §5.2
            workspace:
              type: object
              description: |
                the DESCRIPTOR of the turn's patch, the data plane's `TurnWorkspace`
                (harness-openapi.yaml) minus its `patch`/`patchBase64`: `baseline`, `patchSha256`,
                `patchBytes`, `diffstat`, or `patchRefused`, or `error`. On a solve leaf's result as
                well as a templated session's `responded` one (#390).
    CredentialDescriptor:
      type: object
      required: [name, kind, consumer, destination, binding]
      properties:
        name: { type: string }
        kind:
          {
            type: string,
            description: 'registry entry: bearer | basic | api-key | oauth2-token | …',
          }
        consumer: { type: string, enum: [inference, sandbox-egress, control-plane] }
        destination:
          type: object
          required: [hosts]
          properties:
            hosts:
              type: array
              items: { type: string }
              description: host allow-list, not a base URL
        binding:
          oneOf:
            - type: object
              required: [header, format]
              properties:
                header: { type: string }
                format: { type: string }
            - type: array
              minItems: 1
              maxItems: 4
              items:
                type: object
                required: [header, format]
                properties:
                  header: { type: string }
                  format: { type: string }
        endpoint:
          type: [string, 'null']
          maxLength: 2048
          description: full gateway origin; meaningful only for consumer `inference`
    ModelList:
      type: object
      required: [credential, models]
      properties:
        credential:
          {
            type: string,
            description: 'the credential listed for; operator-fallback for the fallback',
          }
        models:
          type: array
          items:
            type: object
            required: [id]
            properties:
              id: { type: string }
              contextWindow: { type: integer }
              maxTokens: { type: integer }
              reasoning: { type: boolean }
              vision: { type: boolean }
    EgressEvent:
      description: |
        One audit event of the KVM host's egress proxy (`moca-egress`, remote-worker
        internal/egress/audit.go `Event`), exactly as it wrote it; no other field is accepted or
        stored. `path` carries no query, fragment or userinfo; `credential` is a name, never a value.
      type: object
      additionalProperties: false
      required: [time, via, decision]
      properties:
        time: { type: string, description: RFC 3339 }
        via: { type: string, enum: [moca-egress] }
        vm_id: { type: string }
        sid: { type: string, description: "the sandbox's workspace key" }
        sub: { type: string }
        host: { type: string }
        dial_addr: { type: string }
        method: { type: string }
        path: { type: string }
        status: { type: integer }
        bytes_up: { type: integer }
        bytes_down: { type: integer }
        credential: { type: string }
        decision:
          { type: string, description: 'tunnel, forward, destination_denied, audit_dropped, ...' }
        dropped: { type: integer }
        coalesced: { type: integer }
    EgressSummary:
      type: object
      required: [byHost, total, dropped, droppedBy, complete, sealed, sha256]
      properties:
        byHost:
          type: object
          additionalProperties:
            type: object
            required: [count, decisions, bytesUp, bytesDown]
            properties:
              count: { type: integer }
              decisions: { type: object, additionalProperties: { type: integer } }
              bytesUp: { type: integer }
              bytesDown: { type: integer }
        total: { type: integer, description: events stored }
        dropped: { type: integer, description: 'droppedBy summed: the events this log may lack' }
        droppedBy:
          type: object
          required: [proxy, cap, budget, invalid]
          properties:
            proxy: { type: integer, description: "charged by the proxy's audit_dropped reports" }
            cap: { type: integer, description: "over a log's cap: 10,000 events or 4 MiB of lines" }
            budget:
              type: integer
              description: "over the deployment's 64 MiB budget of lines for all logs together"
            invalid: { type: integer, description: named this sandbox but were not a proxy Event }
        complete: { type: boolean, description: dropped is 0 }
        sealed:
          { type: boolean, description: 'past the 600 s grace after the end: takes no more events' }
        sha256:
          type: string
          description: |
            sha256: + the hex sha256 of the NDJSON export: each stored event's canonical JSON
            (the provenance canonicalization: keys sorted, no whitespace), each followed by one \n,
            in arrival order. The empty log's is the sha256 of no bytes.
    Sandbox:
      type: object
      description: A sandbox (sandbox-service spec §5.1). Times are epoch seconds.
      required:
        [
          id,
          owner,
          name,
          template,
          buildId,
          templateManifestHash,
          state,
          reason,
          createdAt,
          expiresAt,
          terminatedAt,
          labels,
          mode,
          idleTimeoutS,
          modeEpoch,
          idleLifetimeS,
        ]
      additionalProperties: false
      properties:
        id:
          type: string
          pattern: '^sbx-[0-9a-f]{26}$'
          description: '`sbx-` plus 26 random lowercase hex characters; also the workspace key'
        owner: { type: string, description: 'github:<numeric id>' }
        name:
          type: [string, 'null']
          pattern: '^[a-z0-9][a-z0-9-]{0,62}$'
          description: unique among the owner's live sandboxes; null when unnamed
        template: { type: string }
        buildId:
          type: [string, 'null']
          description: |
            the build the template reference (id, id:tag or id@<build id>) resolved to at creation,
            kept for the sandbox's life (template lifecycle spec §3.2): `sha256:<manifest hash>`, or
            `imported:<12 hex>` for a template imported from SH_SANDBOX_TEMPLATES; null on a sandbox
            created before builds were recorded
        templateManifestHash:
          type: [string, 'null']
          description: |
            the snapshot's manifest hash (the build id of a built build); null for a template
            imported from SH_SANDBOX_TEMPLATES, which names no snapshot
        state: { type: string, enum: [ready, terminated] }
        reason:
          type: [string, 'null']
          enum: [deleted, expired, null]
          description: why it terminated; null while ready
        createdAt: { type: integer, description: epoch seconds }
        expiresAt:
          type: integer
          description: |
            epoch seconds: now plus `idleLifetimeS` at create. When
            SH_SANDBOX_MAX_LIFETIME_SECONDS is configured, it slides with activity: each activity
            mint (POST .../token and POST .../mode-token, unless the body says `activity: false`)
            and each PUT .../mode moves it to at least now plus `idleLifetimeS`, never backwards;
            reads and lists do not move it. Unset, it stays fixed at create. The maximum caps each
            extension, not the sandbox's age: one with activity inside every idle lifetime does not
            expire. Expiry is computed: past it, the sandbox reads as terminated / expired
            everywhere and refuses to mint (sandbox-service spec §5.2; idle-lifetime spec §3); an activity after the
            deadline is refused and does not revive it.
        terminatedAt:
          type: [integer, 'null']
          description: epoch seconds; the delete time or expiresAt; null while ready
        labels:
          type: object
          maxProperties: 16
          propertyNames: { pattern: '^[a-z0-9][a-z0-9._-]{0,62}$' }
          additionalProperties: { type: string }
          description: free-form string pairs (at most 16; each value at most 256 UTF-8 bytes)
        mode:
          type: string
          enum: [per-exec, lease, lease+processes]
          description: |
            How the worker runs the sandbox's Execs (lease-mode spec §8.1); `per-exec` unless the
            owner picked a lease mode. Sandbox tokens carry it as the `mode` claim.
        idleTimeoutS:
          type: integer
          minimum: 0
          description: the owner's lease idle timeout in seconds; 0 means the worker's default
        modeEpoch:
          type: integer
          minimum: 0
          description: |
            raised by 1 on every PUT /v1/sandboxes/{id}/mode, so a worker can refuse an Exec whose
            token carries an older mode (`stale_mode`). A sandbox created `per-exec` starts at 0, one
            created in a lease mode at 1
        idleLifetimeS:
          type: integer
          minimum: 3600
          description: |
            how long the sandbox lives past its last activity, in seconds: each mint or mode change
            that counts as activity moves `expiresAt` to at least now plus this, when
            SH_SANDBOX_MAX_LIFETIME_SECONDS is configured (unset, `expiresAt` stays fixed). Never
            above SH_SANDBOX_MAX_LIFETIME_SECONDS as it is now; a sandbox made before idle lifetimes
            shows SH_SANDBOX_LIFETIME_SECONDS
    Template:
      type: object
      description: A template (template lifecycle spec §3.2, §4)
      required: [id, description, tools, owner, visibility, onboarding, readiness, tags, builds]
      properties:
        id: { type: string }
        description: { type: string }
        tools:
          type: array
          items: { type: string }
          description: the default build's tools
        owner:
          type: [string, 'null']
          description: the owning subject; null for a template the deployment declared
        visibility:
          type: string
          enum: [private, deployment]
          description: |
            `private`: listed and served only to its owner and admins. In effect: `private` while
            any registered build is self-attested now (a trust removal narrows a template on the
            next read), else as set
        attestation:
          type: string
          enum: [deployment, self]
          description: '`self` when any registered build is self-attested now'
        onboarding:
          type: [string, 'null']
          description: "`registered` once any build is; else the newest build's status"
        readiness:
          type: [string, 'null']
          description: the default build's readiness
          enum: [active, activating, deactivating, inactive, unavailable, unknown, retired, null]
        readinessReason:
          $ref: '#/components/schemas/ReadinessReason'
        tags:
          type: object
          additionalProperties: { type: string }
          description: tag -> buildId; `default` is what a bare id names
        builds:
          type: array
          items: { $ref: '#/components/schemas/TemplateBuild' }
    ReadinessReason:
      type: string
      enum: [not_held, no_slot, memory, memfile_mismatch]
      description: |
        present only with readiness `unavailable` (1.12.0): why placement left the build waiting.
        `not_held` no host holds its snapshot; `no_slot` every holder is at its active limit;
        `memory` a holder under its limit has no memory headroom for the worker now (template
        lifecycle spec §6.2: its floor, a pressure brake, or an inventory older than 60 s);
        `memfile_mismatch` every holder reports the snapshot's memory file is not the guest's size
        (a rebuild clears it, not a wait)
    TemplateBuild:
      type: object
      description: One build of a template, an immutable snapshot (template lifecycle spec §3.2, §3.3)
      required:
        [buildId, status, profile, readiness, capacity, lastUsedAt, tags, createdAt, provenance]
      properties:
        buildId:
          type: string
          description: |
            `sha256:<manifest hash>` or `imported:<12 hex>`. A build that a rebuild of its snapshot
            superseded at registration (1.23.0, template lifecycle spec §6.1) keeps its id,
            `retired`, beside the build that took it over: a build id then names that build, and
            the superseded one is found by its handle
        status:
          type: string
          enum: [queued, building, probing, built, registered, rejected, failed, retired]
          description: |
            its onboarding state (template lifecycle spec §3.3); a build imported from
            SH_SANDBOX_TEMPLATES is `registered`
        profile: { type: string, description: the policy profile; `imported` for the env list's }
        readiness:
          type: [string, 'null']
          enum: [active, activating, deactivating, inactive, unavailable, unknown, retired, null]
          description: |
            for a registered build (§3.3), from facts: `active` the relay holds an attached
            presence record for its worker; `activating` an activation lease stands and a host
            holding it is asked to run it, not attached yet; `deactivating` attached with no lease
            (draining: a worker is never stopped under a live sandbox); `inactive` no lease, not
            attached; `unavailable` leased, but no host that reports holds it, every holder is at
            its active limit, none has the memory for its worker, or every holder reports its
            memory file wrong (`readinessReason` says which); `unknown` the relay's presence could
            not be read; `retired` for a retired build (§5.1); null for any other build that is not
            registered. Before any host agent reports, readiness is the presence alone (`active` or
            `inactive`)
        readinessReason:
          $ref: '#/components/schemas/ReadinessReason'
        queued:
          type: boolean
          description: |
            1.13.0 (template lifecycle spec §6.5), present only with readiness `activating` on a host
            whose agent reports its start limit: true while the build waits for a start slot (its
            place in the host's start line is beyond the host's startConcurrency), false once its
            worker is starting. A queued build stays `activating` longer than before: poll with a
            timeout sized for the host's whole start line
        queuePosition:
          type: integer
          minimum: 1
          description: |
            1.13.0, with `queued`: the build's 1-based place among its host's placed, wanted builds
            not attached yet, first leased first; the first startConcurrency are starting
        graced:
          type: boolean
          enum: [true]
          description: |
            1.13.0 (§6.5), present only while the build is in its host's idle grace: no lease left,
            and its worker kept running (readiness `deactivating`) until `gracedUntil`, unless a
            wanted build needs its slot or a release with `stopNow` ends it. A use within the grace
            finds it active, with no cold start
        gracedUntil:
          type: integer
          description: |
            1.13.0, with `graced`: epoch seconds the grace ends (its last lease's end plus the host's
            idleGraceSeconds)
        capacity:
          type: [object, 'null']
          description: |
            for an active build; and for a retired one whose worker still holds a presence record
            (its host has not stopped it yet), or whose presence cannot be read (`running` null);
            null otherwise, so for a retired build null means its worker is known to be stopped,
            that it never had one (retired before it registered), or that it is `shared` (kept
            running for a build neither retired nor rejected)
          required: [running, inUse]
          properties:
            running:
              type: [integer, 'null']
              description: |
                the sandboxes its worker advertises at once; null for a retired build whose
                presence cannot be read
            inUse:
              type: [integer, 'null']
              description: |
                its live sandboxes now; null on the harness profile, which holds no sandbox
                records (sessions name a template, not a worker)
        shared:
          type: boolean
          description: |
            true for a retired build whose snapshot or worker a build neither retired nor rejected also
            uses (the same snapshot in another template, or one worker id that two builds from one
            image share): its worker is not stopped for the retire, since that build's own state
            decides whether it runs, and its `capacity` is null. False for every other build
        lastUsedAt:
          type: [integer, 'null']
          description: |
            epoch seconds of the newest sandbox created on this build (retained records included),
            not on its worker: builds of one template from one image share a worker id. A build
            superseded by a rebuild of the same snapshot (#818) shares its build id with the build
            that replaced it, so the retired twin reports its successor's use. A sandbox record from
            before build tracing (no build id) counts for every build of its worker. Null when it
            has none, and on the harness profile
        heldBy:
          type: [array, 'null']
          items: { type: string }
          description: |
            the ids of the hosts whose last inventory holds this build's snapshot (template lifecycle
            spec §6.1), sorted; no paths. A host that has gone silent (no inventory for
            HOST_STALE_S, so out of placement) is still listed: it still holds what it last
            reported. A retired build stays held until its host removes it: the host's `removed`
            report drops it at once (§6.1 step 7). `[]` when no host holds it; null on a
            deployment without host agents
        tags:
          type: array
          items: { type: string }
          description: |
            the tags naming this build; a tag names a build id, so a superseded build lists none:
            its tags name the build that took its id over
        createdAt: { type: integer, description: epoch seconds }
        provenance:
          type: [string, 'null']
          description: the digest of the provenance record that created it (with SH_PROVENANCE_DIR)
        handle:
          type: string
          description: |
            the `b-<26 hex>` handle the create answered, by which the build is followed until it is
            built (then its buildId is its manifest hash); equal to buildId for an imported build
        reason:
          type: [object, 'null']
          description: |
            on a `failed` or `rejected` build, why; on a build retired because a rebuild of its
            snapshot superseded it (1.23.0), why, with step `superseded`; null otherwise
          required: [message]
          properties:
            message: { type: string }
            step:
              type: string
              description: 'the step that failed; `cancelled` for a cancel; `superseded` for a superseded build'
            rule:
              type: string
              description: the gating rule, on a rejection; `admin` for a reject after the fact (§5.2)
        attestation:
          type: string
          enum: [deployment, self]
          description: |
            Recomputed on every read from the current policy: `self` when the build was created on
            a selfAttest profile with a gate record trustedGateRecords does not list now, whether or
            not it was listed at create; `deployment` otherwise (a promotion or removal of the
            record changes it, nothing rewritten)
        gateFloorCheckedOffline:
          type: [boolean, 'null']
          description: |
            Its gate record's `gate.floor_checked_offline` (true for a curated family record, which
            predates the field); false only on a profile that allows it (`general-self`); null with
            no gate record
        gateFloorMetOffline:
          type: boolean
          description: |
            Present only for a gate from a `network_needed` contract: its `gate.floor_met_offline`,
            whether the offline run met the floor anyway
        spec:
          type: object
          description: on GET /v1/templates/{id} and the builds routes only
          properties:
            guest_mb: { type: integer }
            vcpus: { type: integer }
            workspace_mb: { type: integer }
            seed: { type: string }
            tools: { type: array, items: { type: string } }
    RetiredBuild:
      type: object
      description: One build a retire answered for, with what ties it to the trace (§5.1)
      required: [build, buildId, readiness, record]
      properties:
        build:
          { type: string, description: "the build's handle (its build id for an imported build)" }
        buildId:
          type: [string, 'null']
          description: the build id; null for one retired before it registered
        readiness: { type: string, enum: [retired] }
        record:
          type: [string, 'null']
          description: the retire record written now (`sha256:...`); null if it was already retired
    DefaultTagMove:
      type: [object, 'null']
      description: |
        The `default` tag's move a retire or a reject made (#909): when it ended the build
        `default` named, `default` moves to the newest registered build left, with a `tag` record.
        Null when `default` did not move (it named another build, or no registered build is left;
        then the next build to register takes `default`).
      required: [buildId, before, record]
      properties:
        buildId: { type: string, description: the build `default` names now }
        before: { type: string, description: the retired build it named }
        record: { type: string, description: 'the `tag` record written (`sha256:...`)' }
    WantedWorker:
      type: object
      required: [template, buildId, worker]
      properties:
        template: { type: string }
        buildId: { type: string }
        worker: { type: string, description: the relay sandbox id of the build's worker }
    TemplateCreate:
      type: object
      required: [image, spec]
      properties:
        id: { type: string, description: 'the template id (lowercased); ignored on /{id}/builds' }
        image:
          type: string
          description: >-
            [host[:port]/]path@sha256:<64 hex>, in the distribution reference grammar (lowercase
            path components, no tag beside the digest), from an allowed registry (hosts compare
            case-insensitively)
        spec:
          type: object
          description: |
            a template spec (`moca-sbx-template-spec/1`; samples in
            deploy/sbx/template-onboarding/examples/): guest_ram_mb (or its alias guest_mb, never
            both: M7.guest; stored as guest_ram_mb), vcpus,
            workspace_mb?, egress, seed, probe, tools, description, and optionally guest_home,
            skip_git_identity_check, guest_home_gitconfig, probe_status, source_record_digest. An
            `id` or `image` in it must equal the create's own (M7.spec_id, M7.spec_image)
        profile: { type: string, description: a policy profile; the policy's default when absent }
        gateRecord:
          type: string
          description: the image's gate record file, byte for byte (its sha256 is what the policy trusts)
        visibility:
          type: string
          enum: [private, deployment]
          description: a new template's visibility; default `deployment`
    TemplateQueued:
      type: object
      required: [templateId, buildId, build, status]
      properties:
        templateId: { type: string }
        buildId:
          type: [string, 'null']
          description: null until registered; then the manifest hash (a reused registered build)
        build:
          type: string
          description: the build to follow (its provisional handle b-<26 hex>, or its buildId once registered)
        status:
          type: string
          enum: [queued, building, probing, built, registered]
          description: "`queued` for a new build; a reused build's own status"
        reused:
          type: boolean
          description: |
            true when the create matched a build of the caller's template with the same inputs
            (image, spec, profile, gate record's sha256) that is registered or on its way there
            (§3.2): that build is answered, and no second one is queued. A registered build counts
            only while a fresh host holds its snapshot (with host agents). Absent for a new build
    LimitUse:
      type: object
      required: [limit, used]
      properties:
        limit: { type: integer }
        used: { type: integer }
    Policy:
      type: object
      description: The template policy (template lifecycle spec §8); schema moca-template-policy/1
      required: [schema, profiles, defaultProfile, allowedRegistries, trustedGateRecords, quota]
      properties:
        schema: { type: string, enum: [moca-template-policy/1] }
        profiles:
          type: object
          description: profile name -> its rules; `base` must exist
          additionalProperties:
            type: object
            required: [requires, envelope]
            properties:
              requires:
                type: array
                items: { type: string, enum: [X1, X10, X11, X12, X14, X15] }
                description: gating rule ids beyond the base rules; an unknown id is refused
              selfAttest:
                type: boolean
                description: |
                  A gate record the policy does not trust still passes X1.trusted when the creating
                  subject submitted it, for that subject's own templates only. The build is
                  self-attested: private, its commits always refused (X12.self), never
                  deployment-visible until an admin adds the record's sha256 to trustedGateRecords.
                  Absent: false. The default policy holds `benchmark-self` and `general-self`
              selfAttestEgress:
                type: boolean
                description: |
                  On a self-attested record only, whether spec.egress may be true (the KVM host's
                  allowlisted egress, never unrestricted). Absent: false. `benchmark-self` keeps it
                  false (benchmark integrity); `general-self` sets it
              requireOfflineGate:
                type: boolean
                description: |
                  Whether the gate's test floor must have been checked offline (X1.offline). A
                  general-gate record (the schema GET /v1/policy names as `gateRecordSchema`) needs
                  `gate.floor_checked_offline: true` (fail closed); a curated family record predates
                  the field and passes without it. Absent: true on a profile that requires X1;
                  `general-self` sets it false
              envelope:
                type: object
                required: [maxGuestMb, maxVcpus, maxWorkspaceMb]
                properties:
                  maxGuestMb: { type: integer }
                  maxVcpus: { type: integer }
                  maxWorkspaceMb: { type: integer }
                  exact:
                    type: object
                    required: [guestMb, vcpus]
                    properties:
                      guestMb: { type: integer, minimum: 1 }
                      vcpus: { type: integer, minimum: 1 }
        defaultProfile: { type: string }
        allowedRegistries:
          type: array
          items: { type: string }
          description: |
            registry hosts. `<default>` is a reference with no host, which the build host pulls from
            its own configured registry; Docker Hub is `docker.io` (`index.docker.io` reads as it)
        allowedRepositories:
          type: object
          additionalProperties:
            type: array
            minItems: 1
            items: { type: string }
          description: |
            Optional, per registry (a key of `allowedRegistries`): the repositories an image may come
            from there, each an exact path (`library/python`) or a prefix (`library/*`), matched on
            whole path segments. A registry with no entry allows every repository it serves. A Docker
            Hub official name (`python`) reads as `library/python`. From a listed registry, an
            image path outside the entries' grammar (uppercase, or an empty, `.` or `..` segment)
            is refused too. A refusal is rule `registry.repository`.
        trustedGateRecords:
          type: array
          items: { type: string }
          description: sha256 digests of the gate records the benchmark profile trusts
        quota: { $ref: '#/components/schemas/Quota' }
        quotaBySubject:
          type: object
          description: |
            per-subject overrides of `quota`, keyed by subject (`github:<numeric id>` or
            `oidc:<provider sub>`); an admin's, `PUT /v1/quota/{subject}`. A `PUT /v1/policy`
            stores the whole policy, this map too: one that sends `?expect=` is refused (`409
            policy_changed`) if a quota changed since its read, and one without it replaces the
            overrides with the ones it sends
          additionalProperties: { $ref: '#/components/schemas/Quota' }
    Quota:
      type: object
      required: [templates, buildsQueued, active]
      properties:
        templates:
          type: integer
          minimum: 0
          description: >-
            templates a subject owns with a build registered or on its way there (a template whose
            builds all failed, were cancelled or retired is not counted, and a new build of it is
            checked against this quota like a new id)
        buildsQueued:
          type: integer
          minimum: 0
          description: >-
            builds of a subject's templates not yet built (queued, building or probing), charged to
            the template's owner
        active: { type: integer, minimum: 0 }
        owned:
          type: integer
          minimum: 0
          description: >-
            template ids a subject owns in any status (a failed or cancelled-only template too),
            checked for a new id only; optional: a default without it is 200, an override without it
            has the default's
    PolicyView:
      type: object
      required: [policy, digest, record]
      properties:
        policy: { $ref: '#/components/schemas/Policy' }
        digest: { type: string, description: the sha256 of the policy itself }
        record: { type: string, description: the provenance policy record's digest }
        gateRecordSchema:
          type: string
          description: |
            The general-gate record schema this deployment reads (`SH_GATE_RECORD_SCHEMA`, default
            `moca-gate-record/1`): a record of it needs `gate.floor_checked_offline: true` for
            X1.offline. On GET /v1/policy only; absent from an older control plane, read as the
            default
    Subject:
      type: object
      required: [subject, enrolled, source, storeEnrolled, roles]
      properties:
        subject:
          { type: string, pattern: '^(?:github:[0-9]+|oidc:[A-Za-z0-9][A-Za-z0-9._@+-]{0,127})$' }
        enrolled:
          type: boolean
          description: enrolled by any route (the settings, the members store, or an admin role)
        source:
          type: string
          enum: [env, api]
          description: "`env`: the deployment's settings; `api`: the members store"
        storeEnrolled:
          type: boolean
          description: |
            Whether the members store itself enrolls it, apart from the settings and any role: what an
            unenroll changes, and what keeps the subject enrolled once the settings drop it.
        roles:
          type: array
          items:
            type: object
            required: [role, source, until, by]
            properties:
              role: { type: string, enum: [admin] }
              source: { type: string, enum: [env, api] }
              until: { type: [integer, 'null'], description: epoch seconds; null for no expiry }
              by: { type: [string, 'null'], description: the admin who granted it (null for env) }
  responses:
    Unauthorized:
      description: no token, a bad token, or a failed exchange or janitor authentication
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
    NotFound:
      description: |
        Unknown session (or sandbox), or one owned by someone else -- deliberately
        indistinguishable. 404 rather than 403, because a 403 is an existence oracle (spec §8.1).
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
    NotEnrolled:
      description: '`not_enrolled`: the caller is not in SH_ALLOWED_SUBJECTS (sandbox-service spec §4.2)'
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
    BadRequest:
      description: a typed validation or policy refusal
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
paths:
  /:
    get:
      operationId: getIndex
      summary: What this URL is, for a browser or curl
      description: |
        A short plain-text page (#779): that this is a Moca control plane (and on the `sandbox`
        profile, the sandbox service), the deployment's `version` when it has one, that the API is
        under `/v1` with `GET /v1/discovery` describing the deployment, how to install `mocactl` and
        log in for the profiles it serves, and that a sandbox's egress is an allowlist whose additions
        the operator makes. Fixed text: it names no URL of the deployment and echoes nothing of the
        request. Its wording is for people and may change; a client reads `/v1/discovery` instead.
        Only the exact path `/`; any other unknown path is the `not_found` 404.
      security: []
      responses:
        '200':
          description: the page
          content:
            text/plain:
              schema: { type: string }
  /healthz:
    get:
      operationId: healthz
      summary: Liveness
      security: []
      responses:
        '200': { description: ok }
  /readyz:
    get:
      operationId: readyz
      summary: Readiness — whether Redis is answering
      description: |
        Credentials live in Kubernetes Secrets, so they stay available while Redis is down
        (spec §7.1, §9.2). This probe therefore reports only the session index.
      security: []
      responses:
        '200': { description: ready }
        '503':
          description: redis_unavailable
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /metrics:
    get:
      operationId: getMetrics
      summary: Async counters (admin only)
      security: [{ sessionToken: [] }]
      description: |
        Counters the control plane alone can report, because it answers the request that produces
        them (async fan-out spec §7, §4.3). Process-local and reset by a restart: with more than one
        replica, each request reports one replica's share. A rate signal, not a ledger.
      responses:
        '200':
          description: counters
          content:
            application/json:
              schema:
                type: object
                required: [counters]
                properties:
                  counters:
                    type: object
                    required: [async_quota_refusals]
                    properties:
                      async_quota_refusals:
                        type: integer
                        description: Submissions refused with 429 async_quota_exhausted.
        '403':
          description: forbidden — the admin role is required
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/discovery:
    get:
      operationId: getDiscovery
      summary: Where a client finds the rest of the deployment
      description: |
        Public and unauthenticated: a client reads it before logging in, so that the control-plane
        URL is the only address a user has to know. `harnessUrl` is the harness base URL as a
        client reaches it, set by the operator with SH_PUBLIC_HARNESS_URL. It is `null` when the
        deployment advertises none; a 404 means a control plane that predates this route.
        `sandboxTiers` (P6.3) is always present; a control plane that predates P6.3 omits it.
        `version` is always present; a control plane that predates advertising one omits it.
        `profile` names the control plane's route profile; on `sandbox`, `execEndpoint` and `execCa`
        say where to send Exec and which CA to trust (sandbox-service spec §4.1). A `sandbox` control plane answers
        only `profile`, `execEndpoint` and, when the exec certificate is self-issued, `execCa`;
        templates are at the fixed `/v1/templates`. A control plane that predates profiles omits
        `profile`, and is a `harness` one.
      security: []
      responses:
        '200':
          description: the advertised endpoints
          content:
            application/json:
              schema:
                oneOf:
                  - type: object
                    description: the harness profile (the default)
                    required: [harnessUrl, sandboxTiers, version]
                    properties:
                      harnessUrl:
                        type: [string, 'null']
                        description: absolute http(s) URL, no trailing slash
                      sandboxTiers:
                        type: [object, 'null']
                        description: |
                          the tiers a session may ask for at creation (SH_SANDBOX_TIERS) and the
                          default; null when none are declared
                        required: [names, default]
                        properties:
                          names: { type: array, items: { type: string } }
                          default: { type: string }
                      sandboxTemplates:
                        type: array
                        description: |
                          the templates a session may name at creation (SH_SANDBOX_TEMPLATES),
                          without their seeds; absent when the deployment declares none
                        items:
                          type: object
                          required: [id, description, tools]
                          properties:
                            id: { type: string }
                            description: { type: string }
                            tools: { type: array, items: { type: string } }
                      version:
                        type: [string, 'null']
                        description: |
                          the deployment's version (MOCA_VERSION, baked in at image build), so a client
                          can show it; `dev` when nothing was baked in, and `null` permitted for
                          compatibility with a control plane that reports none
                      profile:
                        type: string
                        enum: [harness, combined]
                        description: |
                          `combined` (combined control plane spec §3.1) serves sessions and sandboxes:
                          its body adds `execEndpoint` and `execCa`, as the sandbox profile's
                      execEndpoint:
                        type: string
                        description: combined profile only -- host:port of the exec Route
                      execCa:
                        type: string
                        description: combined profile only -- PEM of a self-issued exec certificate
                  - type: object
                    description: the sandbox profile (sandbox-service spec §4.1)
                    required: [profile, execEndpoint]
                    additionalProperties: false
                    properties:
                      profile: { type: string, enum: [sandbox] }
                      execEndpoint:
                        type: string
                        description: sandbox profile only -- host:port of the exec Route
                      execCa:
                        type: string
                        description: |
                          sandbox profile only -- PEM of a self-issued exec certificate; absent when
                          the certificate chains to a public CA
  /v1/auth/device:
    post:
      operationId: startDeviceAuth
      summary: Start a login (GitHub device flow, or the OIDC provider's authorize URL)
      description: |
        GitHub's user-login flow is plain OAuth 2.0, not OIDC (spec §5.1). The device flow is what a
        shell script can complete, and it needs no client secret. The GitHub OAuth app must have
        device flow ENABLED -- it is off by default (spec §5.1.1).

        With the oidc identity provider (SH_IDENTITY_PROVIDER=oidc), the same reply carries the
        provider's authorize URL in verificationUri, a state token in deviceCode, and a user
        code confirmed on the callback page rather than at the provider.
      security: []
      responses:
        '200':
          description: the code the operator types at verificationUri
          content:
            application/json:
              schema:
                type: object
                required: [deviceCode, verificationUri, interval, expiresIn]
                properties:
                  deviceCode: { type: string }
                  userCode:
                    {
                      type: string,
                      description: the code the user confirms the login with -- typed at the provider (github) or on the callback's confirmation page (oidc),
                    }
                  verificationUri: { type: string }
                  interval: { type: integer }
                  expiresIn: { type: integer }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '429':
          description: |
            `quota_exceeded` (oidc only): too many sign-ins are waiting. The route is
            unauthenticated, so the control plane bounds the live login states it parks, in two
            ways: 10,000 in total, and `SH_OIDC_MAX_PENDING_PER_SOURCE` (default 20) per client
            address; the message says which ("...from this address" for the second). A state lives
            until its login is collected or its `expiresIn` runs out, so back off and retry, rather
            than looping.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '502':
          description: |
            identity_provider_misconfigured -- GitHub refused the control plane's OAuth app: device
            flow is off, or SH_GITHUB_CLIENT_ID names no app. An operator fix; `message` says which.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/auth/device/token:
    post:
      operationId: completeDeviceAuth
      summary: Exchange an approved device code for an API token
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [deviceCode]
              properties:
                deviceCode: { type: string }
                label:
                  type: string
                  maxLength: 64
                  description: a client hint such as the hostname; shown back, never trusted
      responses:
        '200':
          description: an api-scoped token
          content:
            application/json:
              schema:
                type: object
                required: [token, subject, expiresAt, refreshToken, refreshExpiresAt]
                properties:
                  token: { type: string }
                  subject: { type: string }
                  displayName: { type: string }
                  roles: { type: array, items: { type: string } }
                  expiresAt: { type: integer, description: epoch seconds }
                  refreshToken:
                    type: string
                    pattern: '^mrt_[A-Za-z0-9_-]{43}$'
                    description: opaque, single-use; exchange at /v1/auth/token for the next pair
                  refreshExpiresAt:
                    { type: integer, description: epoch seconds; the login's absolute limit }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '428':
          description: authorization_pending — the user has not approved yet; poll again
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '403':
          description: |
            Sandbox profile only: `not_enrolled` -- the approving GitHub account is not in
            SH_ALLOWED_SUBJECTS and is not an admin (sandbox-service spec §4.2). No refresh family is issued. The
            `message` names the caller's own subject (`github:<id>`) for an operator to enroll.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '410':
          description: device_code_expired — the code expired before it was approved; start a new one
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/auth/test-token:
    post:
      operationId: testUserToken
      summary: Log in as a configured test user, without the GitHub device flow (dev/test only)
      description: |
        Present only when the control plane was started with `SH_TEST_USERS=N` (ADR-0045); without
        it every request answers 404, so the path is invisible in an ordinary deployment. Requires
        the shared secret `SH_TEST_USER_SECRET`, because the endpoint issues a real login for an
        arbitrary `test:<index>` subject.

        The reply is the SAME body as `/v1/auth/device/token`: a test user gets a refresh family,
        the configured token TTLs and its roles from `SH_ADMIN_SUBJECTS`, so it is configured
        exactly like a GitHub user everywhere downstream. Refused on the sandbox profile, which
        the control plane will not even boot with test users enabled.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [index, secret]
              properties:
                index:
                  type: integer
                  minimum: 1
                  description: 1-based; must be <= SH_TEST_USERS. The subject is `test:<index>`.
                secret:
                  type: string
                  description: must equal SH_TEST_USER_SECRET; compared in constant time
                label:
                  type: string
                  maxLength: 64
                  description: a client hint such as the hostname; shown back, never trusted
      responses:
        '200':
          description: an api-scoped token, the same shape /v1/auth/device/token returns
          content:
            application/json:
              schema:
                type: object
                required: [token, subject, expiresAt, refreshToken, refreshExpiresAt]
                properties:
                  token: { type: string }
                  subject: { type: string, pattern: '^test:[0-9]+$' }
                  displayName: { type: string }
                  roles: { type: array, items: { type: string } }
                  expiresAt: { type: integer, description: epoch seconds }
                  refreshToken:
                    type: string
                    pattern: '^mrt_[A-Za-z0-9_-]{43}$'
                    description: opaque, single-use; exchange at /v1/auth/token for the next pair
                  refreshExpiresAt:
                    { type: integer, description: epoch seconds; the login's absolute limit }
        '400':
          description: |
            invalid_request -- `index` is missing, not an integer, or outside 1..SH_TEST_USERS.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401':
          description: |
            unauthorized -- the shared credential in the request was missing or did not match. One
            code for both, and checked before `index`, so a prober learns neither which half is
            wrong nor how many test users exist.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: |
            not_found -- this control plane has no test users configured (`SH_TEST_USERS` unset).
            Deliberately indistinguishable from an unrouted path.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/auth/oidc/callback:
    get:
      operationId: oidcCallback
      summary: The OIDC provider's browser redirect target
      description: |
        Mounted for every deployment, but answers only when SH_IDENTITY_PROVIDER=oidc. Two rounds
        share the route, both answered as HTML -- the caller is a person in a browser.

        First round (?code=): the provider's redirect. The control plane exchanges the code
        server-side (it alone holds the client secret) and verifies the id_token against the
        provider's JWKS -- but does NOT settle the login. It renders a confirmation form asking
        for the user code shown in the terminal that started the login (the browser-to-terminal
        binding: without it, the authorize URL alone would let an attacker walk a victim's live
        SSO session into the attacker's login).

        Second round (?confirm= plus the round-1 token as ct): the typed code and the
        browser-bound token. Both matching (constant-time, at most 5 tries) settles the login;
        the next /v1/auth/device/token poll picks it up. The token is what stops the login's
        initiator from confirming a victim's parked principal with a bare request: they hold the
        state and the user code, but never saw the victim's round-1 response.
      security: []
      parameters:
        - { name: code, in: query, required: false, schema: { type: string } }
        - { name: state, in: query, required: false, schema: { type: string } }
        - { name: error, in: query, required: false, schema: { type: string } }
        - { name: confirm, in: query, required: false, schema: { type: string } }
        - name: ct
          in: query
          required: false
          schema: { type: string }
          description: >
            the browser-bound token from the round-1 response (the confirmation form's hidden
            field); required alongside confirm, and a missing or wrong one counts as a wrong try
      responses:
        '200':
          description: the confirmation form, the confirmed page, or the refusal page
          content:
            text/html: { schema: { type: string } }
        '400':
          description: no oidc provider configured, or the callback is missing its parameters
          content:
            text/plain: { schema: { type: string } }
        '401':
          description: unknown or expired sign-in state
          content:
            text/plain: { schema: { type: string } }
    post:
      operationId: oidcCallbackSubmit
      summary: The confirmation form's submission
      description: |
        The second round, as the browser's form submits it (urlencoded): state, the typed user
        code (confirm) and the round-1 browser token (ct). POST, not GET, so the code and the
        token stay out of URLs, access logs and browser history. Same outcomes and pages as the
        GET round. Every response carries Cache-Control: no-store, X-Frame-Options: DENY, a
        frame-ancestors 'none' CSP and Referrer-Policy: no-referrer.
      security: []
      requestBody:
        required: true
        content:
          application/x-www-form-urlencoded:
            schema:
              type: object
              required: [state, confirm, ct]
              properties:
                state: { type: string }
                confirm: { type: string, description: the terminal's user code, XXXX-XXXX }
                ct: { type: string, description: the browser-bound token from the round-1 response }
      responses:
        '200':
          description: the confirmed page, the re-rendered form (wrong code), or the refusal page
          content:
            text/html: { schema: { type: string } }
        '400':
          description: no oidc provider configured, or the form is missing its fields
          content:
            text/html: { schema: { type: string } }
        '401':
          description: unknown or expired sign-in state
          content:
            text/html: { schema: { type: string } }
  /v1/auth/token:
    post:
      operationId: refreshAuth
      summary: Exchange a refresh token for a new API token and a new refresh token (RFC 6749 §6)
      description: |
        Every use rotates the refresh token. Presenting the one just replaced within
        SH_REFRESH_REUSE_GRACE_SECONDS answers the same successor again; presenting any older one
        revokes the whole login (reuse detection). Every outcome is audited.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [grant_type, refresh_token]
              properties:
                grant_type: { type: string, enum: [refresh_token] }
                refresh_token: { type: string }
      responses:
        '200':
          description: the same body as /v1/auth/device/token
          content:
            application/json:
              schema:
                type: object
                required: [token, subject, expiresAt, refreshToken, refreshExpiresAt]
                properties:
                  token: { type: string }
                  subject: { type: string }
                  displayName: { type: string }
                  roles: { type: array, items: { type: string } }
                  expiresAt: { type: integer, description: epoch seconds }
                  refreshToken: { type: string, pattern: '^mrt_[A-Za-z0-9_-]{43}$' }
                  refreshExpiresAt: { type: integer, description: epoch seconds }
        '400':
          description: invalid_request, or invalid_grant — the refresh token is unknown, revoked, expired or replayed; log in again
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '403':
          description: |
            Sandbox profile only: `not_enrolled` -- the login's subject was removed from
            SH_ALLOWED_SUBJECTS since it logged in (sandbox-service spec §4.2). The control plane revokes the login
            (audited `refresh_revoked`, reason `not_enrolled`), so the refresh token presented is
            refused from then on; the client should forget it. The `message` names the subject.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '503':
          description: redis_unavailable
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/auth/revoke:
    post:
      operationId: revokeAuth
      summary: Revoke the login a refresh token belongs to (RFC 7009)
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [token]
              properties:
                token: { type: string }
      responses:
        '200':
          description: always, whether or not the token named a login
          content:
            application/json:
              schema: { type: object }
        '400': { $ref: '#/components/responses/BadRequest' }
        '503':
          description: redis_unavailable
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/auth/revoke-all:
    post:
      operationId: revokeAllAuth
      summary: Revoke every login of the calling subject
      security: [{ sessionToken: [] }]
      responses:
        '200':
          description: how many logins were revoked
          content:
            application/json:
              schema:
                type: object
                required: [revoked]
                properties:
                  revoked: { type: integer }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '503':
          description: redis_unavailable
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/me:
    get:
      operationId: getMe
      summary: The calling principal
      security: [{ sessionToken: [] }]
      responses:
        '200':
          description: subject, tenant, roles
          content:
            application/json:
              schema:
                type: object
                required: [subject, tenant, roles]
                properties:
                  subject: { type: string }
                  tenant: { type: string }
                  roles: { type: array, items: { type: string } }
        '401': { $ref: '#/components/responses/Unauthorized' }
  /v1/models:
    get:
      operationId: listModels
      summary: The models an inference credential reaches
      description: |
        Asked of the credential's own endpoint: LiteLLM's /model/info, or Anthropic's /v1/models for
        api.anthropic.com (ids only). `credential` omitted means the credential a new session would
        use: the only inference credential, or the operator fallback when the subject has none.

        The control plane asks only an allow-listed host: api.anthropic.com, the deployment default
        endpoint's host, or a host in SH_MODEL_CATALOG_HOSTS. Any other host is not contacted and
        answers 503 `model_catalog_unavailable`, as an unreachable endpoint does; every catalog
        failure carries the same message. Lists only concrete models: a LiteLLM wildcard route
        (e.g. `anthropic/*`) is not listed, though `model` on createSession / updateSession accepts
        an id it matches.
      security: [{ sessionToken: [] }]
      parameters:
        - { name: credential, in: query, required: false, schema: { type: string } }
      responses:
        '200':
          description: the catalog
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ModelList' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '404':
          description: '`credential_not_found`: no credential with that name'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '503':
          description: |
            `model_catalog_unavailable`: the endpoint could not list its models (unreachable,
            refused, an unreadable body, or a host outside the catalog allow-list)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/sessions:
    post:
      operationId: createSession
      summary: Create an owned session and mint its first session token
      description: |
        Resolves the inference credential AT CREATION and records the choice: a missing key must fail
        here, not three turns in (spec §6.4). Returns `credential_required` when the subject has none
        and `credential_ambiguous` when it has several and named none -- never a silent pick.

        `sandbox.tier` must be one of the tiers `/v1/discovery` advertises; omitted, the deployment
        default is recorded. A 400 `invalid_request` names the declared tiers. `sandbox`, when
        present, must be an object; any tier is a 400 on a deployment that declares none.

        `model`, when given, is checked against the credential's catalog (GET /v1/models):
        - listed → recorded with its limits, `modelVerified: true`;
        - not listed, but a LiteLLM wildcard route (e.g. `anthropic/*`) matches it as a whole string
          → recorded without limits, `modelVerified: true`;
        - the catalog cannot be read, or the endpoint's host is not in the catalog allow-list (see
          listModels) → recorded without limits, `modelVerified: false`;
        - otherwise → 400 `model_unavailable`.
      security: [{ sessionToken: [] }]
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                credentials:
                  type: object
                  properties:
                    inference: { type: string }
                configRef: { type: string, pattern: '^sha256:[0-9a-f]{64}$' }
                sandbox:
                  type: object
                  properties:
                    tier: { type: string }
                    template:
                      type: string
                      description: |
                        a template id from GET /v1/discovery's sandboxTemplates; 400 when unknown, or
                        on a deployment that declares none. Omitted: none, and the session runs only
                        on untemplated workers. With a template store (SH_PROVENANCE_DIR) it
                        resolves through the store as a sandbox's template does (combined control
                        plane spec §3.4): `id`, `id:tag` or `id@sha256:…`, a registered build the
                        caller may see (`400 unknown_template` otherwise), recorded as the session's
                        sandboxBuildId; and, with host agents, activation on first use
                        (`409 template_not_active`), which only a subject enrolled for sandboxes
                        starts (`403 not_enrolled` otherwise, combined control plane spec §3.4)
                    activate:
                      type: boolean
                      default: true
                      description: |
                        false to be refused on a template that is not active without starting its
                        activation (template lifecycle spec §6.4)
                model:
                  type: string
                  pattern: '^[\x21-\x7e]{1,256}$'
                  description: |
                    a model id the credential's endpoint lists (GET /v1/models), or one its
                    wildcard routes match
      responses:
        '201':
          description: created
          content:
            application/json:
              schema:
                type: object
                required: [sessionId, token, expiresAt]
                properties:
                  sessionId: { type: string }
                  token: { type: string }
                  expiresAt: { type: integer, description: epoch seconds }
                  model: { type: string }
                  modelVerified:
                    type: boolean
                    description: false when the catalog could not be read and the id was accepted unchecked
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403':
          description: |
            `not_enrolled` (combined profile): the session's template is not active and nobody is
            starting it, and the caller is not enrolled for sandboxes, so it cannot start it. With
            `sandbox.activate: false` the answer is 409 instead, as for anyone.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: |
            `template_not_active` (Retry-After): the session's template is not active yet, its
            activation started (by an enrolled caller) unless `sandbox.activate` is false, or
            already started by another subject; `no_active_slot` (Retry-After),
            `template_unavailable`: as activate (template lifecycle spec §6.4)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: |
            `config_bundle_not_found`: `configRef` names a digest that is not stored (never
            uploaded, or expired). Promote the directory first. Adopting a stored bundle refreshes
            its 30-day TTL.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
    get:
      operationId: listSessions
      summary: My sessions, newest first
      description: |
        Paged from the owner zset -- the only user-facing list path. `?owner=` requires the admin role
        and returns 403 otherwise.
      security: [{ sessionToken: [] }]
      parameters:
        - { name: limit, in: query, schema: { type: integer, default: 50, maximum: 200 } }
        - {
            name: cursor,
            in: query,
            schema: { type: integer },
            description: exclusive createdAt of the last item seen,
          }
        - { name: owner, in: query, schema: { type: string }, description: admin only }
      responses:
        '200':
          description: a page of sessions
          content:
            application/json:
              schema:
                type: object
                required: [sessions, nextCursor]
                properties:
                  sessions: { type: array, items: { $ref: '#/components/schemas/Session' } }
                  nextCursor: { type: [integer, 'null'] }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403':
          description: forbidden — ?owner= without the admin role
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/sessions/{id}:
    get:
      operationId: getSession
      summary: One of my sessions
      security: [{ sessionToken: [] }]
      parameters: [{ $ref: '#/components/parameters/sessionId' }]
      responses:
        '200':
          description: the session
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Session' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '404': { $ref: '#/components/responses/NotFound' }
    delete:
      operationId: deleteSession
      summary: Cascade-delete one of my sessions
      description: |
        Tombstone, then data, then index -- never the reverse, since dropping the index first leaves
        data present but invisible (spec §7.3).
      security: [{ sessionToken: [] }]
      parameters: [{ $ref: '#/components/parameters/sessionId' }]
      responses:
        '202': { description: accepted — a turn was in flight; the tombstone is set }
        '204': { description: deleted }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '404': { $ref: '#/components/responses/NotFound' }
    patch:
      operationId: updateSession
      summary: Switch the session's model
      description: |
        `model` is a model id, checked against the session's credential's catalog exactly as on
        createSession, or null for the deployment default:
        - listed → stored with its limits, `modelVerified: true`;
        - not listed, but a LiteLLM wildcard route (e.g. `anthropic/*`) matches it as a whole string
          → stored without limits, `modelVerified: true`;
        - the catalog cannot be read, or the endpoint's host is not in the catalog allow-list (see
          listModels) → stored without limits, `modelVerified: false`;
        - otherwise → 400 `model_unavailable`.
        A turn already running keeps its model; the next turn uses the new one. Any other field is
        `invalid_request`. A session deleted while the catalog answered is `session_not_found`, and
        nothing is written. Audited as `model_changed`.
      security: [{ sessionToken: [] }]
      parameters: [{ $ref: '#/components/parameters/sessionId' }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [model]
              additionalProperties: false
              properties:
                model: { type: [string, 'null'], pattern: '^[\x21-\x7e]{1,256}$' }
      responses:
        '200':
          description: the session, switched
          content:
            application/json:
              schema:
                allOf:
                  - { $ref: '#/components/schemas/Session' }
                  - type: object
                    properties:
                      modelVerified:
                        type: boolean
                        description: |
                          false when the catalog could not be read (or its host is not
                          allow-listed) and the id was accepted unchecked; true for null
                          (the deployment default)
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '404': { $ref: '#/components/responses/NotFound' }
  /v1/sessions/{id}/resources:
    get:
      operationId: getSessionResources
      summary: Where this session is running
      description: |
        Partly self-reported by the harness, which is the untrusted brain tier, so this projection is
        DISPLAY ONLY and is never consulted for authorization (spec §7.4). A Kubernetes outage yields
        `sandbox.phase: "unknown"` rather than an error.
      security: [{ sessionToken: [] }]
      parameters: [{ $ref: '#/components/parameters/sessionId' }]
      responses:
        '200':
          description: the projection
          content:
            application/json:
              schema:
                type: object
                required: [session, harness, sandbox]
                properties:
                  session:
                    type: object
                    required: [id, state, createdAt, lastTurnAt, turns, sandboxTier]
                    properties:
                      id: { type: string }
                      state: { type: string, enum: [active, deleting] }
                      createdAt: { type: integer, description: epoch ms }
                      lastTurnAt: { type: [integer, 'null'], description: epoch ms }
                      turns: { type: integer }
                      sandboxTier:
                        type: [string, 'null']
                        description: |
                          the sandbox tier the session runs in (P6.3), by the same rule as
                          Session.sandboxTier; from the control plane's own record, never from the
                          self-reported runtime hash
                  harness: { type: object }
                  sandbox: { type: object }
                  lease: { type: [object, 'null'] }
                  queue: { type: [object, 'null'] }
                  placement:
                    type: [object, 'null']
                    description: where the last leased turn ran; null until one has
                    required: [sandboxId, tier, workspaceReset]
                    properties:
                      sandboxId: { type: string }
                      tier: { type: [string, 'null'] }
                      workspaceReset:
                        type: [object, 'null']
                        description: when, and on which sandbox, the session last lost its workspace
                        required: [at, from]
                        properties:
                          at: { type: number, description: epoch ms }
                          from:
                            type: string
                            description: |
                              the sandbox the session left or, when its workspace was reclaimed
                              where it is, the sandbox it is still on
        '401': { $ref: '#/components/responses/Unauthorized' }
        '404': { $ref: '#/components/responses/NotFound' }
  /v1/sessions/{id}/models:
    get:
      operationId: listSessionModels
      summary: The models this session's credential reaches
      security: [{ sessionToken: [] }]
      parameters: [{ $ref: '#/components/parameters/sessionId' }]
      responses:
        '200':
          description: the catalog
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ModelList' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '404': { $ref: '#/components/responses/NotFound' }
        '503':
          description: '`model_catalog_unavailable`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/sessions/{id}/token:
    post:
      operationId: mintSessionToken
      summary: Re-mint a session token
      description: A session outlives a 5-minute token.
      security: [{ sessionToken: [] }]
      parameters: [{ $ref: '#/components/parameters/sessionId' }]
      responses:
        '200':
          description: a fresh session token
          content:
            application/json:
              schema:
                type: object
                required: [token, expiresAt]
                properties:
                  token: { type: string }
                  expiresAt: { type: integer }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '404': { $ref: '#/components/responses/NotFound' }
  /v1/sessions/{id}/turns:
    post:
      operationId: submitTurn
      summary: Submit a turn asynchronously
      description: |
        Async is a property of the TURN, not of the session, so one session may mix interactive and
        async turns (ADR-0047 §4.1). Answers `202` with the turn id and nothing else: no result and no
        partial state. Poll `GET /v1/sessions/{id}/turns/{turnId}` for both.

        `idempotencyKey` DEFAULTS TO THE SESSION ID, so a session holds at most one async turn in
        flight and a resubmission is deduplicated rather than queued behind -- matching the
        interactive `409 turn_in_progress`. A fan-out of N leaves is therefore N sessions, each with
        its own leaf result record. Resubmitting on a key whose turn is still non-terminal answers
        `202` with the EXISTING turn id.

        Interactive turns do not come through here: they stream over the harness's own
        `POST /turns` with a session token (docs/harness/reference/http-api.md).
      security: [{ sessionToken: [] }]
      parameters: [{ $ref: '#/components/parameters/sessionId' }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [async]
              properties:
                async:
                  type: boolean
                  description: |
                    must be `true`. The field exists so the async path is REQUESTED rather than
                    inferred from which other fields are present.
                kind:
                  type: string
                  description: the leaf kind; defaults to the kind implied by the payload field
                prompt: { type: string, description: a free-form turn }
                item:
                  type: object
                  description: a work item (`item_id`, `file`, `pattern`), as the fan-out leaves send
                problemStatement: { type: string, description: a SWE-bench style task }
                repoUrl: { type: string }
                ref: { type: string }
                idempotencyKey:
                  type: string
                  maxLength: 128
                  description: |
                    printable ASCII, 1-128 characters. Defaults to the session id.
                caps:
                  type: object
                  description: |
                    per-turn budget ceilings, recorded on the turn record and enforced by the worker
                    that runs it (ADR-0047 §5.1, #391); a cap above the deployment's own limit does
                    not raise it. A turn that spends either cap ends `failed` with
                    `result.reason: "budget"`.

                    `tokens` bounds this turn's assistant token spend and is enforced inside the run:
                    once it is reached, further tool calls are refused. `wallClock` bounds the turn
                    from the moment a worker dequeues it, clamped to the deployment's
                    `MOCA_TURN_MAX_S`.

                    Both are PER DELIVERY. A worker that dies mid-leaf has its turn redelivered, and
                    the retry gets a fresh token budget and a fresh wall clock anchored at its own
                    dequeue -- a retry must not fail on its predecessor's spend. So the aggregate
                    across a turn's deliveries can reach the cap times the delivery limit (three).
                    Size `tokens` as a per-attempt ceiling, not a total.

                    There is no `costUsd`: a present one is a 400 `invalid_request`. It was recorded
                    and never enforceable -- nothing here prices a token -- and silently ignoring a
                    spend cap is worse than refusing it. Use `tokens`.
                  properties:
                    tokens: { type: integer }
                    wallClock: { type: integer, description: seconds }
      responses:
        '202':
          description: accepted; poll the status route
          content:
            application/json:
              schema:
                type: object
                required: [sessionId, turnId]
                properties:
                  sessionId: { type: string }
                  turnId: { type: string }
        '400':
          description: '`invalid_json`, `invalid_request`, or `envelope_invalid`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '404': { $ref: '#/components/responses/NotFound' }
        '429':
          description: |
            `async_quota_exhausted`: the caller already holds `MOCA_ASYNC_QUEUED_PER_OWNER`
            non-terminal async turns. Refused BEFORE the enqueue, so nothing was created; the message
            names the caller's current count. Wait for one to finish rather than retrying immediately.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '501':
          description: |
            `workload_runs_unavailable` for a submission naming a `workloadId`, refused at submission
            so it stays synchronous rather than becoming a dead letter.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/sessions/{id}/turns/{turnId}:
    get:
      operationId: getTurn
      summary: An async turn's state
      description: |
        The turn record is the single source of truth for `state` and `attempts`; `result` appears
        once the leaf has written one. A turn reaped as lost reads `state: "lost"` -- which is why
        this route exists alongside `GET /runs/status`, whose inference from the result store cannot
        tell queued from never-submitted from reaped.

        `attempts` is DESCRIPTIVE -- the queue's own delivery count is the sole authority for retry
        exhaustion, so a client must not compute "gave up" from this number.
      security: [{ sessionToken: [] }]
      parameters:
        - { $ref: '#/components/parameters/sessionId' }
        - { $ref: '#/components/parameters/turnId' }
      responses:
        '200':
          description: the turn
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TurnStatus' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '404': { $ref: '#/components/responses/NotFound' }
    delete:
      operationId: cancelTurn
      summary: Cancel a queued or running async turn
      description: |
        A QUEUED turn flips to `cancelled` at once, and the drain loop drops it when it would have
        claimed it.

        A RUNNING turn is asked to stop (ADR-0047 §4.5, #391): the record keeps `state: "running"`
        and gains `cancelRequested: true`, and the worker running it stops the leaf within a few
        seconds, releasing its sandbox. The turn then reads `cancelled`, like a queued one. Poll
        `GET …/turns/{turnId}` for that; this route does not wait.

        Best-effort on purpose, which is why both answers are `202` rather than `200`: a leaf that
        finishes first stays finished, with its own terminal state and its result intact.

        Anything already terminal is `409`.
      security: [{ sessionToken: [] }]
      parameters:
        - { $ref: '#/components/parameters/sessionId' }
        - { $ref: '#/components/parameters/turnId' }
      responses:
        '202':
          description: cancelled (queued), or the cancel requested (running)
          content:
            application/json:
              schema:
                type: object
                required: [turnId, state]
                properties:
                  turnId: { type: string }
                  state: { type: string, enum: [cancelled, running] }
                  cancelRequested:
                    type: boolean
                    description: |
                      `true` only in the running case, where the state is still `running`: the stop
                      has been requested and not yet observed.
        '401': { $ref: '#/components/responses/Unauthorized' }
        '404': { $ref: '#/components/responses/NotFound' }
        '409':
          description: |
            `turn_not_cancellable`: the turn is already terminal. The message names its state.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/sessions/{id}/turns/{turnId}/artifacts/{kind}:
    get:
      operationId: getTurnArtifact
      summary: An async turn's output, whole
      description: |
        The output `GET …/turns/{turnId}` leaves out of its bounded body (#390), served as bytes with
        its own content type. `TurnStatus.result.artifacts` says which kinds this turn has: `patch`
        for the diff, `text` for the assistant's reply.

        `patch` is the diff exactly as the leaf produced it -- never truncated, and byte-exact for a
        diff that is not valid UTF-8 (the worker stores such a capture base64 and this route decodes
        it). `text` is the reply whole, which `TurnStatus.result.summary` only describes in one
        clipped line -- so for a prompt turn this route is the only way to read a long answer back.
        `ETag` is a `sha256:<hex>` digest of the bytes served, in the one format
        `TurnStatus.result.artifacts[].sha256` uses: the capture's own digest when the record carries
        one, and otherwise a digest of these bytes. It is for comparing what you hold against what
        the route would serve; this route does not honour `If-None-Match`, so every fetch is a `200`
        with the whole body.

        Everything absent is `404`, with a message naming which: an unknown kind, a kind this turn
        has nothing for (a solve has no `text`), a turn that is still queued or running, a terminal
        turn whose leaf stored no result, and a capture refused for size
        (`workspace.patchRefused`) -- in that last case the bytes never left the sandbox, so the
        descriptor in the status body is the whole answer.
      security: [{ sessionToken: [] }]
      parameters:
        - { $ref: '#/components/parameters/sessionId' }
        - { $ref: '#/components/parameters/turnId' }
        - name: kind
          in: path
          required: true
          schema: { type: string, enum: [patch, text] }
          description: the artifact kind, as named in `TurnStatus.result.artifacts[].kind`
      responses:
        '200':
          description: the artifact's bytes
          headers:
            ETag:
              description: >-
                `"sha256:<hex>"` — the capture's own digest when it has one, else a digest of these
                bytes. Not usable with `If-None-Match`: the route always serves the full body.
              schema: { type: string }
          content:
            text/x-diff:
              schema: { type: string, format: binary }
            text/plain:
              schema: { type: string }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '404': { $ref: '#/components/responses/NotFound' }
  /v1/credentials:
    get:
      operationId: listCredentials
      summary: My credentials — metadata only
      description: No value is ever returned, and there is no read-back path anywhere in /v1.
      security: [{ sessionToken: [] }]
      responses:
        '200':
          description: descriptors
          content:
            application/json:
              schema:
                type: object
                required: [credentials]
                properties:
                  credentials:
                    type: array
                    items: { $ref: '#/components/schemas/CredentialDescriptor' }
        '401': { $ref: '#/components/responses/Unauthorized' }
  /v1/credentials/{name}:
    put:
      operationId: putCredential
      summary: Store or rotate a credential — write-only
      security: [{ sessionToken: [] }]
      parameters: [{ $ref: '#/components/parameters/credentialName' }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              allOf:
                - $ref: '#/components/schemas/CredentialDescriptor'
                - type: object
                  required: [kind, consumer, destination]
                  properties:
                    secret:
                      type: object
                      additionalProperties: { type: string }
                      description: |
                        Exactly the fields the `kind` declares (bearer -> token, basic ->
                        username+password, api-key -> key, oauth2-token -> accessToken). Encrypted at
                        rest and never returned.
      responses:
        '204': { description: stored }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
    delete:
      operationId: deleteCredential
      summary: Delete a credential
      description: 204 whether or not it existed — a 404 would be an existence oracle over names.
      security: [{ sessionToken: [] }]
      parameters: [{ $ref: '#/components/parameters/credentialName' }]
      responses:
        '204': { description: deleted }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
  /v1/config-bundles:
    get:
      operationId: listConfigBundles
      summary: My config bundles, newest first
      description: |
        Read from the caller's own budget index, so it needs no keyspace scan and shows no other
        subject's bundles. Unpaged: the per-subject byte budget bounds how many a caller can hold.

        `bytes` is what the bundle is CHARGED — its stored (gzip) size, floored at 4096 — not the
        size of the tar that was uploaded. `promotedAt` is null for a bundle recorded before the
        server stored one, and a bundle stored without a budget entry (ADR-0030 `/promote`, which
        writes Redis directly) does not appear at all.

        A charge can outlive its stored bundle, since expired charges are reaped lazily on the next
        upload. Such an entry is still listed: it holds budget, and `DELETE` accepts it.
      security: [{ sessionToken: [] }]
      responses:
        '200':
          description: every live bundle charged to the caller
          content:
            application/json:
              schema:
                type: object
                required: [bundles]
                properties:
                  bundles:
                    type: array
                    items:
                      type: object
                      required: [digest, bytes, promotedAt, expiresAt]
                      properties:
                        digest: { type: string, pattern: '^sha256:[0-9a-f]{64}$' }
                        bytes:
                          type: integer
                          description: the charged bytes, not the uploaded tar's size
                        promotedAt:
                          type: [integer, 'null']
                          description: epoch ms the bundle was first stored; null for a legacy entry
                        expiresAt: { type: integer, description: epoch ms the charge ages out }
        '401': { $ref: '#/components/responses/Unauthorized' }
    post:
      operationId: putConfigBundle
      summary: Upload a client-built config bundle (ADR-0038)
      description: |
        Content-addressed: the server re-hashes the tar and refuses a mismatch. Idempotent; a digest
        that already exists only has its TTL refreshed. The decoded tar may be at most 8 MiB. New
        digests count against a per-subject and a deployment-wide byte budget (429 when full). A
        bundle whose `format.json` names a format newer than this release reads, or is not a format
        version, is refused `400 invalid_request`, with the reason in `message`; a bundle without it
        is format 1.
      security: [{ sessionToken: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [digest, tar]
              properties:
                digest: { type: string, pattern: '^sha256:[0-9a-f]{64}$' }
                tar: { type: string, contentEncoding: base64 }
      responses:
        '201':
          description: stored, or already present
          content:
            application/json:
              schema:
                type: object
                required: [digest, uploaded]
                properties:
                  digest: { type: string }
                  uploaded: { type: boolean, description: false when it already existed }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '429':
          description: |
            `bundle_quota_exceeded`: storing this NEW digest would exceed the caller's
            (`SH_BUNDLE_SUBJECT_BYTES`) or the deployment's (`SH_BUNDLE_TOTAL_BYTES`) byte budget.
            A digest that is already stored is always accepted.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/config-bundles/{digest}:
    delete:
      operationId: deleteConfigBundle
      summary: Delete a stored config bundle and free its budget (ADR-0038)
      description: |
        Allowed to the subject the digest is charged to (its first uploader) or an `admin`. A bundle
        stored without a budget entry (ADR-0030 `/promote`) is admin-only. Sessions created on the
        bundle get `410 config_bundle_not_found` on their next turn, as for an expired one.
      security: [{ sessionToken: [] }]
      parameters:
        - name: digest
          in: path
          required: true
          description: percent-encode the `:`
          schema: { type: string, pattern: '^sha256:[0-9a-f]{64}$' }
      responses:
        '204': { description: deleted }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403':
          description: '`forbidden`: the digest is charged to another subject and the caller is no admin'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: '`config_bundle_not_found`: no bundle and no budget entry for that digest'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/templates:
    get:
      operationId: listTemplates
      summary: The templates a sandbox may be created from, with their builds and readiness
      description: |
        Both profiles (template lifecycle spec §4.1): a sandbox client and a session's brain read
        the same templates. On the sandbox profile, enrolled subjects and admins only
        (`403 not_enrolled`, sandbox-service spec §4.2); on the harness profile, any logged-in subject, and a
        deployment that declares no templates lists none. Each template adds its owner,
        visibility, onboarding state, readiness, tags and builds (template lifecycle spec §3, §4);
        the first three fields are unchanged, so an older client reads the list as before. With
        SH_PROVENANCE_DIR, templates are the store's (SH_SANDBOX_TEMPLATES imported into it once);
        a `private` one is listed only to its owner and admins.
      security: [{ sessionToken: [] }]
      responses:
        '200':
          description: the visible templates, without their worker ids
          content:
            application/json:
              schema:
                type: object
                required: [templates, hosts]
                properties:
                  templates:
                    type: array
                    items: { $ref: '#/components/schemas/Template' }
                  hosts:
                    type: array
                    description: |
                      per KVM host, its limits and use, as its host agent last reported them
                      (template lifecycle spec §6.2); `active.used` counts the workers that stay
                      running on it (leased builds placed or running there, unleased ones draining a
                      live sandbox; graced builds are counted apart, in `graced`). Empty means no host
                      has reported, never that there is no limit. A host whose last inventory is over 6
                      minutes old is left out, here and in placement, until it reports again. `memory`
                      (1.12.0) only from an agent that reports it: then placement also needs the memory
                      for each new worker. `start` (1.13.0) only from an agent that reports its start
                      limit; `idleGraceSeconds` and `graced` (1.13.0) only from an agent that sets an idle
                      grace
                    items:
                      type: object
                      required: [id, active, idleLimitSeconds, disk]
                      properties:
                        id: { type: string }
                        active: { $ref: '#/components/schemas/LimitUse' }
                        idleLimitSeconds: { type: integer }
                        disk:
                          type: object
                          required: [freeGb, floorGb]
                          properties:
                            freeGb: { type: integer }
                            floorGb: { type: integer }
                        memory:
                          type: object
                          description: |
                            template lifecycle spec §6.2, all in MiB. `usedMib` is what placement
                            counts: each running worker's guest RAM + 128 (4096 + 128 for a build
                            with no recorded guest size), its VMs' committed memory, and the builds
                            placed here not started yet. `headroomMib` = min(total − floor − used,
                            available − floor − the pending starts), 0 while `brake` is set; a new
                            worker starts here only if its cost fits it
                          required:
                            [
                              totalMib,
                              availableMib,
                              floorMib,
                              usedMib,
                              headroomMib,
                              pressureFull10,
                              pressureLimit,
                              brake,
                              runningWorkers,
                              memfileMismatch,
                              reportedAt,
                            ]
                          properties:
                            totalMib: { type: integer }
                            availableMib: { type: integer }
                            floorMib:
                              type: integer
                              description: |
                                the effective floor the agent applies: SBX_MEM_FLOOR_MIB, else 10%
                                of MemTotal, at least 4096
                            usedMib: { type: integer }
                            headroomMib: { type: integer }
                            pressureFull10:
                              type: [number, 'null']
                              description: memory PSI `full avg10` (a percentage); null with no /proc/pressure
                            pressureLimit: { type: [number, 'null'] }
                            brake:
                              type: [string, 'null']
                              enum: [pressure, stale, null]
                              description: |
                                why the host takes no new start now (what it runs is kept): PSI over
                                its limit, or its last inventory over 60 s old; null otherwise
                            runningWorkers:
                              { type: integer, description: the template workers running there }
                            memfileMismatch:
                              type: array
                              items: { type: string }
                              description: build ids never placed there (their memory file is not the guest's size)
                            reportedAt:
                              { type: integer, description: epoch seconds of its last inventory }
                        start:
                          type: object
                          description: |
                            1.13.0 (template lifecycle spec §6.5), only from an agent that reports
                            its start limit: at most `concurrency` workers start at once there
                            (SBX_START_CONCURRENCY); `seconds` its measured mean cold start, start
                            to attach (null before one is done); `starting` and `queued` its start
                            line now (placed, wanted builds not attached: within the limit, and
                            beyond it), null when the relay's presence cannot be read
                          required: [concurrency, seconds, starting, queued]
                          properties:
                            concurrency: { type: integer, minimum: 1 }
                            seconds: { type: [number, 'null'] }
                            starting: { type: [integer, 'null'] }
                            queued: { type: [integer, 'null'] }
                        idleGraceSeconds:
                          type: integer
                          minimum: 1
                          description: |
                            1.13.0 (§6.5), only from an agent that sets one (SBX_IDLE_GRACE_S above
                            0): how long a released build's worker is kept running there
                        graced:
                          type: integer
                          description: |
                            1.13.0, beside idleGraceSeconds: the builds in the host's idle grace now
                            (no lease, worker kept running). Each still holds its whole pinned
                            memory file, counted in `memory.usedMib`, and a slot of `active.limit`
                            until a wanted build needs it
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/NotEnrolled' }
    post:
      operationId: createTemplate
      summary: Create a template (or a new build of your own), self-serve; policy decides
      description: |
        Template lifecycle spec §4, §8.1. Any enrolled client (sandbox profile) or logged-in
        subject (harness profile). Needs SH_PROVENANCE_DIR (else `400 invalid_request`). The create
        is checked against the deployment's policy (GET /v1/policy) before anything is queued: a
        refusal is `422 policy_refused` with `rule`, the gating rule's id
        (deploy/sbx/template-onboarding/governance/GATING-RULES.md), and a `check` record on the
        template's stream when the template exists and is the caller's (an admin's, adding a
        build); a refusal on a new id writes an audit-log line instead, and one on another subject's
        id is only answered. Ids are unique per deployment: another subject's id is
        `409 template_exists` (`404 template_not_found` when it is private). Over a quota:
        `429 quota_exceeded` with `quota` (`templates`, `buildsQueued` or `owned`). An admitted create
        writes `create`, `gate` (with a gate record) and `check` records and queues the build for
        a build host; follow it at `build`. A create whose inputs match a build of the caller's
        template that is registered or on its way (§3.2) queues nothing and answers that build with
        `reused: true`: `200` when it is registered, `202` while it is not. On a deployment with
        host agents, a registered build is not reused when fresh hosts (those whose last inventory
        is at most HOST_STALE_S, 360 s, old: the hosts placement counts) report and none holds its
        snapshot; the create is then admitted as a new build (`202`, no `reused`), with the usual
        quota and gate checks. When no fresh host reports at all, the registered build is reused
        as before. That new build registers under the same build id and supersedes the old one,
        which becomes `retired` (`reason.step: superseded`); its live leases move to the new
        build, and the tags that named it, `default` included, name the new build. It is
        rejected, rule `T.unique`, instead when a fresh host other than the one that built it
        holds the snapshot by then, or when the host that claimed it already held the snapshot.
        Only such a rebuild supersedes: another build of the same snapshot (another profile or
        gate record) is rejected `T.unique`. A failed or rejected build is never reused.
      security: [{ sessionToken: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/TemplateCreate' }
      responses:
        '200':
          description: a registered build of the same inputs, reused
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TemplateQueued' }
        '202':
          description: queued (or a reused build not yet registered)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TemplateQueued' }
        '400':
          description: '`invalid_request` (also: this deployment stores no templates)'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/NotEnrolled' }
        '404':
          description: "`template_not_found`: another subject's private template"
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: |
            `template_exists`: another subject's template; or `self_attested`: a self-attested
            create asking for `deployment` visibility, or a self-attested build added to a
            deployment-visible template
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '422':
          description: '`policy_refused`, with `rule`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '429':
          description: '`quota_exceeded`, with `quota`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/templates/{id}:
    get:
      operationId: getTemplate
      summary: One template, its builds with their specs (the seed included)
      description: |
        Both profiles (§4.1). `404 template_not_found` for an unknown id and for a `private`
        template the caller does not own: the existence check (template lifecycle spec §3.2).
      security: [{ sessionToken: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        '200':
          description: the template; each build carries its `spec`
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Template' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/NotEnrolled' }
        '404':
          description: '`template_not_found`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
    patch:
      operationId: updateTemplate
      summary: Change a template's description or visibility (the owner, or an admin)
      description: |
        Template lifecycle spec §5.1. `private` hides it from other subjects (they get 404, as for an
        id that does not exist) and refuses their new use; their sandboxes and sessions already made
        keep running. Each field that changes writes a `visibility` record (`field`, the new value
        and the one before); a field already at its value changes nothing.
      security: [{ sessionToken: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              minProperties: 1
              properties:
                visibility: { type: string, enum: [private, deployment] }
                description:
                  type: string
                  maxLength: 1024
                  description: no lone surrogate (a provenance record cannot hold one)
      responses:
        '200':
          description: changed (or already so)
          content:
            application/json:
              schema:
                type: object
                required: [templateId, subject, visibility, description, changes]
                properties:
                  templateId: { type: string }
                  subject: { type: string }
                  visibility: { type: string, enum: [private, deployment] }
                  description: { type: string }
                  changes:
                    type: array
                    items:
                      type: object
                      required: [field, value, before, record]
                      properties:
                        field: { type: string, enum: [visibility, description] }
                        value: { type: string }
                        before: { type: string }
                        record: { type: string, description: the visibility record written }
        '400':
          description: '`invalid_request`: no field, a bad value (a description holding a lone surrogate is one), or this deployment stores no templates'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403':
          description: "`not_enrolled`, or `forbidden`: neither the template's owner nor an admin"
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: '`template_not_found`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: |
            `self_attested`: `visibility: deployment` for a template with a self-attested build,
            registered or on its way there, until an admin trusts its gate record
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/templates/{id}/builds:
    get:
      operationId: listTemplateBuilds
      summary: A template's builds, newest first, each with its spec
      description: Both profiles (§4.1). `404 template_not_found` as for GET /v1/templates/{id}.
      security: [{ sessionToken: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        '200':
          description: the builds
          content:
            application/json:
              schema:
                type: object
                required: [builds]
                properties:
                  builds:
                    type: array
                    items: { $ref: '#/components/schemas/TemplateBuild' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/NotEnrolled' }
        '404':
          description: '`template_not_found`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
    post:
      operationId: createTemplateBuild
      summary: A new build of your own template (a new image or spec); as POST /v1/templates
      description: |
        The template must exist (`404 template_not_found`) and be the caller's
        (`409 template_exists`; an admin may add a build to any template); otherwise exactly
        POST /v1/templates, the body's `id` ignored, build reuse included.
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      security: [{ sessionToken: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/TemplateCreate' }
      responses:
        '200':
          description: a registered build of the same inputs, reused
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TemplateQueued' }
        '202':
          description: queued (or a reused build not yet registered)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TemplateQueued' }
        '400':
          description: '`invalid_request` (also: this deployment stores no templates)'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/NotEnrolled' }
        '404':
          description: "`template_not_found`: no such template, or another subject's private one"
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: |
            `template_exists`: another subject's template; or `self_attested`: a self-attested
            create asking for `deployment` visibility, or a self-attested build added to a
            deployment-visible template
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '422':
          description: '`policy_refused`, with `rule`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '429':
          description: '`quota_exceeded`, with `quota`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/templates/{id}/builds/{build}:
    get:
      operationId: getTemplateBuild
      summary: One build of a template, with its spec, by build id or by the create's handle
      description: |
        Both profiles (§4.1). The build id is `sha256:<manifest hash>`, or `imported:<12 hex>` for
        a template imported from SH_SANDBOX_TEMPLATES (no snapshot named); URL-encode it. A build
        created through the API is also found by the `b-<26 hex>` handle its create answered. A
        build id that a superseded build shares (1.23.0) names the build that took it over; the
        superseded one is found by its handle. `404 template_not_found` for an unknown template or
        build.
      security: [{ sessionToken: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
        - { name: build, in: path, required: true, schema: { type: string } }
      responses:
        '200':
          description: the build
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TemplateBuild' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/NotEnrolled' }
        '404':
          description: '`template_not_found`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
    delete:
      operationId: retireTemplateBuild
      summary: Retire one build (the owner, or an admin)
      description: |
        Template lifecycle spec §5.1. As `POST /v1/templates/{id}/retire`, for one build named by
        its build id or its handle; the template's other builds stay. If `default` names it,
        `default` moves to the newest registered build left (`default` in the answer, and a `tag`
        record), so a bare id keeps resolving; with none left it stays. Any other tag that points
        at it still resolves to it, and a create through that tag is refused
        `410 template_retired`, naming the tag. The retire record carries no reason (a DELETE has no
        body).
      security: [{ sessionToken: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
        - { name: build, in: path, required: true, schema: { type: string } }
      responses:
        '200':
          description: retired
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/RetiredBuild'
                  - type: object
                    required: [templateId, subject, status, default]
                    properties:
                      templateId: { type: string }
                      subject: { type: string, description: who retired it }
                      status: { type: string, enum: [retired] }
                      default: { $ref: '#/components/schemas/DefaultTagMove' }
        '400':
          description: '`invalid_request`: this deployment stores no templates'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403':
          description: "`not_enrolled`, or `forbidden`: neither the template's owner nor an admin"
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: '`template_not_found`: no such template, or no such build of it'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: '`build_in_use`: a live sandbox runs on the build, or an active session is pinned to it'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/templates/{id}/builds/{build}/reject:
    post:
      operationId: rejectTemplateBuild
      summary: Reject a registered build after the fact (an admin)
      description: |
        Template lifecycle spec §5.2: an admin rejects a registered build, named by its build id or
        its handle, when a rule is found broken after registration, with the reason. The build
        becomes `rejected` (`reason.rule` `admin`), its activation leases go, a host holding it
        stops its worker (`GET /v1/hosts/{host}/wanted` `stop`, as for a retired build), and a
        create naming it answers `400 unknown_template`, as for a build policy rejected at
        registration. A `reject` record names the admin, `from` (the status before),
        `buildRecord` (the digest of the build's `build` record) and the reason. Refused
        `409 build_in_use` while a live sandbox runs on it or an active session is pinned to it.
        Idempotent: an already rejected build is answered with `record: null`. If `default` names
        it, `default` moves to the newest registered build left, as on a retire (`default` in the
        answer). Not reversible: a new build is the way back. Needs SH_PROVENANCE_DIR.
      security: [{ sessionToken: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
        - { name: build, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [reason]
              properties:
                reason:
                  type: string
                  minLength: 1
                  maxLength: 1024
                  description: the rule found broken, and why; kept in the reject record
      responses:
        '200':
          description: rejected
          content:
            application/json:
              schema:
                type: object
                required: [templateId, subject, build, buildId, record, status, default]
                properties:
                  templateId: { type: string }
                  subject: { type: string, description: the admin }
                  default: { $ref: '#/components/schemas/DefaultTagMove' }
                  build: { type: string, description: the build's handle }
                  buildId: { type: [string, 'null'] }
                  record:
                    type: [string, 'null']
                    description: the reject record written; null if the build was already rejected
                  status: { type: string, enum: [rejected] }
        '400':
          description: '`invalid_request`: no reason, a build that is not registered, or this deployment stores no templates'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403':
          description: '`not_enrolled`, or `forbidden`: not an admin'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: '`template_not_found`: no such template, or no such build of it'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: '`build_in_use`: a live sandbox runs on the build, or an active session is pinned to it'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/templates/{id}/builds/{build}/cancel:
    post:
      operationId: cancelTemplateBuild
      summary: Withdraw a build not yet built (the owner)
      description: |
        Template lifecycle spec §5.1. The template's owner, or an admin, cancels a `queued`,
        `building` or `probing` build: it becomes `failed` with `reason.step` `cancelled`, and a
        `build` record (outcome `cancelled`) names who did it. A failed build takes no further
        report from a build host, so it never registers. Another subject: `403 forbidden`; an
        unknown build: `404 template_not_found`; any other status: `400 invalid_request`.
      security: [{ sessionToken: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
        - { name: build, in: path, required: true, schema: { type: string } }
      responses:
        '200':
          description: cancelled
          content:
            application/json:
              schema:
                type: object
                required: [templateId, build, status]
                properties:
                  templateId: { type: string }
                  build: { type: string, description: the build's handle }
                  status: { type: string, enum: [failed] }
        '400':
          description: '`invalid_request`: the build is not queued, building or probing, or this deployment stores no templates'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403':
          description: "`not_enrolled`, or `forbidden`: not the template's owner"
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: '`template_not_found`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/templates/{id}/retire:
    post:
      operationId: retireTemplate
      summary: Retire a template, every build of it (the owner, or an admin)
      description: |
        Template lifecycle spec §5.1. Every build not yet retired becomes `retired` (readiness
        `retired`) and its activation leases go, so it is no longer wanted: a host holding it is
        told to stop its worker (`GET /v1/hosts/{host}/wanted` `stop`). A sandbox or an activation
        naming the template, a tag of it or a build of it is then refused `410 template_retired`.
        Each build retired writes a `retire` record naming the caller, `from` (the status before)
        and `buildRecord` (the digest of the build's `build` record; null for one never built);
        its earlier records stay. Idempotent: an already retired build is listed with
        `record: null` (no second record). Refused `409 build_in_use` while a live sandbox runs on
        any of its builds, or an active session (`POST /v1/sessions` with a sandbox template) is
        pinned to one: delete it, then retire. A retire never cuts off running work. It cannot
        be undone: a new build of the template (`POST /v1/templates/{id}/builds`) is the way back,
        and the id stays its owner's. Needs SH_PROVENANCE_DIR.
      security: [{ sessionToken: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                reason: { type: string, maxLength: 1024, description: kept in each retire record }
      responses:
        '200':
          description: retired
          content:
            application/json:
              schema:
                type: object
                required: [templateId, subject, builds, status, default]
                properties:
                  templateId: { type: string }
                  subject: { type: string, description: who retired it }
                  status: { type: string, enum: [retired] }
                  default: { $ref: '#/components/schemas/DefaultTagMove' }
                  builds:
                    type: array
                    items: { $ref: '#/components/schemas/RetiredBuild' }
        '400':
          description: '`invalid_request`: a reason that is not a string of at most 1024 characters, or this deployment stores no templates'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403':
          description: "`not_enrolled`, or `forbidden`: neither the template's owner nor an admin"
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: '`template_not_found`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: '`build_in_use`: a live sandbox runs on one of its builds, or an active session is pinned to one'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/templates/{id}/tags:
    post:
      operationId: moveTemplateTags
      summary: Move tags onto a registered build (the owner, or an admin)
      description: |
        Template lifecycle spec §3.2, §5.1: tags are labels on builds, moved without rebuilding.
        After the move, `id:tag` (and the bare `id`, for `default`) resolves to the new build for
        new sandboxes and sessions; those already created keep their build. Each tag that changes
        writes a `tag` record (the new build and the one before); a tag already on the build
        changes nothing (`record: null`). A build that is not registered: `400 invalid_request`.
      security: [{ sessionToken: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [tags, build]
              properties:
                tags:
                  type: array
                  minItems: 1
                  maxItems: 16
                  uniqueItems: true
                  items: { type: string, pattern: '^[a-z0-9][a-z0-9-]{0,30}$' }
                build: { type: string, description: a build id or handle of this template }
      responses:
        '200':
          description: moved
          content:
            application/json:
              schema:
                type: object
                required: [templateId, subject, buildId, tags]
                properties:
                  templateId: { type: string }
                  subject: { type: string }
                  buildId: { type: string }
                  tags:
                    type: array
                    items:
                      type: object
                      required: [tag, buildId, before, record]
                      properties:
                        tag: { type: string }
                        buildId: { type: string }
                        before:
                          type: [string, 'null']
                          description: the build it named until now; null if new
                        record:
                          type: [string, 'null']
                          description: the tag record written; null if unchanged
        '400':
          description: '`invalid_request`: bad tags, a build that is not registered, or this deployment stores no templates'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403':
          description: "`not_enrolled`, or `forbidden`: neither the template's owner nor an admin"
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: '`template_not_found`: no such template, or no such build of it'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
    get:
      operationId: listTemplateTags
      summary: A template's tags, each with the build it names and when and by whom it was set
      description: Both profiles (§4.1). `404 template_not_found` as for GET /v1/templates/{id}.
      security: [{ sessionToken: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        '200':
          description: the tags, sorted by name
          content:
            application/json:
              schema:
                type: object
                required: [tags]
                properties:
                  tags:
                    type: array
                    items:
                      type: object
                      required: [tag, buildId, assignedAt, assignedBy]
                      properties:
                        tag: { type: string }
                        buildId: { type: string }
                        assignedAt: { type: integer, description: epoch seconds }
                        assignedBy:
                          type: [string, 'null']
                          description: a subject; null when the deployment set it
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/NotEnrolled' }
        '404':
          description: '`template_not_found`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/templates/{id}/tags/{tag}:
    delete:
      operationId: removeTemplateTag
      summary: Remove a tag (the owner, or an admin); its build stays
      description: |
        Template lifecycle spec §5.1. The tag goes; the build it named is not deleted and stays
        addressable by its build id. `default` is moved, never removed (`400 invalid_request`): the
        bare `id` must resolve. A `tag` record (`buildId: null`, the one before) names the caller.
      security: [{ sessionToken: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
        - { name: tag, in: path, required: true, schema: { type: string } }
      responses:
        '200':
          description: removed
          content:
            application/json:
              schema:
                type: object
                required: [templateId, subject, tag, buildId, before, record]
                properties:
                  templateId: { type: string }
                  subject: { type: string }
                  tag: { type: string }
                  buildId: { type: 'null' }
                  before: { type: string }
                  record: { type: string }
        '400':
          description: '`invalid_request`: the default tag, a tag name not matching `^[a-z0-9][a-z0-9-]{0,30}$`, or this deployment stores no templates'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403':
          description: "`not_enrolled`, or `forbidden`: neither the template's owner nor an admin"
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: '`template_not_found`: no such template, or no such tag on it'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/templates/{id}/owner:
    put:
      operationId: transferTemplateOwner
      summary: Transfer a template to another enrolled subject (an admin)
      description: |
        Template lifecycle spec §5.2. The new owner gets every owner action and its quota counts the
        template from now on; sandboxes and sessions already made keep their subjects. An `owner`
        record names the admin, the new owner and the one before; a transfer to the current owner
        changes nothing (`record: null`). The new owner must be enrolled (on the sandbox profile:
        SH_ALLOWED_SUBJECTS, or an admin). A template the deployment declared (imported from
        SH_SANDBOX_TEMPLATES, no owner) is handed to a subject the same way, `before: null`; its id
        then belongs to that subject, who can build, tag and edit it. A restart does not re-import it.
      security: [{ sessionToken: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [owner]
              properties:
                owner:
                  type: string
                  description: github:<numeric id> or oidc:<provider sub>; never test:<n>
                  pattern: '^(?:github:[0-9]+|oidc:[A-Za-z0-9][A-Za-z0-9._@+-]{0,127})$'
      responses:
        '200':
          description: transferred (or already theirs)
          content:
            application/json:
              schema:
                type: object
                required: [templateId, subject, owner, before, record]
                properties:
                  templateId: { type: string }
                  subject: { type: string, description: the admin }
                  owner: { type: string }
                  before: { type: [string, 'null'], description: null for a declared template }
                  record:
                    { type: [string, 'null'], description: the owner record; null if unchanged }
        '400':
          description: '`invalid_request`: a malformed or unenrolled subject, or this deployment stores no templates'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403':
          description: '`not_enrolled`, or `forbidden`: not an admin'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: '`template_not_found`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: |
            `self_attested`: the template has a self-attested build, registered or on its way
            there: it keeps its owner until an admin trusts its gate record
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/templates/{id}/activate:
    post:
      operationId: activateTemplate
      summary: Take or renew your activation lease on a registered build; a host agent starts its worker
      description: |
        Template lifecycle spec §6.3. Body `{tag?, build?, leaseSeconds?}`: the build by tag
        (default `default`) or build id; the lease 60-86400 s (default the largest
        `idleLimitSeconds` of the hosts that hold it, clamped to 60-86400, else 3600), renewed by calling again, without limit.
        A build is wanted running only while a lease stands, and a leased build is never evicted.
        An `activate` record on the template's stream; a sandbox created under the lease cites its
        digest as `lease`. One activation at a time: the quota and placement check, the record and
        the lease write run under one lock across all templates. Refusals keep no lease:
        `409 template_unavailable` (no registered build under that reference, or no host that
        reports holds it; `reason: memfile_mismatch` when every holder reports its memory file
        wrong), `409 no_active_slot` with `Retry-After` (every holder at its active limit with
        leased builds, or a lease in the same second as a placed build; `reason: memory` when a
        holder under its limit has no memory headroom for the worker; Retry-After is the seconds
        until a build placed on one of this build's holders loses its last live lease, else 60),
        `429 quota_exceeded` with `quota: active`, `410 template_retired` (the build is retired,
        §5.1). Needs SH_PROVENANCE_DIR.
      security: [{ sessionToken: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                tag: { type: string }
                build: { type: string }
                leaseSeconds: { type: integer, minimum: 60, maximum: 86400 }
      responses:
        '200':
          description: leased
          content:
            application/json:
              schema:
                type: object
                required: [templateId, buildId, leaseUntil, host]
                properties:
                  templateId: { type: string }
                  buildId: { type: string }
                  leaseUntil: { type: integer, description: epoch seconds }
                  host:
                    type: [string, 'null']
                    description: the host it is placed on; null while no host agent has reported
        '400':
          description: |
            `invalid_request` (a lease outside 60-86400 s; a template imported from
            SH_SANDBOX_TEMPLATES, which the deployment runs and which takes no lease; also: this
            deployment stores no templates)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/NotEnrolled' }
        '404':
          description: '`template_not_found`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: '`template_unavailable`, or `no_active_slot` with Retry-After; with `readiness`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '410':
          description: '`template_retired`: the build is retired'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '429':
          description: '`quota_exceeded`, with `quota: active`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/templates/{id}/deactivate:
    post:
      operationId: deactivateTemplate
      summary: Release your activation leases on a template; with none left, its worker drains and stops
      description: |
        Template lifecycle spec §6.3. Drops the caller's live leases on the template's builds (an
        admin with `{all: true}`, every subject's) and writes a `deactivate` record when it drops
        any. A build stays wanted while another subject's lease stands; with none left its host
        agent stops the worker once no live sandbox runs on it. Needs SH_PROVENANCE_DIR.

        On a host with an idle grace (SBX_IDLE_GRACE_S, 1.13.0, §6.5) the running worker of a build
        left with no lease is kept for that long after the release, so a use soon after is warm.
        `stopNow: true` skips the grace: once no lease is left (after this release), the worker is
        stopped at the host's next poll, as on a host with no grace; a build already in its grace
        has it ended (`released: 0`). The `deactivate` record carries `stopNow: true`. A stopNow
        while others hold leases changes nothing for them.
      security: [{ sessionToken: [] }]
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                all: { type: boolean, description: admins only; ignored otherwise }
                stopNow:
                  type: boolean
                  description: |
                    1.13.0, skip the host's idle grace (force a cold start next time); not a boolean
                    is `400 invalid_request`
      responses:
        '200':
          description: released
          content:
            application/json:
              schema:
                type: object
                required: [templateId, released]
                properties:
                  templateId: { type: string }
                  released: { type: integer, description: the leases dropped }
        '400':
          description: '`invalid_request`: this deployment stores no templates'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/NotEnrolled' }
        '404':
          description: '`template_not_found`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/policy:
    get:
      operationId: getPolicy
      summary: The deployment's template policy (profiles, envelopes, registries, trusted gate records, quotas)
      description: |
        Template lifecycle spec §8. Both profiles; any enrolled client. Its `record` is the
        provenance `policy` record every `check` cites; `digest` is the sha256 of the policy
        itself. Until an admin sets one, the default policy applies, recorded on first use. Needs
        SH_PROVENANCE_DIR.
      security: [{ sessionToken: [] }]
      responses:
        '200':
          description: the policy
          content:
            application/json:
              schema: { $ref: '#/components/schemas/PolicyView' }
        '400':
          description: '`invalid_request`: this deployment stores no templates'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/NotEnrolled' }
    put:
      operationId: putPolicy
      summary: Set the template policy (an admin); recorded
      description: |
        The policy is stored as sent, after validation (each problem named), and a new `policy`
        record names the admin who set it. Enforced on the next create. When it removes a gate
        record's sha256 from trustedGateRecords, the builds that become self-attested on a
        deployment-visible template make that template private on read; they are named as
        `narrowed` in the answer and in the `policy` record, so the narrowing is never silent.
        A change that widens it (adds to trustedGateRecords or allowedRegistries; adds to or
        drops a registry's allowedRepositories list; adds a profile; loosens one, by a rule dropped
        from requires, requireOfflineGate turned off, selfAttest or selfAttestEgress turned on, an
        envelope bound raised or removed, or its exact size changed or removed; or moves
        defaultProfile to one that accepts more) needs an admin named in SH_ADMIN_SUBJECTS
        where a members store is kept: an admin by an API grant is refused `403 forbidden`, and may
        still narrow it and change its quotas.
        With `?expect=` (the `digest` GET /v1/policy answered) the write is a compare-and-set: it is
        made only if the policy is still the one read; if anything changed since (another admin's
        policy or quota write, `PUT /v1/quota/{subject}` included), nothing is written or recorded
        and the answer is `409 policy_changed`, whose `digest` is the policy's now, so the client
        reads again. Without `expect`, the policy is stored as sent and replaces whatever was set
        meanwhile.
      security: [{ sessionToken: [] }]
      parameters:
        - name: expect
          in: query
          required: false
          description: >-
            A compare-and-set: the policy digest the client read (GET /v1/policy's `digest`,
            `sha256:` and 64 lowercase hex digits); another form is `400 invalid_request`. The
            write is made only if the policy's digest is that value now; else `409
            policy_changed`, with nothing written.
          schema: { type: string, pattern: '^sha256:[0-9a-f]{64}$' }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/Policy' }
      responses:
        '200':
          description: the policy as set, and `narrowed` when a trust removal narrowed templates
          content:
            application/json:
              schema:
                allOf:
                  - { $ref: '#/components/schemas/PolicyView' }
                  - type: object
                    properties:
                      narrowed:
                        type: array
                        items:
                          type: object
                          required: [template, buildId]
                          properties:
                            template: { type: string }
                            buildId: { type: string }
        '400':
          description: '`invalid_request`: the policy or `expect` is malformed, or this deployment stores no templates'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403':
          description: '`forbidden` (not an admin) or `not_enrolled`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: >-
            `policy_changed`: `expect` is not the policy's digest now; nothing written. The body's
            `digest` is the policy's now
          content:
            application/json:
              schema:
                allOf:
                  - { $ref: '#/components/schemas/Error' }
                  - type: object
                    required: [digest]
                    properties:
                      digest: { type: string, description: the policy's digest now }
  /v1/quota:
    get:
      operationId: getQuota
      summary: The caller's template quotas and use (§6.2), and the live-sandbox cap
      description: |
        The quotas that apply to the caller (its admin-set override, else the deployment default;
        `quotaSource` says which, and `ownedSource` for `owned`, which an override may leave to the
        default) and its use: templates owned (with a build registered or on its
        way there), builds queued, building or probing, builds the caller holds a live activation
        lease on (§6.3), and template ids owned in any status (`owned`). On the sandbox profile,
        `sandboxes` is the sandbox service's per-subject cap on live sandboxes (`SH_SANDBOX_MAX_PER_SUBJECT`) and
        the caller's live ones; absent elsewhere. Needs SH_PROVENANCE_DIR.
      security: [{ sessionToken: [] }]
      responses:
        '200':
          description: limits and use
          content:
            application/json:
              schema:
                type: object
                required:
                  [subject, templates, buildsQueued, active, owned, quotaSource, ownedSource]
                properties:
                  subject: { type: string }
                  templates: { $ref: '#/components/schemas/LimitUse' }
                  buildsQueued: { $ref: '#/components/schemas/LimitUse' }
                  active: { $ref: '#/components/schemas/LimitUse' }
                  owned: { $ref: '#/components/schemas/LimitUse' }
                  sandboxes: { $ref: '#/components/schemas/LimitUse' }
                  quotaSource:
                    type: string
                    enum: [subject, default]
                    description: an admin-set quota for this subject, or the deployment default
                  ownedSource:
                    type: string
                    enum: [subject, default]
                    description: >-
                      `owned` alone: the subject's override sets it, or it is the deployment
                      default's (200 when the default does not set it)
        '400':
          description: '`invalid_request`: this deployment stores no templates'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/NotEnrolled' }
  /v1/quota/{subject}:
    put:
      operationId: putQuota
      summary: Set the deployment's default quota, or one subject's (an admin); recorded
      description: |
        Template lifecycle spec §5.2. `subject` is `default` (the deployment default) or a subject
        (`github:<numeric id>` or `oidc:<provider sub>`, an override); a body of `null` removes a
        subject's override, returning it to the default (the default itself is never removed). A
        quota holds `templates`, `buildsQueued` and `active`, and optionally `owned`: another key is
        refused, so nothing else is kept in the policy. A body without `owned` keeps the target's
        `owned` as it is; an override without one has the default's. Each change is a policy change: a new `policy` record (the whole policy, `quotaBySubject`
        in it) naming the admin, whose digest is answered, so the chain shows who set which quota
        when. Enforced at once, on the next create, queued build and activation. Needs
        SH_PROVENANCE_DIR.
      security: [{ sessionToken: [] }]
      parameters:
        - { name: subject, in: path, required: true, schema: { type: string } }
        - name: expect
          in: query
          required: false
          description: >-
            A compare-and-set: the target's quota the client read, as JSON (a Quota, or `null` for
            a subject with no override), percent-encoded as a query value, e.g.
            `?expect=%7B%22templates%22%3A3%2C%22buildsQueued%22%3A1%2C%22active%22%3A1%7D` or
            `?expect=null`. Key order and spacing do not matter; the four counters are compared (an
            unset `owned` matches only an unset one), and another key is refused (`400
            invalid_request`), so a client sends the counters alone. The write is made only if the quota is that value now; else `409 quota_changed`, with
            nothing written.
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              oneOf:
                - $ref: '#/components/schemas/Quota'
                - type: 'null'
      responses:
        '200':
          description: set
          content:
            application/json:
              schema:
                type: object
                required: [target, subject, quota, before, policy, record]
                properties:
                  target:
                    { type: string, description: '`default` or the subject whose quota changed' }
                  subject: { type: string, description: the admin }
                  quota: { oneOf: [{ $ref: '#/components/schemas/Quota' }, { type: 'null' }] }
                  before: { description: 'the quota before (null: the subject had no override)' }
                  policy: { type: string, description: the new policy's digest }
                  record: { type: string, description: the policy record written }
        '400':
          description: '`invalid_request`: a bad target or quota (also one with a key beyond the four), or this deployment stores no templates'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403':
          description: '`forbidden` (not an admin) or `not_enrolled`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: '`quota_changed`: `expect` is not the quota now; nothing written'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/hosts/{host}/inventory:
    post:
      operationId: hostInventory
      summary: A host agent reports what it holds (by manifest hash) and its limits
      description: |
        Template lifecycle spec §6.1. The host's own bearer, SH_HOST_TOKEN_<ID> (SH_TEMPLATE_HOSTS);
        the host in the path must be the one whose token is presented. Body
        `{holds: [{template, manifestHash, running?}], limits: {activeLimit, idleLimitSeconds,
        buildConcurrency, diskFreeGb, diskFloorGb}, memory?}`. The control plane keeps each host's
        last inventory in its own process; the agent re-sends it on every poll. A host whose last
        inventory is over 6 minutes old is left out of placement until it reports again.

        `memory` (1.12.0) is optional: an agent before it sends none, and its host is placed by
        `activeLimit` alone, as before; a control plane before it ignores it. Each field is
        optional and a malformed one is dropped. `memTotalMib`, `memAvailableMib` and
        `memFloorMib` are used only all three together.

        `limits.startConcurrency` and `limits.startSeconds` (1.13.0, §6.5) are optional: the agent's
        start limit (SBX_START_CONCURRENCY, a whole number from 1) and the mean of its last cold
        starts, start to attach, in seconds (absent before one is done; used only beside
        startConcurrency). Without startConcurrency (an older agent) its builds have no place in a
        start line, and Retry-After is as before. `limits.idleGraceSeconds` (1.13.0, §6.5) is
        optional: SBX_IDLE_GRACE_S, a whole number of seconds, 0 (off) to 86400. Absent (an older
        agent), malformed or 0: no grace, as before.
      security: [{ hostToken: [] }]
      parameters:
        - { name: host, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                holds:
                  type: array
                  items:
                    type: object
                    properties:
                      template: { type: string }
                      manifestHash: { type: string, pattern: '^sha256:[0-9a-f]{64}$' }
                      running:
                        type: boolean
                        default: false
                        description: |
                          whether the build's worker unit runs on the host (placement counts it
                          against activeLimit and keeps the build there)
                limits:
                  type: object
                  properties:
                    activeLimit: { type: integer }
                    idleLimitSeconds: { type: integer }
                    buildConcurrency: { type: integer }
                    diskFreeGb: { type: integer }
                    diskFloorGb: { type: integer }
                    startConcurrency:
                      type: integer
                      minimum: 1
                      description: |
                        SBX_START_CONCURRENCY (default 4), at most this many workers starting at
                        once (1.13.0)
                    startSeconds:
                      type: number
                      description: |
                        the mean of the last (up to 10) cold starts, start to attach, seconds (1.13.0)
                    idleGraceSeconds:
                      type: integer
                      minimum: 0
                      maximum: 86400
                      description: |
                        SBX_IDLE_GRACE_S (default 0, off), how long a released build's worker is
                        kept running (1.13.0)
                memory:
                  type: object
                  description: what the host agent reads of its memory (template lifecycle spec §6.2)
                  properties:
                    memTotalMib: { type: integer, description: /proc/meminfo MemTotal, MiB }
                    memAvailableMib: { type: integer, description: /proc/meminfo MemAvailable, MiB }
                    memFloorMib:
                      type: integer
                      description: the effective floor (SBX_MEM_FLOOR_MIB, else 10% of MemTotal, at least 4096)
                    memPressureFull10:
                      type: number
                      description: |
                        /proc/pressure/memory `full avg10`, a percentage; absent with no
                        /proc/pressure (no brake)
                    memPressureLimit:
                      type: number
                      description: SBX_MEM_PRESSURE_LIMIT (default 10); above it, no new start on this host
                    runningWorkers:
                      type: array
                      items: { type: string }
                      description: the workers of held builds whose sbx-worker unit is active
                    vmCommittedMib:
                      type: object
                      additionalProperties: { type: integer }
                      description: |
                        worker id -> its VMs' unreclaimable memory, MiB: its slice's memory.stat
                        anon + shmem + kernel, never page cache; a worker whose slice could not be
                        read is absent
                    memfileMismatch:
                      type: array
                      items: { type: string }
                      description: |
                        manifest hashes of held builds whose memory file is not guest_ram_mb x 1 MiB:
                        never placed on this host
      responses:
        '200':
          description: recorded
          content:
            application/json:
              schema:
                type: object
                properties:
                  host: { type: string }
                  holds: { type: integer }
        '401': { $ref: '#/components/responses/Unauthorized' }
  /v1/hosts/{host}/builds/claim:
    post:
      operationId: hostClaimBuilds
      summary: A host agent claims up to `max` (at most 4) queued builds, oldest first, subjects in turn
      description: |
        Each claimed build moves to `building`, held by this host. Each comes with its template
        id, handle, image, the spec as template-build.sh reads it, and where to fetch its gate
        record (`/v1/hosts/{host}/blobs/{sha256}`).
      security: [{ hostToken: [] }]
      parameters:
        - { name: host, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object, properties: { max: { type: integer } } }
      responses:
        '200':
          description: the claimed builds (possibly none)
          content:
            application/json:
              schema:
                type: object
                required: [builds]
                properties:
                  builds:
                    type: array
                    items:
                      type: object
                      required: [template, build, image, spec]
                      properties:
                        template: { type: string }
                        build: { type: string }
                        image: { type: string }
                        spec: { type: object }
                        gateRecord: { type: string }
        '400':
          description: '`invalid_request`: this deployment stores no templates'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
  /v1/hosts/{host}/blobs/{digest}:
    get:
      operationId: hostBlob
      summary: A document the store holds by sha256 (a gate record), for a host agent
      security: [{ hostToken: [] }]
      parameters:
        - { name: host, in: path, required: true, schema: { type: string } }
        - { name: digest, in: path, required: true, schema: { type: string } }
      responses:
        '200':
          description: the document, base64 of its exact bytes
          content:
            application/json:
              schema:
                type: object
                properties:
                  sha256: { type: string }
                  base64: { type: string }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '404':
          description: '`not_found`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/hosts/{host}/builds/{build}/log:
    post:
      operationId: hostBuildLog
      summary: A host agent appends log entries to a build it claimed (at most 200 a call)
      security: [{ hostToken: [] }]
      parameters:
        - { name: host, in: path, required: true, schema: { type: string } }
        - { name: build, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                entries:
                  type: array
                  items:
                    type: object
                    properties:
                      level: { type: string, enum: [info, warn, error] }
                      step: { type: string }
                      message: { type: string }
      responses:
        '200':
          description: appended
          content:
            application/json:
              schema: { type: object, properties: { appended: { type: integer } } }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '404':
          description: '`not_found`: no such build claimed by this host'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/hosts/{host}/builds/{build}/report:
    post:
      operationId: hostBuildReport
      summary: A host agent reports a step of a build it claimed; `built` registers or rejects it
      description: |
        `{event: building | probing}`; `{event: failed, step, message}`; or `{event: built,
        templateRecord, manifest}`, each the host's file (T, S) as a string. On `built` the
        control plane stores both byte for byte, writes a `build` record, checks them against the
        create's request (§8.2: image, R's digest, manifest hash and version 2, size, gate
        record, X12) and registers the build (its id becomes the manifest hash; the template's
        first takes `default`) or rejects it naming the rule, writing a `check` record either way.
      security: [{ hostToken: [] }]
      parameters:
        - { name: host, in: path, required: true, schema: { type: string } }
        - { name: build, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema: { type: object }
      responses:
        '200':
          description: the build's new status
          content:
            application/json:
              schema:
                type: object
                required: [status]
                properties:
                  status: { type: string }
                  buildId: { type: string }
                  rule: { type: string }
        '400':
          description: '`invalid_request`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '404':
          description: '`not_found`: no such build claimed by this host'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/hosts/{host}/wanted:
    get:
      operationId: hostWanted
      summary: The workers a host agent should run (leased and placed on it), stop (no lease or retired, no live sandbox) and remove (retired, no live sandbox)
      description: |
        Template lifecycle spec §6.3. The host's own bearer. `run`: the registered builds this host
        holds whose lease stands and which placement puts on it, within its `activeLimit` and,
        from an agent that reports its memory, its memory headroom (the same placement an
        activation is judged by; a build already running on a holder stays there). `stop`: the
        ones it holds with no live lease and no idle grace, and a leased one it runs while placement
        keeps it on another host, each with no live sandbox on its worker, and the retired ones it
        holds (§5.1), or ones an admin rejected after the fact (§5.2), with no live sandbox; a
        worker with a live sandbox is in no list (it drains first, and counts against the host's
        `activeLimit` meanwhile). So is a worker a session pinned to its build had a turn on within
        the hold, when the session's subject is enrolled for sandboxes (combined control plane spec
        §3.4: the hosts' idle limit from that turn's credential exchange). `remove` (since 1.19.0;
        §6.1 step 7): the retired builds it holds with no live sandbox and no such hold, each listed
        in `stop` too, so the agent stops a running worker first (one whose sandbox ended less than
        600 s ago, still in `egressSids`, is in `stop` only until then: the removal ends the host's
        hold on the build, and with it the egress events it may ship for that sandbox); it then
        uninstalls the worker and deletes the snapshot and its template record, and reports
        `removed`. A build an admin rejected is in `stop` only, never in `remove`. The agent starts
        only workers already installed on the host. A build imported from SH_SANDBOX_TEMPLATES is in
        no list, retired, rejected or not: the deployment runs its worker. Nor is a retired build
        whose build id or worker a build that is neither retired nor rejected shares (in any
        template): its snapshot or worker is still needed.

        `run` is in the wanted order, first leased first (1.13.0, §6.5: the order the agent starts
        them in, at most its start limit at once). On a host with an idle grace the graced builds
        follow the wanted ones in `run`, soonest grace end first, and are listed in `graced`. A
        graced worker displaced for a wanted build is re-checked for a lease when the answer is
        made: a build leased since is left out of `stop` (its worker keeps running; it is in `run`
        from the next answer).
      security: [{ hostToken: [] }]
      parameters:
        - { name: host, in: path, required: true, schema: { type: string } }
      responses:
        '200':
          description: the wanted state
          content:
            application/json:
              schema:
                type: object
                required: [run, stop, remove]
                properties:
                  run: { type: array, items: { $ref: '#/components/schemas/WantedWorker' } }
                  stop: { type: array, items: { $ref: '#/components/schemas/WantedWorker' } }
                  remove: { type: array, items: { $ref: '#/components/schemas/WantedWorker' } }
                  starting:
                    type: array
                    items: { type: string }
                    description: |
                      1.13.0 (§6.5): the build ids of `run` whose worker is not attached to the
                      relay (its presence, which readiness reads), in `run`'s order. The agent
                      counts those whose unit is active as starting, for SBX_START_WINDOW_S at
                      most from its start (past it a worker is stuck and holds no start slot), and
                      starts at most SBX_START_CONCURRENCY less those. Absent from a control plane before 1.13.0,
                      or when the presence cannot be read: the agent then counts its own recent
                      starts (SBX_START_WINDOW_S).
                  graced:
                    type: array
                    items: { type: string }
                    description: |
                      1.13.0 (§6.5), only for a host whose agent reports an idle grace: the build
                      ids of `run` with no lease, kept running in the grace. The agent never starts
                      one (a grace keeps a running worker) and counts those it runs in its summary.
                      Absent from a control plane before 1.13.0, or for a host with no grace.
                  egressSids:
                    type: array
                    items: { type: string }
                    description: |
                      The workspace keys of the sandboxes whose egress events this host ships:
                      every sandbox on a worker of a build it holds, live or ended less than 600 s
                      ago, the set `POST /v1/hosts/{host}/egress` accepts. The agent sends only these
                      sandboxes' events (and `audit_dropped` reports), so the proxy's other clients'
                      events never leave the host. Absent from a control plane before 1.14.0: the agent
                      then sends nothing.
        '400':
          description: '`invalid_request`: this deployment stores no templates'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
  /v1/hosts/{host}/workers/report:
    post:
      operationId: hostWorkerReport
      summary: A host agent reports a worker attached, refused, detached or removed (provenance; readiness is the relay's)
      description: |
        Template lifecycle spec §6.3. For a registered build this host holds: `attached` (its
        worker unit started) and `refused` (not started, with why: not installed, or the start
        failed) write an `activate` record, `detached` (stopped; also for a retired build, or one
        an admin rejected after the fact, whose worker `stop` lists) a `deactivate` record, each
        with the subject `host:<host>`. A `refused` that repeats this host's last one for the build
        (the same reason) while the build stays in the host's `run` is not recorded again
        (`recorded: null`): the agent retries every 15 s, and the stream is append-only. For a
        retired build this host holds, `removed` (since 1.19.0; its worker uninstalled, its snapshot
        and template record deleted, §6.1 step 7) writes a `retire` record by `host:<host>` with
        `event: removed` and `buildRecord`, the digest of the build's `build` record, and the host
        no longer holds the build (`heldBy` drops it); refused `409 build_in_use` for a build the
        wanted state leaves out because a build neither retired nor rejected shares its build id or
        worker. An admin-rejected build takes no `removed`. Readiness never comes from a report:
        `active` is the relay's attached record.
      security: [{ hostToken: [] }]
      parameters:
        - { name: host, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [buildId, event]
              properties:
                buildId: { type: string }
                event: { type: string, enum: [attached, refused, detached, removed] }
                reason: { type: string, maxLength: 1024 }
      responses:
        '200':
          description: recorded
          content:
            application/json:
              schema:
                type: object
                properties:
                  recorded:
                    type: [string, 'null']
                    description: the event recorded; null for a repeated refusal, not recorded
        '400':
          description: '`invalid_request`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '404':
          description: '`not_found`: no registered build this host holds (for `detached`: no registered or retired one; for `removed`: no retired one)'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: '`build_in_use`: a `removed` for a retired build whose build id or worker a build neither retired nor rejected shares (the wanted state never lists it)'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/hosts/{host}/egress:
    post:
      operationId: hostEgress
      summary: A host agent posts the egress proxy's audit events from its journal
      description: |
        Up to 1000 events, each exactly as `moca-egress` wrote it, and the journal cursor after the
        last. An event is stored in a sandbox's log when its `sid` is the workspace key of a
        sandbox on a worker of a build this host holds, and the sandbox ended at most 600 s ago;
        every other event is refused and counted. One naming such a sandbox that is not exactly a
        proxy Event (an unknown field, a wrong type) is not stored, and counted as dropped there.
        An `audit_dropped` event (no VM) is charged to every sandbox on this host's workers live
        within 60 s before it, its count taken up to 1,000,000. A log holds at most 10,000 events and 4 MiB of lines, and all logs
        together at most 64 MiB of lines; the rest count as dropped (`cap`, `budget`).
        Idempotent by (host, cursor): a post repeating the host's last cursor appends nothing and
        answers as the first.
      security: [{ hostToken: [] }]
      parameters:
        - { name: host, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [events, cursor]
              properties:
                events:
                  {
                    type: array,
                    maxItems: 1000,
                    items: { $ref: '#/components/schemas/EgressEvent' },
                  }
                oversized:
                  type: array
                  items: { type: string }
                  description: |
                    the sid of each event the agent kept back for its size (over 8 KiB); each is
                    counted as dropped in its sandbox's log. events and oversized: 1000 in all
                cursor:
                  {
                    type: string,
                    maxLength: 512,
                    description: 'the journal cursor after the last event',
                  }
      responses:
        '200':
          description: appended (or a replay's first answer)
          content:
            application/json:
              schema:
                type: object
                required: [accepted, refused, capped, overBudget, invalid, dropped, cursor]
                properties:
                  accepted: { type: integer }
                  refused:
                    { type: integer, description: "no sandbox of this host's, or its log sealed" }
                  capped:
                    { type: integer, description: "over a log's cap (10,000 events or 4 MiB)" }
                  overBudget: { type: integer, description: 'over the 64 MiB of all logs together' }
                  invalid:
                    type: integer
                    description: "named a sandbox of this host's but not a proxy Event, or oversized"
                  dropped:
                    { type: integer, description: "the audit_dropped reports' counts, summed" }
                  cursor: { type: string }
        '400':
          description: '`invalid_request`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '503':
          description: redis_unavailable
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/subjects:
    get:
      operationId: listSubjects
      summary: Every enrolled subject, with its roles and where each comes from (an admin)
      description: |
        Enrollment and roles spec §4. Any admin may read it. A subject is enrolled by the deployment's
        settings (`source: env`: SH_ALLOWED_SUBJECTS, SH_ADMIN_SUBJECTS) or through this API
        (`source: api`). Roles are evaluated per request: an API grant past its `until` is not listed.
      security: [{ sessionToken: [] }, { installerToken: [] }]
      responses:
        '200':
          description: the subjects
          content:
            application/json:
              schema:
                type: object
                required: [subjects]
                properties:
                  subjects: { type: array, items: { $ref: '#/components/schemas/Subject' } }
        '400':
          description: '`invalid_request`: a malformed subject or body, or no members store (SH_PROVENANCE_DIR unset)'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403':
          description: '`not_enrolled`, or `forbidden`: not an admin, or (a change) not an admin named in the settings'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/subjects/{subject}:
    put:
      operationId: enrollSubject
      summary: Enroll a subject (an admin)
      description: |
        Body `{"enrolled": true}`. Writes a `member` record on the `members` provenance stream, naming
        the admin. Enrolled at the subject's next request. Enrolling one already enrolled writes nothing,
        and so does enrolling one the settings enroll (SH_ALLOWED_SUBJECTS or SH_ADMIN_SUBJECTS): it is
        answered unchanged (`record: null`), so the store never holds an enrollment hidden behind the
        settings.
      security: [{ sessionToken: [] }, { installerToken: [] }]
      parameters:
        - name: subject
          in: path
          required: true
          schema:
            { type: string, pattern: '^(?:github:[0-9]+|oidc:[A-Za-z0-9][A-Za-z0-9._@+-]{0,127})$' }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [enrolled]
              properties: { enrolled: { type: boolean, enum: [true] } }
      responses:
        '200':
          description: enrolled
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Subject'
                  - type: object
                    required: [record]
                    properties:
                      record:
                        type: [string, 'null']
                        description: the `member` or `role` record written (null when nothing changed)
        '400':
          description: '`invalid_request`: a malformed subject or body, or no members store (SH_PROVENANCE_DIR unset)'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403':
          description: '`not_enrolled`, or `forbidden`: not an admin, or (a change) not an admin named in the settings'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
    delete:
      operationId: unenrollSubject
      summary: Unenroll a subject enrolled through the API (an admin)
      description: |
        Writes a `member` record. The subject is refused at its next request (`403 not_enrolled`); its
        live sandboxes run to their expiry and its templates keep their owner. A subject enrolled by
        the settings can't be unenrolled here: `409 bootstrap_subject`. A subject holding an admin grant
        is enrolled by it, so unenrolling it would change nothing: `409 admin_granted` (revoke the role
        first).
      security: [{ sessionToken: [] }, { installerToken: [] }]
      parameters:
        - name: subject
          in: path
          required: true
          schema:
            { type: string, pattern: '^(?:github:[0-9]+|oidc:[A-Za-z0-9][A-Za-z0-9._@+-]{0,127})$' }
      responses:
        '200':
          description: unenrolled (or it was not)
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Subject'
                  - type: object
                    required: [record]
                    properties:
                      record:
                        type: [string, 'null']
                        description: the `member` or `role` record written (null when nothing changed)
        '400':
          description: '`invalid_request`: a malformed subject or body, or no members store (SH_PROVENANCE_DIR unset)'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403':
          description: '`not_enrolled`, or `forbidden`: not an admin, or (a change) not an admin named in the settings'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: '`bootstrap_subject`: enrolled by SH_ALLOWED_SUBJECTS or SH_ADMIN_SUBJECTS; `admin_granted`: it holds an admin grant (revoke it first)'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/subjects/{subject}/roles/admin:
    put:
      operationId: grantAdmin
      summary: Grant the admin role, optionally until a time (an admin)
      description: |
        Only an admin named in the settings (SH_ADMIN_SUBJECTS) may grant it; an API-granted admin
        is refused `403 forbidden`. An optional `until` (epoch seconds, in the future and at most 366
        days ahead, so a value in milliseconds is refused `400 invalid_request`) makes it
        lapse by itself; the first request that
        sees it lapsed writes a `role` record `expired`, once. A grant writes a `role` record
        `granted`, naming the admin and `until`. Effective at the subject's next request.
      security: [{ sessionToken: [] }, { installerToken: [] }]
      parameters:
        - name: subject
          in: path
          required: true
          schema:
            { type: string, pattern: '^(?:github:[0-9]+|oidc:[A-Za-z0-9][A-Za-z0-9._@+-]{0,127})$' }
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                until:
                  {
                    type: [integer, 'null'],
                    description: 'epoch seconds, at most 366 days ahead; absent or null: no expiry',
                  }
      responses:
        '200':
          description: granted
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Subject'
                  - type: object
                    required: [record]
                    properties:
                      record:
                        type: [string, 'null']
                        description: the `member` or `role` record written (null when nothing changed)
        '400':
          description: '`invalid_request`: a malformed subject or body, or no members store (SH_PROVENANCE_DIR unset)'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403':
          description: '`not_enrolled`, or `forbidden`: not an admin, or (a change) not an admin named in the settings'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: '`bootstrap_subject`: an admin by SH_ADMIN_SUBJECTS'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
    delete:
      operationId: revokeAdmin
      summary: Revoke an API-granted admin role (an admin)
      description: |
        Writes a `role` record `revoked`. Refused for an admin by the settings (`409
        bootstrap_subject`) and for the caller's own role (`409 self_revoke`), so the API can't
        lock itself out.
      security: [{ sessionToken: [] }, { installerToken: [] }]
      parameters:
        - name: subject
          in: path
          required: true
          schema:
            { type: string, pattern: '^(?:github:[0-9]+|oidc:[A-Za-z0-9][A-Za-z0-9._@+-]{0,127})$' }
      responses:
        '200':
          description: revoked (or it held none)
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Subject'
                  - type: object
                    required: [record]
                    properties:
                      record:
                        type: [string, 'null']
                        description: the `member` or `role` record written (null when nothing changed)
        '400':
          description: '`invalid_request`: a malformed subject or body, or no members store (SH_PROVENANCE_DIR unset)'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403':
          description: '`not_enrolled`, or `forbidden`: not an admin, or (a change) not an admin named in the settings'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: '`bootstrap_subject` (an admin by SH_ADMIN_SUBJECTS), or `self_revoke`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/sandboxes:
    description: |
      Sandbox service control planes only (`SH_ROUTE_PROFILE=sandbox`); a MOCA control plane answers
      404 (sandbox-service spec §4.1).
    post:
      operationId: createSandbox
      summary: Create a sandbox
      description: |
        Enrolled subjects and admins only. Does no I/O to the worker: the first Exec creates the
        workspace, so a new sandbox always starts empty (sandbox-service spec §5.1).

        Activation on first use (template lifecycle spec §6.4), on a deployment with template hosts
        (SH_TEMPLATE_HOSTS): a sandbox is created only on an `active` build. On one that is not, the
        create takes the caller's activation lease (as POST /v1/templates/{id}/activate, with its
        refusals: `409 no_active_slot`, `409 template_unavailable`, `429 quota_exceeded`; the
        `activate` record says `reason: first_use`; not taken again while the caller holds a live
        lease on the build, so a retry writes nothing) and answers `409 template_not_active` with
        `readiness` and `Retry-After`; retry after the wait. Retry-After is 30 s, or (1.13.0, §6.5)
        the build's place in its host's start line, when the host's agent reports its start limit
        and a measured start time: `ceil(ceil(queuePosition / startConcurrency) × startSeconds)`. A
        build in its host's idle grace (1.13.0) is served at once. With `activate: false` nothing is
        started. No sandbox record is kept while waiting, so a wait never uses the live-sandbox cap.
        The gate applies before any host has reported too: an attached worker serves, an absent one
        is refused. Without template hosts the create succeeds as before, and so it does on a template
        imported from SH_SANDBOX_TEMPLATES (no host holds it: the deployment runs its worker). The `sandbox` record's
        `lease` is the digest of the `activate` record of the caller's live lease on the build.
      security: [{ sessionToken: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [template]
              properties:
                template:
                  type: string
                  description: |
                    a template from GET /v1/templates, as `id` (its `default` tag), `id:tag` or
                    `id@<build id>`: resolved to one registered build at creation and kept for the
                    sandbox's life (template lifecycle spec §3.2)
                activate:
                  type: boolean
                  default: true
                  description: |
                    false: on a build that is not active, be refused without starting its
                    activation (§6.4)
                name: { type: string, pattern: '^[a-z0-9][a-z0-9-]{0,62}$' }
                labels:
                  type: object
                  maxProperties: 16
                  propertyNames: { pattern: '^[a-z0-9][a-z0-9._-]{0,62}$' }
                  additionalProperties: { type: string }
                  description: at most 16 pairs; each value at most 256 UTF-8 bytes
                mode:
                  type: string
                  enum: [per-exec, lease, lease+processes]
                  description: |
                    default `per-exec`. A lease mode must be listed in SH_SANDBOX_MODES_ALLOWED
                    (default `per-exec`: no lease mode), else 403 `mode_not_allowed`; `per-exec`
                    always is.
                idleTimeoutS:
                  type: integer
                  minimum: 30
                  description: |
                    the lease idle timeout in seconds, at most SH_SANDBOX_IDLE_CEILING_S (default
                    1800). Omit it for the worker's default (stored as 0); an explicit 0 is refused
                    (400).
                idleLifetimeS:
                  type: integer
                  minimum: 3600
                  description: |
                    how long the sandbox lives past its last activity, in seconds, at most
                    SH_SANDBOX_MAX_LIFETIME_SECONDS (unset: SH_SANDBOX_LIFETIME_SECONDS;
                    deploy/sbx/setup.sh sets 30 days). Omit it for SH_SANDBOX_LIFETIME_SECONDS
                    (default 604800). `expiresAt` starts at now plus this.
      responses:
        '201':
          description: |
            the new sandbox, ready: mode epoch 0 for `per-exec`, 1 for a lease mode, which the worker
            serves per-Exec until the first LeaseControl set_mode (POST .../mode-token mints one)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Sandbox' }
        '400':
          description: |
            `invalid_json`, `invalid_request`, or `unknown_template` (an unknown id, tag or build,
            or one the caller cannot see)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403':
          description: '`not_enrolled`, or `mode_not_allowed`: the deployment does not allow that mode'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: |
            `name_conflict`: the caller already has a live sandbox with that name;
            `template_not_active` (Retry-After), with `readiness`: the build is not active yet, its
            activation started unless `activate: false` (with readiness `unavailable`, `reason` is
            its readinessReason); `no_active_slot` (Retry-After) and
            `template_unavailable`: as activate
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '410':
          description: |
            `template_retired`: the template, the tag or the build it names is retired, or every
            build of the template is (template lifecycle spec §5.1)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '429':
          description: |
            `quota_exceeded`: per-user or deployment-wide live sandboxes (sandbox-service spec §5.3), or, on first
            use, the active-template quota (`quota: active`)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '503':
          description: redis_unavailable
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
    get:
      operationId: listSandboxes
      summary: My sandboxes, newest first
      description: |
        The caller's own, terminated (but retained) ones included. `?all=1` lists everyone's and
        requires the admin role.
      security: [{ sessionToken: [] }]
      parameters:
        - name: state
          in: query
          required: false
          schema: { type: string, enum: [ready, terminated] }
        - name: all
          in: query
          required: false
          description: admins only
          schema: { type: string, enum: ['1'] }
      responses:
        '200':
          description: the sandboxes, newest first
          content:
            application/json:
              schema:
                type: object
                required: [sandboxes]
                properties:
                  sandboxes: { type: array, items: { $ref: '#/components/schemas/Sandbox' } }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403':
          description: '`not_enrolled`, or `forbidden`: ?all= without the admin role'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '503':
          description: redis_unavailable
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/sandboxes/{id}:
    get:
      operationId: getSandbox
      summary: One sandbox
      description: The caller's own; admins may read any. Another user's sandbox is a 404.
      security: [{ sessionToken: [] }]
      parameters: [{ $ref: '#/components/parameters/sandboxId' }]
      responses:
        '200':
          description: the sandbox
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Sandbox' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/NotEnrolled' }
        '404': { $ref: '#/components/responses/NotFound' }
        '503':
          description: redis_unavailable
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
    delete:
      operationId: deleteSandbox
      summary: Terminate a sandbox
      description: |
        Idempotent: deleting a terminated sandbox answers 200 with how it ended. The caller's own;
        admins may delete any. The host janitor frees the workspace later (sandbox-service spec §8.3).
      security: [{ sessionToken: [] }]
      parameters: [{ $ref: '#/components/parameters/sandboxId' }]
      responses:
        '200':
          description: terminated
          content:
            application/json:
              schema:
                type: object
                required: [id, state, reason]
                properties:
                  id: { type: string }
                  state: { type: string, enum: [terminated] }
                  reason: { type: string, enum: [deleted, expired] }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/NotEnrolled' }
        '404': { $ref: '#/components/responses/NotFound' }
        '503':
          description: redis_unavailable
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/sandboxes/{id}/token:
    post:
      operationId: mintSandboxToken
      summary: Mint a sandbox token for Exec
      description: |
        Owner only, admins included: an admin calling it on another user's sandbox gets the same
        404 as anyone else (sandbox-service spec §4.2). The token's `exp` is the sooner of now plus
        SH_SANDBOX_TOKEN_TTL_SECONDS and the sandbox's `expiresAt`, after an activity mint moved it
        to at least now plus the sandbox's `idleLifetimeS` (§4.3; idle-lifetime spec §4.2); the
        move happens only when SH_SANDBOX_MAX_LIFETIME_SECONDS is configured, else the deadline is
        fixed at creation. A sandbox whose lease
        mode SH_SANDBOX_MODES_ALLOWED no longer lists is first set to `per-exec` at the next epoch,
        and the `idle_timeout_s` claim is clamped to SH_SANDBOX_IDLE_CEILING_S (lease-mode spec
        §8.1). The optional body `{ "activity": false }` mints without moving the deadline; a
        non-boolean `activity` is refused (400).
      security: [{ sessionToken: [] }]
      parameters: [{ $ref: '#/components/parameters/sandboxId' }]
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                activity:
                  type: boolean
                  default: true
                  description: >-
                    false: mint without counting as activity (the deadline does not move); for
                    mints that run no command, e.g. a lease keepalive
      responses:
        '400': { $ref: '#/components/responses/BadRequest' }
        '200':
          description: a sandbox token, and where to send Exec with it
          content:
            application/json:
              schema:
                type: object
                required: [token, expiresAt, sandboxExpiresAt, execEndpoint, wrk, wsk, execCa]
                properties:
                  token: { type: string, description: 'JWT, typ moca-sandbox+jwt' }
                  expiresAt: { type: integer, description: epoch seconds }
                  sandboxExpiresAt:
                    type: integer
                    description: the sandbox's expiresAt after this mint; track it, it moves
                  execEndpoint: { type: string, description: 'host:port of the exec Route' }
                  wrk:
                    type: string
                    description: the worker sandbox_id serving the template (ExecRequest.sandbox_id)
                  wsk: { type: string, description: the workspace key (Exec.workspace_key) }
                  execCa:
                    type: [string, 'null']
                    description: the exec Route's CA (PEM) when self-issued, else null
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/NotEnrolled' }
        '404': { $ref: '#/components/responses/NotFound' }
        '409':
          description: '`sandbox_terminated`, with `reason` (deleted | expired)'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '503':
          description: redis_unavailable
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/sandboxes/{id}/egress:
    get:
      operationId: getSandboxEgress
      summary: A sandbox's egress log
      description: |
        The egress proxy's audit events for this sandbox, as the KVM host's proxy wrote them
        (`moca-egress`'s Event: time, via, vm_id, sid, sub, host, dial_addr, method, path without
        query, fragment or userinfo, status, bytes_up, bytes_down, credential NAME, decision,
        dropped, coalesced), in arrival order. The caller's own sandbox; admins may read any, as
        `GET /v1/sandboxes/{id}`. Kept as long as the sandbox record (SH_SANDBOX_RETENTION_SECONDS).

        Paths are logged without query, fragment or userinfo, and an injected credential appears by
        name only, but a secret a guest puts in a URL path segment is logged as sent.

        `format=ndjson` returns the whole log, one canonical JSON event per line, each ended by
        `\n`, streamed (chunked); a store failure after the first chunk cuts it short, so check
        its sha256. Its sha256 is `summary.sha256`, and the sandbox's end record's `egress.sha256` (or a
        later `sandbox` record with `state: egress`, when events arrived after the end).
      security: [{ sessionToken: [] }]
      parameters:
        - { $ref: '#/components/parameters/sandboxId' }
        - name: after
          in: query
          description: the previous page's `next`
          schema: { type: string, pattern: '^[0-9]{1,20}-[0-9]{1,20}$' }
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 1000, default: 100 }
        - name: format
          in: query
          schema: { type: string, enum: [json, ndjson], default: json }
      responses:
        '200':
          description: a page of the log and its summary, or (format=ndjson) the whole log
          content:
            application/json:
              schema:
                type: object
                required: [events, next, summary]
                properties:
                  events: { type: array, items: { $ref: '#/components/schemas/EgressEvent' } }
                  next:
                    {
                      type: [string, 'null'],
                      description: "the next page's `after`; null at the end",
                    }
                  summary:
                    description: |
                      the whole log's summary, on the first page (no `after`); null on the pages
                      after it, so paging a log through reads it once
                    oneOf:
                      - { $ref: '#/components/schemas/EgressSummary' }
                      - { type: 'null' }
            application/x-ndjson:
              schema: { type: string }
        '400':
          description: '`invalid_request`: a bad after, limit or format'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/NotEnrolled' }
        '404': { $ref: '#/components/responses/NotFound' }
        '503':
          description: redis_unavailable
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/sandboxes/{id}/mode:
    put:
      operationId: setSandboxMode
      summary: Change a sandbox's mode
      description: |
        Owner only, admins included: an admin calling it on another user's sandbox gets the same
        404 as anyone else (sandbox-service spec §4.2). Only the owner's user API token is taken: a sandbox token is
        refused (401). Every accepted call raises `modeEpoch` by 1, the same mode included, and is
        audited as `sandbox_mode_changed` (who, the old mode, the new mode, the epoch). Sandbox
        tokens minted afterwards carry the new mode and epoch. The response's `setModeToken` signs
        that mode and epoch for the client's `LeaseControl set_mode`, through which a downgrade takes
        effect at once (lease-mode spec §8.2). A mode change always counts as activity and slides the
        sandbox's deadline to at least now plus its `idleLifetimeS` (only when
        SH_SANDBOX_MAX_LIFETIME_SECONDS is configured, as for the token mint); a body naming
        `activity` is refused (400).
      security: [{ sessionToken: [] }]
      parameters: [{ $ref: '#/components/parameters/sandboxId' }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [mode]
              properties:
                mode:
                  type: string
                  enum: [per-exec, lease, lease+processes]
                  description: |
                    a lease mode must be listed in SH_SANDBOX_MODES_ALLOWED, else 403
                    `mode_not_allowed`; `per-exec` is always allowed
                idleTimeoutS:
                  type: integer
                  minimum: 30
                  description: |
                    at most SH_SANDBOX_IDLE_CEILING_S. Omit it for the worker's default (stored as
                    0, not the previous value); an explicit 0 is refused (400).
      responses:
        '200':
          description: the sandbox as changed, and a set-mode token for its new epoch
          content:
            application/json:
              schema:
                type: object
                required: [sandbox, setModeToken]
                properties:
                  sandbox: { $ref: '#/components/schemas/Sandbox' }
                  setModeToken:
                    type: string
                    description: 'JWT, typ moca-sandbox-mode+jwt, valid 300 s'
        '400':
          description: '`invalid_json` or `invalid_request` (an unknown mode, an idle timeout out of range)'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403':
          description: '`not_enrolled`, or `mode_not_allowed`: the deployment does not allow that mode'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404': { $ref: '#/components/responses/NotFound' }
        '409':
          description: '`sandbox_terminated`, with `reason` (deleted | expired)'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '503':
          description: redis_unavailable
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/sandboxes/{id}/mode-token:
    post:
      operationId: mintSandboxModeToken
      summary: Mint a set-mode token for the current mode and epoch
      description: |
        Owner only, admins included: an admin calling it on another user's sandbox gets the same
        404 as anyone else (sandbox-service spec §4.2). Only the owner's user API token is taken. Raises nothing:
        it signs the mode and epoch the record holds now, for a client to re-send `LeaseControl
        set_mode` when the worker reports the epoch unknown (lease-mode spec §8.2). The exception
        is a lease mode SH_SANDBOX_MODES_ALLOWED no longer lists: the sandbox is first set to
        `per-exec` at the next epoch, as the sandbox token mint does (§8.1). The `idle_timeout_s`
        claim is clamped to SH_SANDBOX_IDLE_CEILING_S. Like the token mint it slides the sandbox's
        deadline to at least now plus its `idleLifetimeS`, unless the body says `activity: false`
        (a non-boolean `activity` is refused, 400); as there, the deadline moves only when
        SH_SANDBOX_MAX_LIFETIME_SECONDS is configured.
      security: [{ sessionToken: [] }]
      parameters: [{ $ref: '#/components/parameters/sandboxId' }]
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                activity:
                  type: boolean
                  default: true
                  description: >-
                    false: mint without counting as activity (the deadline does not move); for
                    mints that run no command, e.g. a lease keepalive
      responses:
        '400': { $ref: '#/components/responses/BadRequest' }
        '200':
          description: a set-mode token
          content:
            application/json:
              schema:
                type: object
                required: [setModeToken]
                properties:
                  setModeToken:
                    type: string
                    description: 'JWT, typ moca-sandbox-mode+jwt, valid 300 s'
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/NotEnrolled' }
        '404': { $ref: '#/components/responses/NotFound' }
        '409':
          description: '`sandbox_terminated`, with `reason` (deleted | expired)'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '503':
          description: redis_unavailable
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/janitor/sandboxes:
    get:
      operationId: janitorSandboxes
      summary: The host janitor's read -- every live and retained terminated sandbox
      description: |
        Sandbox service control planes only. Authenticated by `SH_JANITOR_TOKEN` alone, never a
        user's token, and refused with none configured (sandbox-service spec §8.3). Carries only what the janitor
        needs to find a workspace tree.
      security: [{ janitorToken: [] }]
      responses:
        '200':
          description: live and terminated sandboxes
          content:
            application/json:
              schema:
                type: object
                required: [live, terminated]
                properties:
                  live:
                    type: array
                    items:
                      type: object
                      required: [wsk, wrk]
                      properties:
                        wsk: { type: string }
                        wrk: { type: string }
                  terminated:
                    type: array
                    items:
                      type: object
                      required: [wsk, wrk, terminatedAt]
                      properties:
                        wsk: { type: string }
                        wrk: { type: string }
                        terminatedAt: { type: integer, description: epoch seconds }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '503':
          description: redis_unavailable
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /v1/egress/credential:
    post:
      operationId: lookupEgressCredential
      summary: moca-egress's owner lookup -- ready header values for a sandbox's outbound host
      description: |
        Sandbox service control planes with egress credentials configured only. Authenticated by
        a KVM host's egress token. Returns the sandbox OWNER's `sandbox-egress` credentials whose
        destination matches `host`, rendered to header values, sorted by port, then path prefix
        length descending, then name. Header values are never logged or audited (egress-credentials spec §4.2).
      security: [{ egress: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [sandbox, host]
              properties:
                sandbox: { type: string, pattern: '^sbx-[0-9a-f]{26}$' }
                host: { type: string, pattern: '^[A-Za-z0-9.-]{1,253}$' }
      responses:
        '200':
          description: the credentials for the host
          content:
            application/json:
              schema:
                type: object
                required: [subject, ttlSeconds, credentials]
                properties:
                  subject: { type: string }
                  ttlSeconds: { type: integer, minimum: 5 }
                  credentials:
                    type: array
                    items:
                      type: object
                      required: [name, port, pathPrefix, headers, expiresAt]
                      properties:
                        name: { type: string }
                        port: { type: integer }
                        pathPrefix: { type: string }
                        headers:
                          type: array
                          items:
                            type: object
                            required: [name, value]
                            properties:
                              name: { type: string }
                              value: { type: string }
                        expiresAt: { type: [string, 'null'], format: date-time }
        '400':
          description: invalid_request (bad sandbox id or host)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '404':
          description: "`sandbox_not_found` (unknown, terminated or another host's) or `no_credential`"
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '500':
          description: '`destination_ambiguous` or `credential_unsafe`'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '503':
          description: redis_unavailable
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /internal/credentials:
    post:
      operationId: exchangeCredential
      summary: Data-plane only — exchange a session token for that subject's credential
      description: |
        Not part of the public surface. Authenticated by the shared `SH_EXCHANGE_TOKEN`, fail-closed
        with none configured (spec §5.3.1). Puts the control plane on the CONTROL path once per turn,
        never on the data path: it sees no prompt and no model output.
      security: [{ exchangeToken: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [token]
              properties:
                token: { type: string, description: the session token presented by the caller }
      responses:
        '200':
          description: the resolved credential
          content:
            application/json:
              schema:
                type: object
                required: [mode, anthropicAuthToken, anthropicBaseUrl, sessionId, subject]
                properties:
                  mode:
                    type: string
                    enum: [placeholder, direct]
                    description: |
                      `placeholder` when the deployment has an injector to rewrite it; `direct` (MU1's
                      interim mode) when none is configured. Tagged, because a mislabelled credential
                      fails silently in both directions (spec §3.6).
                  anthropicAuthToken: { type: string }
                  anthropicBaseUrl:
                    { type: string, description: never absent — see endpoint_unresolved }
                  sessionId: { type: string }
                  subject: { type: string }
                  configRef:
                    { type: string, description: present only when the session has a config bundle }
                  sandboxTier:
                    type: string
                    description: |
                      the tier the session's turn runs in (P6.3): the recorded tier, or today's
                      default for a session that recorded none; absent whenever the deployment
                      declares no tiers, even for a session that recorded one
                  sandboxTemplate:
                    type: string
                    description: |
                      the sandbox template the session named at creation; the data plane runs the
                      turn only on workers labelled moca.dev/template with it. Absent when the
                      session named none. Sent even when the deployment no longer declares it, so
                      the turn is refused rather than run on an untemplated worker (fail closed)
                  sandboxSeed:
                    type: string
                    description: |
                      the template's seed, a bash command the data plane runs once per workspace;
                      present only beside sandboxTemplate. For a session pinned to a manifest-hash
                      build through the template store, that build's own `spec.seed` (none when the
                      build has none); otherwise the deployment's declared seed, while it declares one
                  sandboxSeedSource:
                    type: string
                    enum: [build, declared]
                    description: |
                      where sandboxSeed came from, sent with it: `build` (the pinned build's spec) or
                      `declared` (SH_SANDBOX_TEMPLATES). The turn reports it as `sandbox.seed`
                  sandboxBuildId:
                    type: string
                    pattern: '^sha256:[0-9a-f]{64}$'
                    description: |
                      the manifest-hash build the session's template resolved to at creation
                      (combined control plane spec §3.4); the data plane runs the turn only on
                      workers labelled moca.dev/build with it, and refuses it when none is
                      attached. Present only beside sandboxTemplate, for a manifest-hash build
                  model:
                    type: object
                    description: |
                      the session's model and the limits recorded when it was chosen; absent when
                      the session names none (the data plane then uses its deployment default)
                    required: [id]
                    properties:
                      id: { type: string }
                      contextWindow: { type: integer }
                      maxTokens: { type: integer }
                      reasoning: { type: boolean }
                      vision: { type: boolean }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '404': { $ref: '#/components/responses/NotFound' }
  /internal/turn-credentials:
    post:
      operationId: exchangeTurnCredential
      summary: Data-plane only — resolve a queued turn's credential at dequeue
      description: |
        Not part of the public surface, and the DEQUEUE counterpart of `/internal/credentials`
        (async fan-out spec §5.4). Same shared `SH_EXCHANGE_TOKEN`, same fail-closed-with-none-
        configured rule, same once-per-turn position on the control path. It differs in what the
        caller presents: a turn id, not a session token, because at dequeue no session token exists
        and putting a credential or a bearer in the work queue is what MI1 §6.5 forbids. The id alone
        is sufficient because everything else comes from the turn record the control plane wrote at
        the authenticated enqueue.

        What it returns depends on the deployment's tenancy, and nothing else. Under
        `MOCA_TENANCY=single` it returns the credential resolved from the record (`mode: direct` or
        `placeholder`). Under `multi` it returns MI1 §6.1 **grants** (`mode: grant`) and never a
        credential value: `anthropicAuthToken` is the inference grant, `anthropicBaseUrl` is the
        deployment's inference listener, and `sandboxGrant` comes with them. Under
        `multi` the deployment must configure the grant ring and the listener or the control plane
        refuses to boot -- which is what replaces M1's per-request `501` (ADR-0047).

        The call is a pure READ. It does not move the turn to `running` — the consumer does that,
        because it holds the delivery count the transition records, and because a deployment-wide
        shared bearer must not be able to mutate turn state.
      security: [{ exchangeToken: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [turnId]
              properties:
                turnId:
                  type: string
                  pattern: '^t-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'
                  description: |
                    the id the worker read off the queue, and the ONLY thing the queue carries. The
                    pattern is the one `submitTurn` mints, and it is enforced (400), not advisory.
      responses:
        '200':
          description: the credential this turn spends, resolved from its record
          content:
            application/json:
              schema:
                type: object
                required:
                  [
                    turnId,
                    mode,
                    anthropicAuthToken,
                    anthropicBaseUrl,
                    sessionId,
                    subject,
                    caps,
                    envelope,
                  ]
                properties:
                  turnId:
                    type: string
                    description: echoed, so a response cannot be misattributed to another claim
                  mode:
                    type: string
                    enum: [placeholder, direct, grant]
                    description: |
                      as on /internal/credentials: `placeholder` when the deployment has an injector
                      to rewrite it, `direct` when none is configured. `direct` is reachable only
                      under `MOCA_TENANCY=single` (MI1 §6.6).

                      `grant` is the only mode under `MOCA_TENANCY=multi`, and `direct`/`placeholder`
                      the only modes under `single`: the tenancy picks it, never the caller.
                  anthropicAuthToken: { type: string }
                  anthropicBaseUrl:
                    { type: string, description: never absent — see endpoint_unresolved }
                  sessionId:
                    type: string
                    description: the session the turn belongs to, from the record
                  subject: { type: string }
                  caps:
                    type: object
                    description: |
                      the per-turn budget ceilings recorded at submission, returned so a worker can
                      enforce them without re-reading the record (#391). Empty when the submission
                      named none. `tokens` is enforced inside the run; `wallClock` is not read by the
                      worker at all -- it is already resolved into `turnExp` below.
                    properties:
                      tokens: { type: integer }
                      wallClock: { type: integer, description: seconds }
                  envelope:
                    type: object
                    description: |
                      the leaf the worker runs, exactly as recorded at submission, with the turn's
                      `sessionId` attached. Returned here rather than from a second internal route
                      because this handler has already read the record. It carries no credential and
                      no bearer token: the record stores a credential NAME, and not in the envelope.
                    required: [sessionId]
                    properties:
                      sessionId: { type: string }
                    additionalProperties: true
                  authHeader:
                    type: string
                    enum: [x-api-key]
                    description: |
                      present only when the credential must be sent as `x-api-key` rather than as a
                      bearer; omitting it would make the worker 401 against the endpoint. Never
                      present in `grant` mode: the listener sends whichever header the credential's
                      binding names, so the worker always presents a bearer.
                  sandboxGrant:
                    type: string
                    description: |
                      the `moca-sandbox` half of MI1 §6.1's pair, present only in `grant` mode. Not
                      spent by the worker itself -- it is what a sandbox presents to the egress proxy
                      -- and carried here because the worker is the only thing holding the turn.
                  turnExp:
                    type: integer
                    description: |
                      unix seconds: the absolute end of THIS DELIVERY, anchored at the DEQUEUE and
                      clamped to `min(caps.wallClock, MOCA_TURN_MAX_S)`. In `grant` mode both grants
                      expire at it and no refresh extends past it.

                      Per delivery, not per turn, because it is anchored at each dequeue: a
                      redelivery after a worker died mid-leaf gets a fresh window, since its grants
                      are minted here too and a deadline it had already passed would make the turn
                      unrunnable rather than merely capped. See `caps` on the submission route for
                      the aggregate this allows (the cap times the delivery limit).

                      Returned in EVERY mode since #391, because it is also the deadline the worker
                      enforces: it stops the leaf at this instant and ends the turn `failed` with
                      `result.reason: "budget"`. `caps.wallClock` is never re-resolved by the worker,
                      so a mode that omitted this would have an unenforceable wall-clock cap.
                  configRef:
                    { type: string, description: present only when the turn named a config bundle }
                  sandboxTier:
                    type: string
                    description: |
                      the tier this turn runs in: the tier the TURN RECORD pinned at submission,
                      which is the session's stored tier and so already resolved against the
                      deployment's default as it stood when the session was created. A record that
                      pinned none is resolved against the session instead. Absent whenever the
                      deployment declares no tiers.
                  sandboxTemplate:
                    type: string
                    description: |
                      as on /internal/credentials: the session's sandbox template, so a queued turn
                      of a templated session runs only on its workers (session-templates spec §5.2).
                      From the session, whose template and build are written once, at creation.
                      Sent even when the deployment no longer declares it (fail closed)
                  sandboxSeed:
                    type: string
                    description: as on /internal/credentials; only beside sandboxTemplate
                  sandboxSeedSource:
                    type: string
                    enum: [build, declared]
                    description: as on /internal/credentials; only beside sandboxSeed
                  sandboxBuildId:
                    type: string
                    pattern: '^sha256:[0-9a-f]{64}$'
                    description: |
                      as on /internal/credentials: the build the session is pinned to; only beside
                      sandboxTemplate, for a manifest-hash build
                  model:
                    type: object
                    description: |
                      the model the TURN RECORD pinned at submission, with the limits recorded when
                      it was chosen; absent when the submission named none, and the worker then uses
                      its deployment default. Pinned, so switching the session's model while this
                      turn is still queued does not move it onto the new one.
                    required: [id]
                    properties:
                      id: { type: string }
                      contextWindow: { type: integer }
                      maxTokens: { type: integer }
                      reasoning: { type: boolean }
                      vision: { type: boolean }
        '400':
          description: |
            `invalid_request`: the body carries no `turnId`, or one outside the `t-<uuid>` shape
            `submitTurn` mints. Refused before Redis is touched, so no caller input picks the key
            shape this route reads. A worker seeing it should ack its entry and drop it — the id on
            the queue is corrupt and no retry can fix it.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '404':
          description: |
            `turn_not_found` for an id with no record, and `session_not_found` when the turn's session
            is gone, tombstoned, or owned by someone else. A worker seeing either should ack its queue
            entry and drop it — retrying cannot help.

            The two codes are distinguishable, deliberately: a worker needs `turn_not_found` apart from
            `session_not_found` (and both apart from 409 `turn_not_claimable`, whose message names the
            state) to record why it dropped an entry. That costs nothing here, because every caller on
            this route authenticated with the deployment-wide `SH_EXCHANGE_TOKEN` and a successful call
            hands back the credential itself — so no refusal reveals anything the same caller could not
            already obtain. This is NOT the 404-rather-than-403 rule of spec §8.1, which governs the
            owner-scoped `/v1` routes a session token reaches.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '409':
          description: |
            `turn_not_claimable`: the record exists but is `cancelled` or already terminal, so no
            credential is minted (§5.4). This is what makes `DELETE …/turns/{turnId}` effective —
            cancel flips the record and never reaches into the queue. NEVER returned for a `running`
            record: a redelivery is the case the claim exists for.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '500':
          description: |
            `internal_error`: the audit write failed with an untyped error, or the turn store is not
            wired. Not retryable the way the 503s below are — this is a bug, not an outage.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '503':
          description: |
            `redis_unavailable` when the record cannot be read, or `credential_unavailable` when the
            credential store cannot be reached. Retryable, unlike the 404.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /internal/turn-grants:
    post:
      operationId: issueTurnGrants
      summary: Data-plane only — mint a turn's two session grants
      description: |
        Not part of the public surface. MI1 §6.2's turn-start call: the worker presents the session
        token it was handed with the turn plus the shared `SH_EXCHANGE_TOKEN`, and receives the
        turn's two grants.

        A GRANT IS NOT A CREDENTIAL. It is a short-lived signed capability that must be spent at an
        enforcement point — `cred` names the session's inference credential and `egress` lists its
        `sandbox-egress` credential names (§7.2); no secret value is ever returned. That is the
        difference from `/internal/credentials`, which §6.2 says this route eventually replaces.

        **Mounted only when `MOCA_GRANT_SIGNING_KEY` is configured.** Without it the path is
        genuinely unrouted and answers `404 not_found` before the body is parsed (ADR-0045).
        The INFERENCE grant is redeemed at the control plane's own inference listener
        (`MOCA_INFERENCE_ADDR`), which swaps it for the session's credential, and
        `/internal/turn-credentials` returns a pair of its own under `MOCA_TENANCY=multi`. The
        SANDBOX grant still has no redeemer: the `moca-egress` CONNECT path and `/internal/token`
        (§6.3, §8.6) are later slices. `/internal/credentials` stays exactly as it is.
      security: [{ exchangeToken: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [token]
              properties:
                token:
                  type: string
                  description: |
                    the SESSION token presented by the caller. An api token is refused with
                    `token_invalid`: the grants are about one session, and a session token is the
                    only kind that names one.
      responses:
        '200':
          description: the turn's two grants
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TurnGrants' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '404':
          description: |
            `session_not_found` for an unknown session, a session the presented token's subject does
            not own, and a tombstoned one — one answer for all three, so this route is no more of an
            existence oracle than `/internal/credentials`. Also a bare `not_found` when the
            deployment configured no grant signing key, in which case the path is not mounted.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '500':
          description: |
            `internal_error`: the audit write failed with an untyped error. The grant is refused
            rather than issued off the books — that audit entry is the only record a capability
            left the control plane.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '503':
          description: '`redis_unavailable`: the session record or the audit stream is unreachable.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
  /internal/grants/refresh:
    post:
      operationId: refreshTurnGrants
      summary: Data-plane only — re-mint a turn's grants with a later expiry
      description: |
        Not part of the public surface. MI1 §6.2's mid-turn call: the worker presents a grant it
        already holds — either audience — plus the shared `SH_EXCHANGE_TOKEN`, and receives both
        halves again with a new `exp`. Workers refresh at half-life.

        `turnExp` is carried forward UNCHANGED, because it is an absolute cap: refreshing cannot
        extend a turn no matter how many times it happens. Past `turnExp` the refresh is refused
        outright rather than clamped, and a tombstoned session stops refreshing (§6.2).

        The claims are re-derived from the session record rather than copied from the presented
        grant. §6.2 says "same claims, new exp", but an inference grant carries no `cfg`/`egress`
        and a sandbox grant no `cred`, so echoing cannot reconstruct the other half — and
        re-reading makes a mid-turn credential or bundle change take effect at the next refresh,
        which is strictly tighter.

        **Mounted only when `MOCA_GRANT_SIGNING_KEY` is configured**, as above.
      security: [{ exchangeToken: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [grant]
              properties:
                grant:
                  type: string
                  description: |
                    either of the turn's current grants. A separate field from the issue route's
                    `token` deliberately: the two carry different credentials to different
                    verifiers, and a worker that confused them gets an `invalid_request` naming the
                    field rather than a `grant_invalid` naming nothing.
      responses:
        '200':
          description: the same two grants with a new `exp` and an unchanged `turnExp`
          content:
            application/json:
              schema: { $ref: '#/components/schemas/TurnGrants' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401':
          description: |
            `unauthorized` when the shared bearer is missing or wrong. `grant_invalid` for EVERY way
            the presented grant can fail: bad signature, `alg: none` or any non-EdDSA alg, wrong
            `typ` (a session token presented here), wrong `aud`, unknown `kid`, past `exp`, or past
            `turnExp`. One code on purpose (§6.3): the caller's only move on any of them is to
            re-exchange at `/internal/turn-grants`, so splitting the code the way the session
            token's `token_invalid`/`token_expired` are split would buy a caller nothing. The
            `message` does name the failed check, for the operator reading the log — the route is
            behind the shared bearer, so no untrusted holder of a tampered grant reaches it.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: |
            `session_not_found` for an unknown, unowned or tombstoned session — the same answer the
            issue route gives. Also a bare `not_found` when no grant signing key is configured.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '500':
          description: '`internal_error`: the audit write failed with an untyped error.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '503':
          description: '`redis_unavailable`: the session record or the audit stream is unreachable.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
